<?php
session_start();

if (!isset($_SESSION["user_id"]) || $_SESSION["role"] !== "company_admin") {
    header("Location: ../auth/login.php");
    exit;
}

require_once '../config/database.php';

$companyId = (int)$_SESSION["company_id"];

/* ── Delete staff ── */
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST["remove_staff"])) {
    $uid = (int)$_POST["user_id"];
    /* Remove from company_staff only — keeps user account */
    $pdo->prepare("DELETE FROM company_staff WHERE user_id=? AND company_id=?")->execute([$uid, $companyId]);
    /* Deactivate user so they can't log in */
    $pdo->prepare("UPDATE users SET status='inactive' WHERE id=?")->execute([$uid]);
    header("Location: staff.php?msg=removed"); exit;
}

/* ── Reset password ── */
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST["reset_password"])) {
    $uid     = (int)$_POST["user_id"];
    $newPass = trim($_POST["new_password"]);
    if (strlen($newPass) >= 6) {
        $hash = password_hash($newPass, PASSWORD_DEFAULT);
        $pdo->prepare("UPDATE users SET password=? WHERE id=?")->execute([$hash, $uid]);
        header("Location: staff.php?msg=password_reset"); exit;
    }
}

/* ── Fetch staff ── */
$search = trim($_GET["q"] ?? "");
$params = [$companyId];
$where  = "";
if ($search !== "") {
    $where    = "AND (u.name LIKE ? OR u.email LIKE ? OR cs.position LIKE ? OR cs.department LIKE ?)";
    $params[] = "%$search%"; $params[] = "%$search%";
    $params[] = "%$search%"; $params[] = "%$search%";
}

