<?php
require_once 'db.php';
requireAdmin();

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$currentAdminId = $_SESSION['admin_id'] ?? 0;

if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

function redirectWithMessage(string $type, string $text): void
{
    header("Location: manage_staff.php?{$type}=" . urlencode($text));
    exit;
}

function isValidStatus(string $status): bool
{
    return in_array($status, ['active', 'inactive'], true);
}

$message = $_GET['message'] ?? '';
$error   = $_GET['error'] ?? '';

# HANDLE ADD STAFF
if (isset($_POST['add_staff'])) {
    if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'] ?? '')) {
        redirectWithMessage('error', 'Invalid request token.');
    }

    $full_name = trim($_POST['full_name'] ?? '');
    $username  = trim($_POST['username'] ?? '');
    $password  = $_POST['password'] ?? '';
    $status    = trim($_POST['status'] ?? 'active');

    if ($full_name === '' || $username === '' || $password === '') {
        redirectWithMessage('error', 'Please fill in all required fields.');
    }

    if (!isValidStatus($status)) {
        redirectWithMessage('error', 'Invalid status selected.');
    }

    if (strlen($password) < 6) {
        redirectWithMessage('error', 'Password must be at least 6 characters.');
    }

    $check = $pdo->prepare("SELECT id FROM staff WHERE username = ?");
    $check->execute([$username]);

    if ($check->fetch()) {
        redirectWithMessage('error', 'Username already exists.');
    }

    $hashedPassword = password_hash($password, PASSWORD_DEFAULT);

    $stmt = $pdo->prepare("
        INSERT INTO staff (full_name, username, password, status)
        VALUES (?, ?, ?, ?)
    ");
    $stmt->execute([$full_name, $username, $hashedPassword, $status]);

    redirectWithMessage('message', 'Staff added successfully.');
}

# HANDLE DELETE STAFF
if (isset($_POST['delete_staff'])) {
    if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'] ?? '')) {
        redirectWithMessage('error', 'Invalid request token.');
    }

    $id = (int)($_POST['staff_id'] ?? 0);

    if ($id <= 0) {
        redirectWithMessage('error', 'Invalid staff ID.');
    }

    if ($id === (int)$currentAdminId) {
        redirectWithMessage('error', 'You cannot delete your own account.');
    }

    $stmt = $pdo->prepare("DELETE FROM staff WHERE id = ?");
    $stmt->execute([$id]);

    redirectWithMessage('message', 'Staff deleted successfully.');
}

# HANDLE UPDATE STAFF
if (isset($_POST['update_staff'])) {
    if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'] ?? '')) {
        redirectWithMessage('error', 'Invalid request token.');
    }

    $id          = (int)($_POST['staff_id'] ?? 0);
    $full_name   = trim($_POST['full_name'] ?? '');
    $username    = trim($_POST['username'] ?? '');
    $newPassword = $_POST['password'] ?? '';
    $status      = trim($_POST['status'] ?? 'active');

    if ($id <= 0 || $full_name === '' || $username === '') {
        redirectWithMessage('error', 'Please fill in all required fields.');
    }

    if (!isValidStatus($status)) {
        redirectWithMessage('error', 'Invalid status selected.');
    }

    if ($id === (int)$currentAdminId && $status === 'inactive') {
        redirectWithMessage('error', 'You cannot deactivate your own account.');
    }

    $check = $pdo->prepare("SELECT id FROM staff WHERE username = ? AND id != ?");
    $check->execute([$username, $id]);

    if ($check->fetch()) {
        redirectWithMessage('error', 'Username already exists.');
    }

    if ($newPassword !== '' && strlen($newPassword) < 6) {
        redirectWithMessage('error', 'New password must be at least 6 characters.');
    }

    if ($newPassword !== '') {
        $hashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);

        $stmt = $pdo->prepare("
            UPDATE staff
            SET full_name = ?, username = ?, password = ?, status = ?
            WHERE id = ?
        ");
        $stmt->execute([$full_name, $username, $hashedPassword, $status, $id]);

        redirectWithMessage('message', 'Staff updated successfully. Password reset completed.');
    } else {
        $stmt = $pdo->prepare("
            UPDATE staff
            SET full_name = ?, username = ?, status = ?
            WHERE id = ?
        ");
        $stmt->execute([$full_name, $username, $status, $id]);

        redirectWithMessage('message', 'Staff updated successfully.');
    }
}

# LOAD STAFF FOR TABLE
$staff = $pdo->query("SELECT id, full_name, username, status FROM staff ORDER BY id DESC")->fetchAll();

