<?php
session_start();
require_once '../config.php';

requireAdmin();

$page_title = 'Staff & Admin Management';

// Create admin_users table if it doesn't exist
$conn->query("CREATE TABLE IF NOT EXISTS admin_users (
    id INT PRIMARY KEY AUTO_INCREMENT,
    full_name VARCHAR(100) NOT NULL,
    email VARCHAR(100) NOT NULL UNIQUE,
    password_hash VARCHAR(255) NOT NULL,
    role ENUM('super_admin', 'admin', 'moderator', 'support') DEFAULT 'admin',
    permissions LONGTEXT,
    is_active BOOLEAN DEFAULT TRUE,
    last_login TIMESTAMP NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    INDEX idx_email (email),
    INDEX idx_role (role)
)");

// Get all admin users
$admins_query = "SELECT id, full_name, email, role, is_active, last_login, created_at FROM admin_users ORDER BY created_at DESC";
$admins = $conn->query($admins_query)->fetch_all(MYSQLI_ASSOC);

// Handle add/edit admin
$message = '';
$alert_type = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] === 'add_admin') {
        $full_name = clean($_POST['full_name'] ?? '');
        $email = clean($_POST['email'] ?? '');
        $role = clean($_POST['role'] ?? 'admin');
        $password = $_POST['password'] ?? '';
        
        if (!$full_name || !$email || !$password) {
            $message = 'Please fill all required fields';
            $alert_type = 'danger';
        } else {
            $password_hash = password_hash($password, PASSWORD_BCRYPT);
            $stmt = $conn->prepare("INSERT INTO admin_users (full_name, email, password_hash, role) VALUES (?, ?, ?, ?)");
            $stmt->bind_param('ssss', $full_name, $email, $password_hash, $role);
            if ($stmt->execute()) {
                $message = 'Admin user added successfully!';
                $alert_type = 'success';
                header('Refresh: 2; url=admin-users.php');
            } else {
                $message = 'Error adding admin: ' . $stmt->error;
                $alert_type = 'danger';
            }
        }
    } elseif ($_POST['action'] === 'toggle_status') {
        $admin_id = (int)$_POST['admin_id'];
        $stmt = $conn->prepare("UPDATE admin_users SET is_active = !is_active WHERE id = ?");
        $stmt->bind_param('i', $admin_id);
        if ($stmt->execute()) {
            $message = 'Admin status updated!';
            $alert_type = 'success';
        }
    } elseif ($_POST['action'] === 'delete_admin') {
        $admin_id = (int)$_POST['admin_id'];
        // Prevent deleting self
        if ($admin_id == $_SESSION['admin_id']) {
            $message = 'You cannot delete your own account!';
            $alert_type = 'danger';
        } else {
            $stmt = $conn->prepare("DELETE FROM admin_users WHERE id = ?");
            $stmt->bind_param('i', $admin_id);
            if ($stmt->execute()) {
                $message = 'Admin user deleted!';
                $alert_type = 'success';
            }
        }
    }
}

include 'header.php';
?>

                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">
                        <i class="fas fa-users-cog text-primary"></i> Staff & Admin Management
                    </h1>
                    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addAdminModal">
                        <i class="fas fa-user-plus"></i> Add Admin User
                    </button>
                </div>

                <?php if ($message): ?>
                    <div class="alert alert-<?= $alert_type ?> alert-dismissible fade show" role="alert">
                        <?= htmlspecialchars($message) ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>

                <!-- Admin Users Table -->
                <div class="card">
                    <div class="card-header bg-light">
                        <h5 class="card-title mb-0">
                            <i class="fas fa-list"></i> Admin Users (<?= count($admins) ?>)
                        </h5>
                    </div>
                    <div class="table-responsive">
                        <table class="table table-hover mb-0">
                            <thead class="table-light">
                                <tr>
                                    <th>Name</th>
                                    <th>Email</th>
                                    <th>Role</th>
                                    <th>Status</th>
                                    <th>Last Login</th>
                                    <th>Created</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($admins)): ?>
                                    <tr>
                                        <td colspan="7" class="text-center text-muted py-4">
                                            No admin users found
                                        </td>
                                    </tr>
                                <?php else: ?>
                                    <?php foreach ($admins as $admin): ?>
                                        <tr>
                                            <td>
                                                <strong><?= htmlspecialchars($admin['full_name']) ?></strong>
                                            </td>
                                            <td>
                                                <small><?= htmlspecialchars($admin['email']) ?></small>
                                            </td>
                                            <td>
                                                <span class="badge bg-info"><?= ucfirst(str_replace('_', ' ', $admin['role'])) ?></span>
                                            </td>
                                            <td>
                                                <form method="POST" class="d-inline">
                                                    <input type="hidden" name="action" value="toggle_status">
                                                    <input type="hidden" name="admin_id" value="<?= $admin['id'] ?>">
                                                    <button type="submit" class="btn btn-sm <?= $admin['is_active'] ? 'btn-success' : 'btn-secondary' ?>">
                                                        <?= $admin['is_active'] ? 'Active' : 'Inactive' ?>
                                                    </button>
                                                </form>
                                            </td>
                                            <td>
                                                <small><?= $admin['last_login'] ? date('M d, h:i A', strtotime($admin['last_login'])) : 'Never' ?></small>
                                            </td>
                                            <td>
                                                <small><?= date('M d, Y', strtotime($admin['created_at'])) ?></small>
                                            </td>
                                            <td>
                                                <?php if ($admin['id'] != $_SESSION['admin_id']): ?>
                                                    <form method="POST" class="d-inline">
                                                        <input type="hidden" name="action" value="delete_admin">
                                                        <input type="hidden" name="admin_id" value="<?= $admin['id'] ?>">
                                                        <button type="submit" class="btn btn-sm btn-outline-danger" onclick="return confirm('Delete this admin user?')">
                                                            <i class="fas fa-trash"></i> Delete
                                                        </button>
                                                    </form>
                                                <?php else: ?>
                                                    <span class="text-muted small">(Current User)</span>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>

                <!-- Add Admin Modal -->
                <div class="modal fade" id="addAdminModal" tabindex="-1">
                    <div class="modal-dialog">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title"><i class="fas fa-user-plus"></i> Add New Admin User</h5>
                                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                            </div>
                            <form method="POST">
                                <div class="modal-body">
                                    <input type="hidden" name="action" value="add_admin">
                                    
                                    <div class="mb-3">
                                        <label class="form-label">Full Name <span class="text-danger">*</span></label>
                                        <input type="text" name="full_name" class="form-control" required>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label class="form-label">Email <span class="text-danger">*</span></label>
                                        <input type="email" name="email" class="form-control" required>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label class="form-label">Password <span class="text-danger">*</span></label>
                                        <input type="password" name="password" class="form-control" required>
                                        <small class="text-muted">Minimum 6 characters</small>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label class="form-label">Role</label>
                                        <select name="role" class="form-select">
                                            <option value="admin">Admin</option>
                                            <option value="moderator">Moderator</option>
                                            <option value="support">Support</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                                    <button type="submit" class="btn btn-primary">
                                        <i class="fas fa-save"></i> Add Admin
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>

<?php include 'footer.php'; ?>
