<?php
session_start();

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

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

/* ── Handle quick status toggle ── */
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST["toggle_status"])) {
    $id     = (int)$_POST["company_id"];
    $status = $_POST["new_status"] === "active" ? "active" : "inactive";
    $pdo->prepare("UPDATE companies SET status=? WHERE id=?")->execute([$status, $id]);
    header("Location: companies.php?msg=status_updated");
    exit;
}

/* ── Delete company ── */
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST["delete_company"])) {
    $id = (int)$_POST["company_id"];
    $pdo->prepare("DELETE FROM companies WHERE id=?")->execute([$id]);
    header("Location: companies.php?msg=deleted");
    exit;
}

/* ── Fetch companies with staff count ── */
$search = trim($_GET["q"] ?? "");
$params = [];
$where  = "";
if ($search !== "") {
    $where  = "WHERE c.name LIKE ? OR c.id = ?";
    $params = ["%$search%", (int)$search];
}

$companies = $pdo->prepare("
    SELECT c.*,
           COUNT(cs.id) AS staff_count
    FROM companies c
    LEFT JOIN company_staff cs ON cs.company_id = c.id
    $where
    GROUP BY c.id
    ORDER BY c.created_at DESC
");
$companies->execute($params);
$companies = $companies->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>Companies — Admin</title>
    <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+Lao:wght@400;500;600;700;800&family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <style>
        *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
        :root {
            --primary: #2563eb; --primary-dk: #1e3a5f;
            --green: #16a34a; --green-lt: #dcfce7;
            --red: #dc2626; --red-lt: #fee2e2;
            --amber: #d97706; --amber-lt: #fef3c7;
            --surface: #ffffff; --bg: #f0f4f8;
            --border: #e2e8f0; --text: #0f172a; --muted: #64748b;
            --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 */
        .top-bar { background: var(--surface); border-bottom: 1px solid var(--border); padding: 12px 32px; display: flex; align-items: center; gap: 16px; 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; color: var(--text); 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,#1e3a5f,#2563eb); color: #fff; box-shadow: 0 3px 10px rgba(37,99,235,.3); }
        .btn-primary:hover { opacity: .9; }

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

        /* alert */
        .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; }
        .alert-danger  { background: var(--red-lt);   color: var(--red);   border: 1.5px solid #fca5a5; }

        /* search bar */
        .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; }

        /* table card */
        .table-card { background: var(--surface); border-radius: var(--radius); box-shadow: var(--shadow); border: 1px solid var(--border); overflow: hidden; }
        table { width: 100%; border-collapse: collapse; }
        thead th { background: #f8fafc; padding: 12px 16px; text-align: left; font-size: 11px; font-weight: 700; color: var(--muted); text-transform: uppercase; letter-spacing: .5px; border-bottom: 1px solid var(--border); }
        tbody tr { border-bottom: 1px solid var(--border); transition: background .1s; }
        tbody tr:last-child { border-bottom: none; }
        tbody tr:hover { background: #f8fafc; }
        td { padding: 14px 16px; font-size: 13px; vertical-align: middle; }

        /* company name cell */
        .co-name { font-weight: 700; color: var(--text); font-size: 14px; }
        .co-id   { font-size: 11px; color: var(--muted); margin-top: 2px; }

        /* credit */
        .credit-val { font-weight: 800; color: var(--primary); font-size: 15px; }

        /* status badge */
        .badge { display: inline-flex; align-items: center; gap: 5px; padding: 3px 10px; border-radius: 999px; font-size: 11px; font-weight: 700; }
        .badge-active   { background: var(--green-lt); color: var(--green); border: 1.5px solid #86efac; }
        .badge-inactive { background: var(--red-lt);   color: var(--red);   border: 1.5px solid #fca5a5; }

        /* action buttons */
        .action-btns { display: flex; gap: 6px; flex-wrap: wrap; }
        .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: var(--primary); background: #eff6ff; }
        .btn-edit:hover { background: var(--primary); color: #fff; border-color: var(--primary); }
        .btn-credit  { border-color: #86efac; color: var(--green); background: var(--green-lt); }
        .btn-credit:hover { background: var(--green); color: #fff; border-color: var(--green); }
        .btn-toggle  { border-color: #fcd34d; color: var(--amber); background: var(--amber-lt); }
        .btn-toggle: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 state */
        .empty { text-align: center; padding: 60px 20px; color: var(--muted); }
        .empty .icon { font-size: 48px; margin-bottom: 12px; }
        .empty p { font-size: 14px; }

        /* summary strip */
        .summary-strip { display: flex; gap: 14px; margin-bottom: 20px; flex-wrap: wrap; }
        .summary-card { background: var(--surface); border-radius: 12px; padding: 14px 20px; box-shadow: var(--shadow); border: 1px solid var(--border); display: flex; align-items: center; gap: 12px; flex: 1; min-width: 160px; }
        .summary-icon { width: 40px; height: 40px; border-radius: 10px; display: flex; align-items: center; justify-content: center; font-size: 20px; }
        .s-blue { background: #dbeafe; } .s-green { background: var(--green-lt); } .s-amber { background: var(--amber-lt); }
        .summary-val { font-size: 22px; font-weight: 800; color: var(--text); line-height: 1; }
        .summary-lbl { font-size: 11px; color: var(--muted); font-weight: 600; margin-top: 2px; text-transform: uppercase; }

        /* confirm modal */
        .modal-overlay { display: none; position: fixed; inset: 0; background: rgba(15,23,42,.45); z-index: 999; align-items: center; justify-content: center; }
        .modal-overlay.open { display: flex; }
        .modal { background: var(--surface); border-radius: 16px; padding: 28px; max-width: 380px; width: 90%; box-shadow: 0 20px 60px rgba(15,23,42,.2); }
        .modal h3 { font-size: 17px; font-weight: 800; margin-bottom: 10px; }
        .modal p { font-size: 13px; color: var(--muted); margin-bottom: 20px; line-height: 1.6; }
        .modal-actions { display: flex; gap: 10px; justify-content: flex-end; }

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

<!-- top bar -->
<div class="top-bar">
    <a class="back-link" href="dashboard.php">← Dashboard</a>
    <h1>🏢 Companies</h1>
    <a class="btn btn-primary" href="company_form.php">+ Add Company</a>
</div>

<div class="page-body">

    <?php if ($msg === "status_updated"): ?>
        <div class="alert alert-success">✅ Company status updated.</div>
    <?php elseif ($msg === "deleted"): ?>
        <div class="alert alert-danger">🗑️ Company deleted.</div>
    <?php elseif ($msg === "saved"): ?>
        <div class="alert alert-success">✅ Company saved successfully.</div>
    <?php endif; ?>

    <!-- Summary strip -->
    <?php
        $totalCos      = count($companies);
        $activeCos     = count(array_filter($companies, fn($c) => $c["status"] === "active"));
        $totalCredit   = array_sum(array_column($companies, "credit_balance"));
        $totalStaffAll = array_sum(array_column($companies, "staff_count"));
    ?>
    <div class="summary-strip">
        <div class="summary-card">
            <div class="summary-icon s-blue">🏢</div>
            <div><div class="summary-val"><?= $totalCos ?></div><div class="summary-lbl">Total Companies</div></div>
        </div>
        <div class="summary-card">
            <div class="summary-icon s-green">✅</div>
            <div><div class="summary-val"><?= $activeCos ?></div><div class="summary-lbl">Active</div></div>
        </div>
        <div class="summary-card">
            <div class="summary-icon s-amber">👥</div>
            <div><div class="summary-val"><?= number_format($totalStaffAll) ?></div><div class="summary-lbl">Total Staff</div></div>
        </div>
        <div class="summary-card">
            <div class="summary-icon s-green">💰</div>
            <div><div class="summary-val">₭ <?= number_format($totalCredit, 0) ?></div><div class="summary-lbl">Total Credit</div></div>
        </div>
    </div>

    <!-- Search -->
    <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 by company name or ID…">
            </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="companies.php">Clear</a><?php endif; ?>
        </form>
    </div>

    <!-- Table -->
    <div class="table-card">
        <table>
            <thead>
                <tr>
                    <th>#</th>
                    <th>Company</th>
                    <th>Staff</th>
                    <th>Credit Balance</th>
                    <th>Status</th>
                    <th>Created</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
            <?php if (empty($companies)): ?>
                <tr><td colspan="7">
                    <div class="empty">
                        <div class="icon">🏢</div>
                        <p><?= $search ? "No companies found for &ldquo;" . htmlspecialchars($search) . "&rdquo;." : "No companies yet. Add your first one!" ?></p>
                    </div>
                </td></tr>
            <?php else: ?>
                <?php foreach ($companies as $co): ?>
                <tr>
                    <td style="color:var(--muted);font-size:12px;"><?= $co["id"] ?></td>
                    <td>
                        <div class="co-name"><?= htmlspecialchars($co["name"]) ?></div>
                        <?php if ($co["logo"]): ?>
                            <div class="co-id">Has logo</div>
                        <?php endif; ?>
                    </td>
                    <td>
                        <span style="font-weight:700;"><?= number_format($co["staff_count"]) ?></span>
                        <span style="color:var(--muted);font-size:12px;"> staff</span>
                    </td>
                    <td>
                        <span class="credit-val">₭ <?= number_format((float)$co["credit_balance"], 0) ?></span>
                    </td>
                    <td>
                        <span class="badge badge-<?= $co['status'] ?>">
                            <?= $co["status"] === "active" ? "✅ Active" : "⛔ Inactive" ?>
                        </span>
                    </td>
                    <td style="color:var(--muted);font-size:12px;">
                        <?= date("d M Y", strtotime($co["created_at"])) ?>
                    </td>
                    <td>
                        <div class="action-btns">
                            <a class="btn-sm btn-edit"   href="company_form.php?id=<?= $co['id'] ?>">✏️ Edit</a>
                            <a class="btn-sm btn-credit" href="company_credit.php?id=<?= $co['id'] ?>">💰 Credit</a>
                            <form method="POST" style="display:inline;">
                                <input type="hidden" name="toggle_status" value="1">
                                <input type="hidden" name="company_id"  value="<?= $co['id'] ?>">
                                <input type="hidden" name="new_status"
                                    value="<?= $co['status'] === 'active' ? 'inactive' : 'active' ?>">
                                <button class="btn-sm btn-toggle" type="submit">
                                    <?= $co["status"] === "active" ? "⛔ Disable" : "✅ Enable" ?>
                                </button>
                            </form>
                            <button class="btn-sm btn-danger"
                                onclick="confirmDelete(<?= $co['id'] ?>, '<?= htmlspecialchars(addslashes($co['name'])) ?>')">
                                🗑️
                            </button>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            <?php endif; ?>
            </tbody>
        </table>
    </div>

</div>

<!-- Delete confirm modal -->
<div class="modal-overlay" id="deleteModal">
    <div class="modal">
        <h3>Delete Company?</h3>
        <p id="deleteMsg">This will permanently delete the company and all associated staff and HR records. This cannot be undone.</p>
        <div class="modal-actions">
            <button class="btn" style="background:#f1f5f9;color:var(--muted);border:1.5px solid var(--border);"
                onclick="document.getElementById('deleteModal').classList.remove('open')">Cancel</button>
            <form method="POST" id="deleteForm">
                <input type="hidden" name="delete_company" value="1">
                <input type="hidden" name="company_id" id="deleteId">
                <button class="btn" style="background:var(--red);color:#fff;" type="submit">Delete</button>
            </form>
        </div>
    </div>
</div>

<script>
function confirmDelete(id, name) {
    document.getElementById('deleteId').value = id;
    document.getElementById('deleteMsg').textContent =
        `Delete "${name}"? This will remove all staff and HR records permanently.`;
    document.getElementById('deleteModal').classList.add('open');
}
document.getElementById('deleteModal').addEventListener('click', function(e) {
    if (e.target === this) this.classList.remove('open');
});
</script>
</body>
</html>