<?php
// admin/users.php - Admin User Management (SQLite version)
require_once '../config.php';
requireAdmin();

$pdo = getDBConnection();
$error = '';
$success = '';

// Handle user actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Add new user
    if (isset($_POST['add_user'])) {
        $username = trim($_POST['username']);
        $email = trim($_POST['email']);
        $password = $_POST['password'];
        $full_name = trim($_POST['full_name']);
        $is_admin = isset($_POST['is_admin']) ? 1 : 0;
        $is_active = isset($_POST['is_active']) ? 1 : 0;
        $organization_id = $_POST['organization_id'] ?: null;
        
        if (empty($username) || empty($email) || empty($password)) {
            $error = "Username, email, and password are required";
        } else {
            try {
                $password_hash = hash('sha256', $password);
                $stmt = $pdo->prepare("
                    INSERT INTO users (username, email, password_hash, full_name, is_admin, is_active, organization_id) 
                    VALUES (?, ?, ?, ?, ?, ?, ?)
                ");
                $stmt->execute([$username, $email, $password_hash, $full_name, $is_admin, $is_active, $organization_id]);
                $success = "User '$username' added successfully";
            } catch (Exception $e) {
                $error = "Failed to add user: " . $e->getMessage();
            }
        }
    }
    
    // Edit user
    if (isset($_POST['edit_user'])) {
        $user_id = $_POST['user_id'];
        $username = trim($_POST['username']);
        $email = trim($_POST['email']);
        $full_name = trim($_POST['full_name']);
        $is_admin = isset($_POST['is_admin']) ? 1 : 0;
        $is_active = isset($_POST['is_active']) ? 1 : 0;
        $organization_id = $_POST['organization_id'] ?: null;
        
        try {
            $stmt = $pdo->prepare("
                UPDATE users 
                SET username = ?, email = ?, full_name = ?, is_admin = ?, is_active = ?, organization_id = ?
                WHERE id = ?
            ");
            $stmt->execute([$username, $email, $full_name, $is_admin, $is_active, $organization_id, $user_id]);
            
            // Update password if provided
            if (!empty($_POST['new_password'])) {
                $new_password_hash = hash('sha256', $_POST['new_password']);
                $stmt = $pdo->prepare("UPDATE users SET password_hash = ? WHERE id = ?");
                $stmt->execute([$new_password_hash, $user_id]);
            }
            
            $success = "User updated successfully";
        } catch (Exception $e) {
            $error = "Failed to update user: " . $e->getMessage();
        }
    }
    
    // Delete user
    if (isset($_POST['delete_user'])) {
        $user_id = $_POST['user_id'];
        
        // Don't allow deleting own account
        if ($user_id == $_SESSION['user_id']) {
            $error = "You cannot delete your own account";
        } else {
            try {
                $stmt = $pdo->prepare("DELETE FROM users WHERE id = ?");
                $stmt->execute([$user_id]);
                $success = "User deleted successfully";
            } catch (Exception $e) {
                $error = "Failed to delete user: " . $e->getMessage();
            }
        }
    }
    
    // Toggle user status
    if (isset($_POST['toggle_status'])) {
        $user_id = $_POST['user_id'];
        $current_status = $_POST['current_status'];
        $new_status = $current_status == 1 ? 0 : 1;
        
        try {
            $stmt = $pdo->prepare("UPDATE users SET is_active = ? WHERE id = ?");
            $stmt->execute([$new_status, $user_id]);
            $success = "User status updated";
        } catch (Exception $e) {
            $error = "Failed to update status";
        }
    }
}

// Get all users with their organizations
$users = $pdo->query("
    SELECT u.*, o.name as organization_name 
    FROM users u 
    LEFT JOIN organizations o ON u.organization_id = o.id 
    ORDER BY u.created_at DESC
")->fetchAll();

// Get all organizations for dropdown
$organizations = $pdo->query("SELECT id, name FROM organizations ORDER BY name")->fetchAll();

// Get statistics (SQLite compatible)
$totalUsers = $pdo->query("SELECT COUNT(*) FROM users")->fetchColumn();
$activeUsers = $pdo->query("SELECT COUNT(*) FROM users WHERE is_active = 1")->fetchColumn();
$adminUsers = $pdo->query("SELECT COUNT(*) FROM users WHERE is_admin = 1")->fetchColumn();

// SQLite compatible today's users
$todayUsers = $pdo->query("SELECT COUNT(*) FROM users WHERE DATE(created_at) = DATE('now')")->fetchColumn();

$theme = getTheme();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin - User Management | Soul Guard</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        :root {
            --bg-primary: #0a0a0f;
            --bg-secondary: #13131a;
            --bg-card: rgba(255, 255, 255, 0.03);
            --border-color: rgba(255, 255, 255, 0.06);
            --text-primary: #e4e4e7;
            --text-secondary: #a1a1aa;
            --accent-blue: #3b82f6;
            --accent-red: #ef4444;
            --accent-green: #22c55e;
            --accent-yellow: #eab308;
            --accent-purple: #a855f7;
            --accent-cyan: #06b6d4;
            --accent-orange: #f97316;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: var(--bg-primary);
            color: var(--text-primary);
            min-height: 100vh;
            background-image: radial-gradient(ellipse at top, rgba(59, 130, 246, 0.08), transparent 50%);
        }

        /* Navigation */
        .navbar {
            background: var(--bg-secondary);
            border-bottom: 1px solid var(--border-color);
            padding: 0 30px;
            height: 65px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            position: sticky;
            top: 0;
            z-index: 100;
        }

        .logo {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .logo-icon {
            width: 40px;
            height: 40px;
            background: linear-gradient(135deg, #3b82f6, #a855f7);
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 20px;
        }

        .logo-text h1 {
            font-size: 18px;
            font-weight: 700;
            background: linear-gradient(135deg, #3b82f6, #a855f7);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }

        .logo-text small {
            font-size: 10px;
            color: var(--text-secondary);
        }

        .nav-links {
            display: flex;
            align-items: center;
            gap: 5px;
            flex-wrap: wrap;
        }

        .nav-links a {
            color: var(--text-secondary);
            text-decoration: none;
            padding: 8px 14px;
            border-radius: 8px;
            font-size: 13px;
            font-weight: 500;
            transition: all 0.2s;
        }

        .nav-links a:hover {
            background: rgba(255, 255, 255, 0.05);
            color: var(--text-primary);
        }

        .nav-links a.active {
            background: rgba(59, 130, 246, 0.15);
            color: var(--accent-blue);
        }

        .user-badge {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 6px 12px;
            background: rgba(255, 255, 255, 0.05);
            border-radius: 20px;
            font-size: 12px;
            margin-left: 10px;
        }

        .user-avatar {
            width: 28px;
            height: 28px;
            background: linear-gradient(135deg, #3b82f6, #a855f7);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
            font-weight: 700;
            color: white;
        }

        .logout-btn {
            background: rgba(239, 68, 68, 0.1) !important;
            color: var(--accent-red) !important;
            border: 1px solid rgba(239, 68, 68, 0.2);
        }

        .container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 30px;
        }

        /* Header */
        .page-header {
            margin-bottom: 30px;
        }

        .page-header h1 {
            font-size: 28px;
            margin-bottom: 8px;
        }

        .page-header p {
            color: var(--text-secondary);
            font-size: 14px;
        }

        /* Stats Grid */
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
            gap: 15px;
            margin-bottom: 30px;
        }

        .stat-card {
            background: var(--bg-card);
            border: 1px solid var(--border-color);
            border-radius: 16px;
            padding: 20px;
            text-align: center;
            transition: all 0.3s;
        }

        .stat-card:hover {
            transform: translateY(-2px);
            background: rgba(255, 255, 255, 0.05);
        }

        .stat-number {
            font-size: 32px;
            font-weight: 800;
            color: var(--accent-cyan);
        }

        .stat-label {
            font-size: 11px;
            color: var(--text-secondary);
            text-transform: uppercase;
            margin-top: 8px;
        }

        /* Buttons */
        .btn {
            display: inline-block;
            padding: 10px 20px;
            background: linear-gradient(135deg, #06b6d4, #14b8a6);
            color: white;
            text-decoration: none;
            border-radius: 8px;
            transition: all 0.3s;
            font-size: 13px;
            font-weight: 600;
            border: none;
            cursor: pointer;
        }

        .btn-primary {
            background: linear-gradient(135deg, #06b6d4, #14b8a6);
        }

        .btn-danger {
            background: linear-gradient(135deg, #ef4444, #dc2626);
        }

        .btn-warning {
            background: linear-gradient(135deg, #f59e0b, #d97706);
        }

        .btn-sm {
            padding: 5px 10px;
            font-size: 11px;
        }

        .btn-outline {
            background: transparent;
            border: 1px solid var(--accent-cyan);
            color: var(--accent-cyan);
        }

        .btn-outline:hover {
            background: rgba(6, 182, 212, 0.1);
        }

        /* Table */
        .table-container {
            background: var(--bg-card);
            border: 1px solid var(--border-color);
            border-radius: 16px;
            overflow-x: auto;
        }

        table {
            width: 100%;
            border-collapse: collapse;
        }

        th, td {
            padding: 14px 12px;
            text-align: left;
            border-bottom: 1px solid var(--border-color);
        }

        th {
            background: rgba(255, 255, 255, 0.03);
            color: var(--accent-cyan);
            font-weight: 600;
            font-size: 13px;
        }

        td {
            font-size: 13px;
        }

        /* Badges */
        .badge {
            display: inline-block;
            padding: 4px 10px;
            border-radius: 20px;
            font-size: 11px;
            font-weight: 600;
        }

        .badge-admin {
            background: rgba(168, 85, 247, 0.2);
            color: #c4b5fd;
        }

        .badge-user {
            background: rgba(59, 130, 246, 0.2);
            color: #93c5fd;
        }

        .badge-active {
            background: rgba(34, 197, 94, 0.2);
            color: #86efac;
        }

        .badge-inactive {
            background: rgba(239, 68, 68, 0.2);
            color: #fca5a5;
        }

        /* Modal */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.95);
            z-index: 1000;
            justify-content: center;
            align-items: center;
        }

        .modal-content {
            background: var(--bg-secondary);
            border: 1px solid var(--border-color);
            border-radius: 16px;
            padding: 30px;
            max-width: 500px;
            width: 90%;
            max-height: 85vh;
            overflow-y: auto;
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid var(--border-color);
        }

        .modal-header h3 {
            color: var(--accent-cyan);
        }

        .modal-close {
            cursor: pointer;
            font-size: 24px;
            color: var(--text-secondary);
        }

        .modal-close:hover {
            color: var(--accent-red);
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-size: 12px;
            color: var(--text-secondary);
            font-weight: 500;
        }

        .form-group input, .form-group select {
            width: 100%;
            padding: 10px 12px;
            background: rgba(0, 0, 0, 0.3);
            border: 1px solid var(--border-color);
            border-radius: 8px;
            color: var(--text-primary);
            font-size: 13px;
        }

        .form-group input:focus, .form-group select:focus {
            outline: none;
            border-color: var(--accent-cyan);
        }

        .checkbox-group {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .checkbox-group input {
            width: auto;
        }

        .form-buttons {
            display: flex;
            gap: 10px;
            justify-content: flex-end;
            margin-top: 20px;
        }

        .alert {
            padding: 12px 16px;
            border-radius: 8px;
            margin-bottom: 20px;
            font-size: 13px;
        }

        .alert-success {
            background: rgba(34, 197, 94, 0.1);
            border: 1px solid rgba(34, 197, 94, 0.3);
            color: #86efac;
        }

        .alert-error {
            background: rgba(239, 68, 68, 0.1);
            border: 1px solid rgba(239, 68, 68, 0.3);
            color: #fca5a5;
        }

        .action-buttons {
            display: flex;
            gap: 5px;
            flex-wrap: wrap;
        }

        .empty-state {
            text-align: center;
            padding: 60px;
            color: var(--text-secondary);
        }

        @media (max-width: 768px) {
            .container {
                padding: 15px;
            }
            .stats-grid {
                grid-template-columns: repeat(2, 1fr);
            }
            th, td {
                padding: 8px;
                font-size: 11px;
            }
            .action-buttons {
                flex-direction: column;
            }
        }
    </style>
</head>
<body>
    <nav class="navbar">
        <div class="logo">
            <div class="logo-icon">🛡️</div>
            <div class="logo-text">
                <h1>Soul Guard Admin</h1>
                <small>User Management</small>
            </div>
        </div>
        <div class="nav-links">
            <a href="index.php">📊 Dashboard</a>
            <a href="users.php" class="active">👥 Users</a>
            <a href="services.php">📋 Services</a>
            <a href="reports.php">📄 Reports</a>
            <span class="user-badge">
                <div class="user-avatar"><?php echo strtoupper(substr($_SESSION['username'], 0, 1)); ?></div>
                <?php echo htmlspecialchars($_SESSION['username']); ?>
            </span>
            <a href="../index.php?logout=1" class="logout-btn">🚪 Logout</a>
        </div>
    </nav>

    <div class="container">
        <div class="page-header">
            <h1>👥 User Management</h1>
            <p>Manage system users, roles, and permissions</p>
        </div>

        <?php if ($success): ?>
        <div class="alert alert-success">✅ <?php echo htmlspecialchars($success); ?></div>
        <?php endif; ?>

        <?php if ($error): ?>
        <div class="alert alert-error">❌ <?php echo htmlspecialchars($error); ?></div>
        <?php endif; ?>

        <!-- Statistics -->
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-number"><?php echo $totalUsers; ?></div>
                <div class="stat-label">Total Users</div>
            </div>
            <div class="stat-card">
                <div class="stat-number"><?php echo $activeUsers; ?></div>
                <div class="stat-label">Active Users</div>
            </div>
            <div class="stat-card">
                <div class="stat-number"><?php echo $adminUsers; ?></div>
                <div class="stat-label">Administrators</div>
            </div>
            <div class="stat-card">
                <div class="stat-number">+<?php echo $todayUsers; ?></div>
                <div class="stat-label">New Today</div>
            </div>
        </div>

        <!-- Add User Button -->
        <div style="margin-bottom: 20px; text-align: right;">
            <button class="btn" onclick="openAddModal()">➕ Add New User</button>
        </div>

        <!-- Users Table -->
        <div class="table-container">
            <table>
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Username</th>
                        <th>Email</th>
                        <th>Full Name</th>
                        <th>Organization</th>
                        <th>Role</th>
                        <th>Status</th>
                        <th>Joined</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if(empty($users)): ?>
                    <tr>
                        <td colspan="9" class="empty-state">No users found</td>
                    </tr>
                    <?php else: ?>
                        <?php foreach($users as $user): ?>
                        <tr>
                            <td>#<?php echo $user['id']; ?></td>
                            <td><?php echo htmlspecialchars($user['username']); ?></td>
                            <td><?php echo htmlspecialchars($user['email']); ?></td>
                            <td><?php echo htmlspecialchars($user['full_name'] ?: '-'); ?></td>
                            <td><?php echo htmlspecialchars($user['organization_name'] ?: '-'); ?></td>
                            <td>
                                <?php if($user['is_admin']): ?>
                                <span class="badge badge-admin">👑 Admin</span>
                                <?php else: ?>
                                <span class="badge badge-user">👤 User</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php if($user['is_active']): ?>
                                <span class="badge badge-active">✅ Active</span>
                                <?php else: ?>
                                <span class="badge badge-inactive">❌ Inactive</span>
                                <?php endif; ?>
                            </td>
                            <td><?php echo date('M d, Y', strtotime($user['created_at'])); ?></td>
                            <td class="action-buttons">
                                <button class="btn btn-sm btn-outline" onclick='openEditModal(<?php echo json_encode($user); ?>)'>✏️ Edit</button>
                                <?php if($user['id'] != $_SESSION['user_id']): ?>
                                <button class="btn btn-sm btn-warning" onclick="toggleStatus(<?php echo $user['id']; ?>, <?php echo $user['is_active']; ?>)">
                                    <?php echo $user['is_active'] ? '🔴 Deactivate' : '🟢 Activate'; ?>
                                </button>
                                <button class="btn btn-sm btn-danger" onclick="confirmDelete(<?php echo $user['id']; ?>, '<?php echo htmlspecialchars($user['username']); ?>')">🗑️ Delete</button>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <!-- Add User Modal -->
    <div id="addModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>➕ Add New User</h3>
                <span class="modal-close" onclick="closeAddModal()">&times;</span>
            </div>
            <form method="POST" action="">
                <input type="hidden" name="add_user" value="1">
                
                <div class="form-group">
                    <label>Username *</label>
                    <input type="text" name="username" required>
                </div>
                
                <div class="form-group">
                    <label>Email *</label>
                    <input type="email" name="email" required>
                </div>
                
                <div class="form-group">
                    <label>Password *</label>
                    <input type="password" name="password" required>
                </div>
                
                <div class="form-group">
                    <label>Full Name</label>
                    <input type="text" name="full_name">
                </div>
                
                <div class="form-group">
                    <label>Organization</label>
                    <select name="organization_id">
                        <option value="">-- None --</option>
                        <?php foreach($organizations as $org): ?>
                        <option value="<?php echo $org['id']; ?>"><?php echo htmlspecialchars($org['name']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="form-group checkbox-group">
                    <input type="checkbox" name="is_admin" id="is_admin_add">
                    <label for="is_admin_add">Administrator Privileges</label>
                </div>
                
                <div class="form-group checkbox-group">
                    <input type="checkbox" name="is_active" id="is_active_add" checked>
                    <label for="is_active_add">Active Account</label>
                </div>
                
                <div class="form-buttons">
                    <button type="submit" class="btn">Create User</button>
                    <button type="button" class="btn btn-outline" onclick="closeAddModal()">Cancel</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Edit User Modal -->
    <div id="editModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>✏️ Edit User</h3>
                <span class="modal-close" onclick="closeEditModal()">&times;</span>
            </div>
            <form method="POST" action="">
                <input type="hidden" name="edit_user" value="1">
                <input type="hidden" name="user_id" id="edit_user_id">
                
                <div class="form-group">
                    <label>Username *</label>
                    <input type="text" name="username" id="edit_username" required>
                </div>
                
                <div class="form-group">
                    <label>Email *</label>
                    <input type="email" name="email" id="edit_email" required>
                </div>
                
                <div class="form-group">
                    <label>New Password (leave blank to keep current)</label>
                    <input type="password" name="new_password">
                </div>
                
                <div class="form-group">
                    <label>Full Name</label>
                    <input type="text" name="full_name" id="edit_full_name">
                </div>
                
                <div class="form-group">
                    <label>Organization</label>
                    <select name="organization_id" id="edit_organization_id">
                        <option value="">-- None --</option>
                        <?php foreach($organizations as $org): ?>
                        <option value="<?php echo $org['id']; ?>"><?php echo htmlspecialchars($org['name']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="form-group checkbox-group">
                    <input type="checkbox" name="is_admin" id="edit_is_admin">
                    <label for="edit_is_admin">Administrator Privileges</label>
                </div>
                
                <div class="form-group checkbox-group">
                    <input type="checkbox" name="is_active" id="edit_is_active">
                    <label for="edit_is_active">Active Account</label>
                </div>
                
                <div class="form-buttons">
                    <button type="submit" class="btn">Save Changes</button>
                    <button type="button" class="btn btn-outline" onclick="closeEditModal()">Cancel</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Delete Confirmation Form -->
    <form id="deleteForm" method="POST" action="">
        <input type="hidden" name="delete_user" value="1">
        <input type="hidden" name="user_id" id="delete_user_id">
    </form>

    <!-- Toggle Status Form -->
    <form id="toggleForm" method="POST" action="">
        <input type="hidden" name="toggle_status" value="1">
        <input type="hidden" name="user_id" id="toggle_user_id">
        <input type="hidden" name="current_status" id="toggle_current_status">
    </form>

    <script>
        // Add User Modal
        function openAddModal() {
            document.getElementById('addModal').style.display = 'flex';
        }
        
        function closeAddModal() {
            document.getElementById('addModal').style.display = 'none';
        }
        
        // Edit User Modal
        function openEditModal(user) {
            document.getElementById('edit_user_id').value = user.id;
            document.getElementById('edit_username').value = user.username;
            document.getElementById('edit_email').value = user.email;
            document.getElementById('edit_full_name').value = user.full_name || '';
            document.getElementById('edit_organization_id').value = user.organization_id || '';
            document.getElementById('edit_is_admin').checked = user.is_admin == 1;
            document.getElementById('edit_is_active').checked = user.is_active == 1;
            document.getElementById('editModal').style.display = 'flex';
        }
        
        function closeEditModal() {
            document.getElementById('editModal').style.display = 'none';
        }
        
        // Toggle Status
        function toggleStatus(userId, currentStatus) {
            if (confirm('Are you sure you want to ' + (currentStatus == 1 ? 'deactivate' : 'activate') + ' this user?')) {
                document.getElementById('toggle_user_id').value = userId;
                document.getElementById('toggle_current_status').value = currentStatus;
                document.getElementById('toggleForm').submit();
            }
        }
        
        // Confirm Delete
        function confirmDelete(userId, username) {
            if (confirm(`Are you sure you want to delete user "${username}"? This action cannot be undone.`)) {
                document.getElementById('delete_user_id').value = userId;
                document.getElementById('deleteForm').submit();
            }
        }
        
        // Close modals when clicking outside
        window.onclick = function(event) {
            const addModal = document.getElementById('addModal');
            const editModal = document.getElementById('editModal');
            if (event.target == addModal) {
                addModal.style.display = 'none';
            }
            if (event.target == editModal) {
                editModal.style.display = 'none';
            }
        }
    </script>
</body>
</html>