$staff = $pdo->prepare("
    SELECT u.id, u.name, u.email, u.status,
           cs.staff_role, cs.position, cs.department, cs.joined_date
    FROM company_staff cs
    JOIN users u ON u.id = cs.user_id
    WHERE cs.company_id = ? $where
    ORDER BY cs.staff_role ASC, u.name ASC
");
$staff->execute($params);
$staff = $staff->fetchAll(PDO::FETCH_ASSOC);

$msg = $_GET["msg"] ?? "";
?>
<!DOCTYPE html>
<html lang="lo">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Staff — <?= htmlspecialchars($_SESSION["company_name"]) ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+Lao:wght@400;600;700;800&family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <style>
        *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
        :root {
            --primary: #0f766e; --surface: #ffffff; --bg: #f0f4f8;
            --border: #e2e8f0; --text: #0f172a; --muted: #64748b;
            --green: #16a34a; --green-lt: #dcfce7;
            --red: #dc2626; --red-lt: #fee2e2;
            --amber: #d97706; --amber-lt: #fef3c7;
            --teal-lt: #ccfbf1;
            --radius: 14px; --shadow: 0 2px 14px rgba(15,23,42,.09);
        }
        body { font-family: "Noto Sans Lao","Inter",Arial,sans-serif; background: var(--bg); color: var(--text); min-height: 100vh; }

        .top-bar { background: var(--surface); border-bottom: 1px solid var(--border); padding: 12px 32px; display: flex; align-items: center; gap: 14px; flex-wrap: wrap; position: sticky; top: 0; z-index: 100; box-shadow: 0 1px 6px rgba(15,23,42,.06); }
        .back-link { display: inline-flex; align-items: center; gap: 6px; color: var(--muted); text-decoration: none; font-size: 13px; font-weight: 600; padding: 6px 12px; border-radius: 8px; border: 1.5px solid var(--border); transition: all .15s; }
        .back-link:hover { border-color: var(--primary); color: var(--primary); }
        .top-bar h1 { font-size: 17px; font-weight: 800; flex: 1; }
        .btn { display: inline-flex; align-items: center; gap: 7px; padding: 9px 18px; border-radius: 10px; font-size: 13px; font-weight: 700; font-family: inherit; cursor: pointer; border: none; text-decoration: none; transition: all .15s; }
        .btn-primary { background: linear-gradient(135deg,#084740,#0f766e); color: #fff; box-shadow: 0 3px 10px rgba(15,118,110,.3); }
        .btn-primary:hover { opacity: .9; }

        .page-body { padding: 28px 32px; max-width: 1200px; margin: auto; }

        .alert { padding: 12px 16px; border-radius: 10px; margin-bottom: 20px; font-size: 13px; font-weight: 600; }
        .alert-success { background: var(--green-lt); color: var(--green); border: 1.5px solid #86efac; }

        .toolbar { display: flex; align-items: center; gap: 12px; margin-bottom: 20px; flex-wrap: wrap; }
        .search-wrap { position: relative; flex: 1; min-width: 220px; }
        .search-wrap input { width: 100%; padding: 10px 14px 10px 38px; border: 1.5px solid var(--border); border-radius: 10px; font-size: 13px; font-family: inherit; outline: none; transition: border-color .15s; }
        .search-wrap input:focus { border-color: var(--primary); }
        .search-wrap .icon { position: absolute; left: 12px; top: 50%; transform: translateY(-50%); font-size: 15px; }

        /* staff grid */
        .staff-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(310px, 1fr)); gap: 14px; }

        .staff-card { background: var(--surface); border-radius: var(--radius); box-shadow: var(--shadow); border: 1px solid var(--border); padding: 20px; transition: transform .15s, box-shadow .15s; }
        .staff-card:hover { transform: translateY(-2px); box-shadow: 0 6px 20px rgba(15,23,42,.11); }

        .staff-header { display: flex; align-items: center; gap: 12px; margin-bottom: 14px; }
        .staff-avatar { width: 44px; height: 44px; border-radius: 12px; background: linear-gradient(135deg,#084740,#0f766e); display: flex; align-items: center; justify-content: center; color: #fff; font-weight: 800; font-size: 18px; flex-shrink: 0; }
        .staff-avatar.admin-av { background: linear-gradient(135deg,#4c1d95,#7c3aed); }
        .staff-name { font-size: 15px; font-weight: 700; color: var(--text); line-height: 1.2; }
        .staff-email { font-size: 12px; color: var(--muted); margin-top: 2px; }

        .staff-meta { display: flex; flex-wrap: wrap; gap: 6px; margin-bottom: 14px; }
        .meta-pill { font-size: 11px; font-weight: 700; padding: 3px 9px; border-radius: 999px; border: 1.5px solid; }
        .pill-role-admin { background: #ede9fe; color: #7c3aed; border-color: #c4b5fd; }
        .pill-role-staff { background: var(--teal-lt); color: #0f766e; border-color: #5eead4; }
        .pill-dept   { background: #f1f5f9; color: var(--muted); border-color: var(--border); }
        .pill-pos    { background: #eff6ff; color: #2563eb; border-color: #93c5fd; }
        .pill-active   { background: var(--green-lt); color: var(--green); border-color: #86efac; }
        .pill-inactive { background: var(--red-lt); color: var(--red); border-color: #fca5a5; }

        .staff-joined { font-size: 12px; color: var(--muted); margin-bottom: 14px; }

        .staff-actions { display: flex; gap: 7px; flex-wrap: wrap; border-top: 1px solid var(--border); padding-top: 14px; }
        .btn-sm { padding: 5px 12px; border-radius: 7px; font-size: 12px; font-weight: 700; font-family: inherit; cursor: pointer; border: 1.5px solid; text-decoration: none; display: inline-flex; align-items: center; gap: 4px; transition: all .15s; }
        .btn-edit   { border-color: #93c5fd; color: #2563eb; background: #eff6ff; }
        .btn-edit:hover { background: #2563eb; color: #fff; border-color: #2563eb; }
        .btn-pw     { border-color: #fcd34d; color: var(--amber); background: var(--amber-lt); }
        .btn-pw:hover { background: var(--amber); color: #fff; border-color: var(--amber); }
        .btn-danger { border-color: #fca5a5; color: var(--red); background: var(--red-lt); }
        .btn-danger:hover { background: var(--red); color: #fff; border-color: var(--red); }

        .empty { text-align: center; padding: 60px; color: var(--muted); }
        .empty .icon { font-size: 48px; margin-bottom: 12px; }

        /* Modal */
        .modal-overlay { display: none; position: fixed; inset: 0; background: rgba(15,23,42,.45); z-index: 999; align-items: center; justify-content: center; padding: 20px; }
        .modal-overlay.open { display: flex; }
        .modal { background: var(--surface); border-radius: 16px; padding: 28px; max-width: 400px; width: 100%; box-shadow: 0 20px 60px rgba(15,23,42,.2); }
        .modal h3 { font-size: 16px; font-weight: 800; margin-bottom: 14px; }
        .modal input { width: 100%; padding: 10px 14px; border: 1.5px solid var(--border); border-radius: 10px; font-size: 14px; font-family: inherit; outline: none; margin-bottom: 16px; }
        .modal input:focus { border-color: var(--primary); }
        .modal-actions { display: flex; gap: 10px; justify-content: flex-end; }
        .btn-modal-cancel { background: #f1f5f9; color: var(--muted); border: 1.5px solid var(--border); padding: 8px 16px; border-radius: 8px; font-size: 13px; font-weight: 700; cursor: pointer; font-family: inherit; }
        .btn-modal-ok     { background: var(--primary); color: #fff; border: none; padding: 8px 18px; border-radius: 8px; font-size: 13px; font-weight: 700; cursor: pointer; font-family: inherit; }

        @media (max-width: 700px) { .page-body { padding: 16px; } .top-bar { padding: 10px 16px; } }
    </style>
</head>
<body>

<div class="top-bar">
    <a class="back-link" href="dashboard.php">← Dashboard</a>
    <h1>👥 Staff — <?= htmlspecialchars($_SESSION["company_name"]) ?></h1>
    <a class="btn btn-primary" href="staff_form.php">+ Add Staff</a>
</div>

<div class="page-body">

    <?php if ($msg === "removed"): ?>
        <div class="alert alert-success">✅ Staff member removed.</div>
    <?php elseif ($msg === "password_reset"): ?>
        <div class="alert alert-success">✅ Password reset successfully.</div>
    <?php elseif ($msg === "saved"): ?>
        <div class="alert alert-success">✅ Staff member saved.</div>
    <?php endif; ?>

    <div class="toolbar">
        <form method="GET" style="display:contents;">
            <div class="search-wrap">
                <span class="icon">🔍</span>
                <input type="text" name="q" value="<?= htmlspecialchars($search) ?>"
                    placeholder="Search name, email, position, department…">
            </div>
            <button class="btn btn-primary" type="submit">Search</button>
            <?php if ($search): ?>
                <a class="btn" style="background:#f1f5f9;color:var(--muted);border:1.5px solid var(--border);" href="staff.php">Clear</a>
            <?php endif; ?>
        </form>
        <span style="font-size:13px;color:var(--muted);margin-left:auto;">
            <?= count($staff) ?> staff member<?= count($staff) !== 1 ? "s" : "" ?>
        </span>
    </div>

    <?php if (empty($staff)): ?>
        <div class="empty">
            <div class="icon">👥</div>
            <p><?= $search ? "No staff found for \"$search\"." : "No staff yet. Add your first staff member!" ?></p>
        </div>
    <?php else: ?>
        <div class="staff-grid">
        <?php foreach ($staff as $s): ?>
            <div class="staff-card">
                <div class="staff-header">
                    <div class="staff-avatar <?= $s['staff_role'] === 'admin' ? 'admin-av' : '' ?>">
                        <?= strtoupper(mb_substr($s['name'], 0, 1)) ?>
                    </div>
                    <div>
                        <div class="staff-name"><?= htmlspecialchars($s['name']) ?></div>
                        <div class="staff-email"><?= htmlspecialchars($s['email']) ?></div>
                    </div>
                </div>

                <div class="staff-meta">
                    <span class="meta-pill pill-role-<?= $s['staff_role'] ?>">
                        <?= $s['staff_role'] === 'admin' ? '👑 Admin' : '👤 Staff' ?>
                    </span>
                    <?php if ($s['position']): ?>
                        <span class="meta-pill pill-pos"><?= htmlspecialchars($s['position']) ?></span>
                    <?php endif; ?>
                    <?php if ($s['department']): ?>
                        <span class="meta-pill pill-dept"><?= htmlspecialchars($s['department']) ?></span>
                    <?php endif; ?>
                    <span class="meta-pill pill-<?= $s['status'] ?>">
                        <?= $s['status'] === 'active' ? '✅ Active' : '⛔ Inactive' ?>
                    </span>
                </div>

                <?php if ($s['joined_date']): ?>
                    <div class="staff-joined">
                        📅 Joined: <?= date("d M Y", strtotime($s['joined_date'])) ?>
                    </div>
                <?php endif; ?>

                <div class="staff-actions">
                    <a class="btn-sm btn-edit" href="staff_form.php?id=<?= $s['id'] ?>">✏️ Edit</a>
                    <button class="btn-sm btn-pw"
                        onclick="openPwModal(<?= $s['id'] ?>, '<?= htmlspecialchars(addslashes($s['name'])) ?>')">
                        🔑 Reset PW
                    </button>
                    <button class="btn-sm btn-danger"
                        onclick="openRemoveModal(<?= $s['id'] ?>, '<?= htmlspecialchars(addslashes($s['name'])) ?>')">
                        🗑️ Remove
                    </button>
                </div>
            </div>
        <?php endforeach; ?>
        </div>
    <?php endif; ?>
</div>

<!-- Password reset modal -->
<div class="modal-overlay" id="pwModal">
    <div class="modal">
        <h3>🔑 Reset Password</h3>
        <p id="pwModalName" style="color:var(--muted);font-size:13px;margin-bottom:12px;"></p>
        <form method="POST" id="pwForm">
            <input type="hidden" name="reset_password" value="1">
            <input type="hidden" name="user_id" id="pwUserId">
            <input type="password" name="new_password" placeholder="New password (min 6 chars)" minlength="6" required>
            <div class="modal-actions">
                <button type="button" class="btn-modal-cancel" onclick="document.getElementById('pwModal').classList.remove('open')">Cancel</button>
                <button type="submit" class="btn-modal-ok">Reset</button>
            </div>
        </form>
    </div>
</div>

<!-- Remove confirm modal -->
<div class="modal-overlay" id="removeModal">
    <div class="modal">
        <h3>Remove Staff Member?</h3>
        <p id="removeMsg" style="color:var(--muted);font-size:13px;margin-bottom:20px;"></p>
        <form method="POST" id="removeForm">
            <input type="hidden" name="remove_staff" value="1">
            <input type="hidden" name="user_id" id="removeUserId">
            <div class="modal-actions">
                <button type="button" class="btn-modal-cancel" onclick="document.getElementById('removeModal').classList.remove('open')">Cancel</button>
                <button type="submit" class="btn-modal-ok" style="background:var(--red);">Remove</button>
            </div>
        </form>
    </div>
</div>

<script>
function openPwModal(id, name) {
    document.getElementById('pwUserId').value = id;
    document.getElementById('pwModalName').textContent = 'Staff: ' + name;
    document.getElementById('pwModal').classList.add('open');
}
function openRemoveModal(id, name) {
    document.getElementById('removeUserId').value = id;
    document.getElementById('removeMsg').textContent =
        `Remove "${name}" from your company? Their account will be deactivated.`;
    document.getElementById('removeModal').classList.add('open');
}
document.querySelectorAll('.modal-overlay').forEach(m => {
    m.addEventListener('click', e => { if (e.target === m) m.classList.remove('open'); });
});
</script>
</body>
</html>