# LOAD STAFF FOR EDIT
$editStaff = null;
if (isset($_GET['edit'])) {
    $id = (int)$_GET['edit'];

    if ($id > 0) {
        $stmt = $pdo->prepare("SELECT id, full_name, username, status FROM staff WHERE id = ?");
        $stmt->execute([$id]);
        $editStaff = $stmt->fetch();
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Staff Management</title>
    <link rel="stylesheet" href="css/style.css?v=1">

    <style>
        * {
            box-sizing: border-box;
        }

        body {
            font-family: Arial, sans-serif;
            background: #f3f6fb;
            margin: 0;
            color: #111827;
        }

        .staff-topbar {
            margin: 20px 0;
            padding: 0 16px;
        }

        .staff-back-btn {
            display: inline-block;
            background: #2563eb;
            color: #fff;
            padding: 8px 14px;
            border-radius: 8px;
            text-decoration: none;
            font-weight: bold;
        }

        .staff-back-btn:hover {
            background: #1d4ed8;
        }

        .staff-container {
            width: 1100px;
            max-width: 95%;
            margin: 25px auto;
            padding: 0 16px;
        }

        .staff-page-title {
            margin: 0 0 16px;
            font-size: 28px;
            font-weight: 700;
        }

        .staff-box {
            background: #fff;
            padding: 20px;
            border-radius: 16px;
            margin-top: 20px;
            box-shadow: 0 10px 25px rgba(15, 23, 42, 0.05);
        }

        .staff-box h3 {
            margin-top: 0;
            margin-bottom: 16px;
        }

        .message {
            background: #dcfce7;
            color: #166534;
            padding: 12px;
            border-radius: 10px;
            margin-bottom: 15px;
        }

        .error {
            background: #fee2e2;
            color: #991b1b;
            padding: 12px;
            border-radius: 10px;
            margin-bottom: 15px;
        }

        .staff-form-row {
            margin-bottom: 14px;
        }

        .staff-form-row label {
            display: block;
            margin-bottom: 6px;
            font-weight: 600;
        }

        .staff-form-row input,
        .staff-form-row select {
            width: 320px;
            max-width: 100%;
            padding: 10px 12px;
            border: 1px solid #d1d5db;
            border-radius: 10px;
            font-size: 14px;
            background: #fff;
            color: #111827;
        }

        .small-note {
            font-size: 12px;
            color: #6b7280;
            margin-top: 5px;
        }

        .staff-btn {
            padding: 10px 16px;
            border: none;
            border-radius: 10px;
            cursor: pointer;
            text-decoration: none;
            display: inline-block;
            font-size: 14px;
            font-weight: 600;
        }

        .staff-btn-primary {
            background: #2563eb;
            color: #fff;
        }

        .staff-btn-primary:hover {
            background: #1d4ed8;
        }

        .staff-btn-danger {
            background: #dc2626;
            color: #fff;
        }

        .staff-btn-danger:hover {
            background: #b91c1c;
        }

        .staff-btn-secondary {
            background: #e5e7eb;
            color: #111827;
        }

        .staff-btn-secondary:hover {
            background: #d1d5db;
        }

        .staff-btn-disabled {
            background: #9ca3af;
            color: #fff;
            cursor: not-allowed;
        }

        .staff-btn-row {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
            align-items: center;
            margin-top: 8px;
        }

        .staff-table-wrap {
            width: 100%;
            overflow-x: auto;
        }

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

        .staff-table th,
        .staff-table td {
            padding: 12px 10px;
            border-bottom: 1px solid #e5e7eb;
            text-align: left;
            vertical-align: middle;
            font-size: 14px;
        }

        .staff-table th {
            background: #f8fafc;
            white-space: nowrap;
        }

        .status-active {
            display: inline-block;
            padding: 6px 10px;
            border-radius: 999px;
            background: #dcfce7;
            color: #166534;
            font-weight: bold;
            font-size: 12px;
        }

        .status-inactive {
            display: inline-block;
            padding: 6px 10px;
            border-radius: 999px;
            background: #fee2e2;
            color: #991b1b;
            font-weight: bold;
            font-size: 12px;
        }

        .staff-actions {
            display: flex;
            gap: 8px;
            align-items: center;
            flex-wrap: wrap;
        }

        .inline-form {
            display: inline;
            margin: 0;
        }

        .self-badge {
            font-size: 12px;
            background: #e0e7ff;
            color: #3730a3;
            padding: 4px 8px;
            border-radius: 999px;
            margin-left: 8px;
            font-weight: 600;
        }

        @media (max-width: 768px) {
            .staff-container {
                max-width: 100%;
            }

            .staff-page-title {
                font-size: 24px;
            }

            .staff-actions {
                min-width: 150px;
            }
        }
    </style>
</head>
<body>

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

<div class="staff-topbar">
    <a href="admin-dashboard.php" class="staff-back-btn">← Dashboard</a>
</div>

<div class="staff-container">
    <h2 class="staff-page-title">Staff Management</h2>

    <?php if ($message): ?>
        <div class="message"><?= esc($message) ?></div>
    <?php endif; ?>

    <?php if ($error): ?>
        <div class="error"><?= esc($error) ?></div>
    <?php endif; ?>

    <div class="staff-box">
        <?php if ($editStaff): ?>
            <h3>Edit Staff</h3>

            <form method="POST">
                <input type="hidden" name="csrf_token" value="<?= esc($_SESSION['csrf_token']) ?>">
                <input type="hidden" name="staff_id" value="<?= (int)$editStaff['id'] ?>">

                <div class="staff-form-row">
                    <label for="full_name">Full Name</label>
                    <input type="text" id="full_name" name="full_name"
                           value="<?= esc($editStaff['full_name']) ?>" required>
                </div>

                <div class="staff-form-row">
                    <label for="username">Username</label>
                    <input type="text" id="username" name="username"
                           value="<?= esc($editStaff['username']) ?>" required>
                </div>

                <div class="staff-form-row">
                    <label for="password">New Password</label>
                    <input type="password" id="password" name="password"
                           placeholder="Leave blank to keep current password">
                    <div class="small-note">Only enter a password if you want to reset it. Minimum 6 characters.</div>
                </div>

                <div class="staff-form-row">
                    <label for="status">Status</label>
                    <select id="status" name="status" required>
                        <option value="active" <?= $editStaff['status'] === 'active' ? 'selected' : '' ?>>Active</option>
                        <option value="inactive" <?= $editStaff['status'] === 'inactive' ? 'selected' : '' ?>>Inactive</option>
                    </select>
                    <?php if ((int)$editStaff['id'] === (int)$currentAdminId): ?>
                        <div class="small-note">Your own account cannot be set to inactive here.</div>
                    <?php endif; ?>
                </div>

                <div class="staff-btn-row">
                    <button type="submit" name="update_staff" class="staff-btn staff-btn-primary">Update Staff</button>
                    <a href="manage_staff.php" class="staff-btn staff-btn-secondary">Cancel</a>
                </div>
            </form>

        <?php else: ?>
            <h3>Add New Staff</h3>

            <form method="POST">
                <input type="hidden" name="csrf_token" value="<?= esc($_SESSION['csrf_token']) ?>">

                <div class="staff-form-row">
                    <label for="full_name">Full Name</label>
                    <input type="text" id="full_name" name="full_name" placeholder="Staff Name" required>
                </div>

                <div class="staff-form-row">
                    <label for="username">Username</label>
                    <input type="text" id="username" name="username" placeholder="Username" required>
                </div>

                <div class="staff-form-row">
                    <label for="password">Password</label>
                    <input type="password" id="password" name="password" placeholder="Password" required>
                    <div class="small-note">Minimum 6 characters.</div>
                </div>

                <div class="staff-form-row">
                    <label for="status">Status</label>
                    <select id="status" name="status" required>
                        <option value="active">Active</option>
                        <option value="inactive">Inactive</option>
                    </select>
                </div>

                <div class="staff-btn-row">
                    <button type="submit" name="add_staff" class="staff-btn staff-btn-primary">Add Staff</button>
                </div>
            </form>
        <?php endif; ?>
    </div>

    <div class="staff-box">
        <h3>Staff List</h3>

        <div class="staff-table-wrap">
            <table class="staff-table">
                <tr>
                    <th>ID</th>
                    <th>Name</th>
                    <th>Username</th>
                    <th>Status</th>
                    <th>Action</th>
                </tr>

                <?php foreach ($staff as $s): ?>
                    <tr>
                        <td><?= (int)$s['id'] ?></td>
                        <td>
                            <?= esc($s['full_name']) ?>
                            <?php if ((int)$s['id'] === (int)$currentAdminId): ?>
                                <span class="self-badge">You</span>
                            <?php endif; ?>
                        </td>
                        <td><?= esc($s['username']) ?></td>
                        <td>
                            <?php if ($s['status'] === 'active'): ?>
                                <span class="status-active">Active</span>
                            <?php else: ?>
                                <span class="status-inactive">Inactive</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <div class="staff-actions">
                                <a class="staff-btn staff-btn-primary" href="?edit=<?= (int)$s['id'] ?>">Edit</a>

                                <?php if ((int)$s['id'] === (int)$currentAdminId): ?>
                                    <button type="button" class="staff-btn staff-btn-disabled" title="You cannot delete your own account">Delete</button>
                                <?php else: ?>
                                    <form method="POST" class="inline-form" onsubmit="return confirm('Delete this staff account?');">
                                        <input type="hidden" name="csrf_token" value="<?= esc($_SESSION['csrf_token']) ?>">
                                        <input type="hidden" name="staff_id" value="<?= (int)$s['id'] ?>">
                                        <button type="submit" name="delete_staff" class="staff-btn staff-btn-danger">Delete</button>
                                    </form>
                                <?php endif; ?>
                            </div>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </table>
        </div>
    </div>
</div>

</body>
</html>