<?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"];

/* ── Approve / Reject ── */
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST["review"])) {
    $id     = (int)$_POST["leave_id"];
    $action = $_POST["action"] === "approved" ? "approved" : "rejected";
    $pdo->prepare("UPDATE hr_leave SET status=?, reviewed_by=? WHERE id=? AND company_id=?")
        ->execute([$action, $_SESSION["user_id"], $id, $companyId]);
    header("Location: hr_leave.php?msg=$action"); exit;
}

$filterStatus = $_GET["status"] ?? "pending";
$validStatus  = ["pending","approved","rejected","all"];
if (!in_array($filterStatus, $validStatus)) $filterStatus = "pending";

$where  = $filterStatus !== "all" ? "AND l.status = ?" : "";
$params = [$companyId];
if ($filterStatus !== "all") $params[] = $filterStatus;

$leaves = $pdo->prepare("
    SELECT l.*, u.name AS staff_name, cs.department, cs.position
    FROM hr_leave l
    JOIN users u ON u.id = l.staff_id
    JOIN company_staff cs ON cs.user_id = l.staff_id AND cs.company_id = l.company_id
    WHERE l.company_id=? $where
    ORDER BY l.created_at DESC
    LIMIT 100
");
$leaves->execute($params);
$leaves = $leaves->fetchAll(PDO::FETCH_ASSOC);

$counts = $pdo->prepare("SELECT status, COUNT(*) AS n FROM hr_leave WHERE company_id=? GROUP BY status");
$counts->execute([$companyId]);
$cmap = array_column($counts->fetchAll(PDO::FETCH_ASSOC), "n", "status");

$msg = $_GET["msg"] ?? "";
$typeLabels = ["annual"=>"🏖️ Annual","sick"=>"🤒 Sick","unpaid"=>"💸 Unpaid","maternity"=>"🤱 Maternity","other"=>"📋 Other"];
$sc = ["pending"=>["#fef3c7","#d97706"],"approved"=>["#dcfce7","#16a34a"],"rejected"=>["#fee2e2","#dc2626"]];
?>
<!DOCTYPE html>
<html lang="lo">
<head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Leave Requests — <?= htmlspecialchars($_SESSION["company_name"]) ?></title>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
<style>
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
:root{--p:#0f766e;--s:#fff;--bg:#f0f4f8;--b:#e2e8f0;--t:#0f172a;--m:#64748b;--g:#16a34a;--gl:#dcfce7;--r:#dc2626;--rl:#fee2e2;--a:#d97706;--al:#fef3c7;--rad:14px;--sh:0 2px 14px rgba(15,23,42,.09)}
body{font-family:"Inter",Arial,sans-serif;background:var(--bg);color:var(--t);min-height:100vh}
.top-bar{background:var(--s);border-bottom:1px solid var(--b);padding:12px 32px;display:flex;align-items:center;gap:14px;position:sticky;top:0;z-index:100;box-shadow:0 1px 6px rgba(15,23,42,.06)}
.back{display:inline-flex;align-items:center;gap:6px;color:var(--m);text-decoration:none;font-size:13px;font-weight:600;padding:6px 12px;border-radius:8px;border:1.5px solid var(--b);transition:all .15s}
.back:hover{border-color:var(--p);color:var(--p)}
h1{font-size:17px;font-weight:800;flex:1}
.pb{padding:24px 32px;max-width:1100px;margin:auto}
.alert{padding:12px 16px;border-radius:10px;margin-bottom:18px;font-size:13px;font-weight:600}
.al-ok{background:var(--gl);color:var(--g);border:1.5px solid #86efac}
.al-rj{background:var(--rl);color:var(--r);border:1.5px solid #fca5a5}

/* tabs */
.tabs{display:flex;gap:6px;margin-bottom:20px;flex-wrap:wrap}
.tab{padding:8px 18px;border-radius:999px;font-size:13px;font-weight:700;text-decoration:none;border:1.5px solid var(--b);color:var(--m);background:var(--s);transition:all .15s;display:inline-flex;align-items:center;gap:6px}
.tab:hover{border-color:var(--p);color:var(--p)}
.tab.active{background:var(--p);border-color:var(--p);color:#fff}
.count-pill{background:rgba(255,255,255,.25);border-radius:999px;padding:1px 7px;font-size:11px}
.tab:not(.active) .count-pill{background:var(--b);color:var(--m)}

/* stats */
.sum-row{display:grid;grid-template-columns:repeat(auto-fill,minmax(140px,1fr));gap:10px;margin-bottom:20px}
.sc{background:var(--s);border-radius:12px;padding:12px 16px;box-shadow:var(--sh);border:1px solid var(--b);text-align:center}
.sv{font-size:22px;font-weight:800;margin-bottom:2px}
.sl{font-size:11px;color:var(--m);font-weight:600;text-transform:uppercase}

/* cards */
.leave-list{display:flex;flex-direction:column;gap:12px}
.leave-card{background:var(--s);border-radius:var(--rad);box-shadow:var(--sh);border:1px solid var(--b);padding:18px 20px}
.lc-top{display:flex;align-items:flex-start;justify-content:space-between;gap:14px;flex-wrap:wrap;margin-bottom:12px}
.staff-name{font-size:15px;font-weight:800}
.staff-meta{font-size:12px;color:var(--m);margin-top:2px}
.badge{display:inline-flex;padding:3px 10px;border-radius:999px;font-size:11px;font-weight:700}
.lc-info{display:flex;gap:20px;flex-wrap:wrap;margin-bottom:14px}
.info-item{font-size:13px}
.info-item .lbl{font-size:11px;color:var(--m);font-weight:600;text-transform:uppercase;letter-spacing:.3px;margin-bottom:2px}
.info-item .val{font-weight:700}
.reason-box{background:#f8fafc;border-radius:8px;padding:10px 14px;font-size:13px;color:var(--m);margin-bottom:14px;border-left:3px solid var(--b)}
.lc-actions{display:flex;gap:8px;flex-wrap:wrap}
.btn-approve{display:inline-flex;align-items:center;gap:6px;padding:8px 18px;border-radius:8px;background:var(--g);color:#fff;border:none;font-size:13px;font-weight:700;cursor:pointer;font-family:inherit;transition:opacity .15s}
.btn-approve:hover{opacity:.9}
.btn-reject{display:inline-flex;align-items:center;gap:6px;padding:8px 18px;border-radius:8px;background:var(--r);color:#fff;border:none;font-size:13px;font-weight:700;cursor:pointer;font-family:inherit;transition:opacity .15s}
.btn-reject:hover{opacity:.9}
.empty{text-align:center;padding:60px;color:var(--m)}
.empty .icon{font-size:44px;margin-bottom:12px}
@media(max-width:700px){.pb{padding:16px}.top-bar{padding:10px 16px}}
</style>
</head>
<body>
<div class="top-bar">
    <a class="back" href="dashboard.php">← Dashboard</a>
    <h1>🏖️ Leave Requests</h1>
</div>
<div class="pb">

<?php if($msg==="approved"): ?><div class="alert al-ok">✅ Leave request approved.</div>
<?php elseif($msg==="rejected"): ?><div class="alert al-rj">❌ Leave request rejected.</div><?php endif; ?>

<!-- Stats -->
<div class="sum-row">
    <div class="sc"><div class="sv" style="color:var(--a)"><?=$cmap["pending"]??0?></div><div class="sl">Pending</div></div>
    <div class="sc"><div class="sv" style="color:var(--g)"><?=$cmap["approved"]??0?></div><div class="sl">Approved</div></div>
    <div class="sc"><div class="sv" style="color:var(--r)"><?=$cmap["rejected"]??0?></div><div class="sl">Rejected</div></div>
    <div class="sc"><div class="sv"><?=array_sum($cmap)?></div><div class="sl">Total</div></div>
</div>

<!-- Tabs -->
<div class="tabs">
    <?php foreach(["pending"=>"⏳ Pending","approved"=>"✅ Approved","rejected"=>"❌ Rejected","all"=>"All"] as $s=>$lbl): ?>
    <a class="tab <?=$s===$filterStatus?"active":""?>" href="hr_leave.php?status=<?=$s?>">
        <?=$lbl?> <span class="count-pill"><?=$cmap[$s]??0?></span>
    </a>
    <?php endforeach; ?>
</div>

<!-- Leave cards -->
<?php if(empty($leaves)): ?>
<div class="empty"><div class="icon">🏖️</div><p>No <?=$filterStatus==="all"?"":$filterStatus?> leave requests.</p></div>
<?php else: ?>
<div class="leave-list">
<?php foreach($leaves as $l):
    $c=$sc[$l["status"]]??["#f1f5f9","#475569"];
    $days=(int)$l["days"];
?>
<div class="leave-card">
    <div class="lc-top">
        <div>
            <div class="staff-name"><?=htmlspecialchars($l["staff_name"])?></div>
            <div class="staff-meta"><?=htmlspecialchars($l["position"]??"")?>
                <?php if($l["department"]): ?> · <?=htmlspecialchars($l["department"])?><?php endif; ?></div>
        </div>
        <div style="display:flex;flex-direction:column;align-items:flex-end;gap:6px">
            <span class="badge" style="background:<?=$c[0]?>;color:<?=$c[1]?>"><?=ucfirst($l["status"])?></span>
            <span style="font-size:11px;color:var(--m)"><?=date("d M Y",strtotime($l["created_at"]))?></span>
        </div>
    </div>
    <div class="lc-info">
        <div class="info-item"><div class="lbl">Type</div><div class="val"><?=$typeLabels[$l["leave_type"]]??$l["leave_type"]?></div></div>
        <div class="info-item"><div class="lbl">From</div><div class="val"><?=date("d M Y",strtotime($l["start_date"]))?></div></div>
        <div class="info-item"><div class="lbl">To</div><div class="val"><?=date("d M Y",strtotime($l["end_date"]))?></div></div>
        <div class="info-item"><div class="lbl">Days</div><div class="val" style="color:var(--p);font-size:16px"><?=$days?> day<?=$days!==1?"s":""?></div></div>
    </div>
    <?php if($l["reason"]): ?>
    <div class="reason-box">💬 <?=htmlspecialchars($l["reason"])?></div>
    <?php endif; ?>
    <?php if($l["status"]==="pending"): ?>
    <div class="lc-actions">
        <form method="POST" style="display:inline" onsubmit="return confirm('Approve this leave request?')">
            <input type="hidden" name="review"   value="1">
            <input type="hidden" name="leave_id" value="<?=$l["id"]?>">
            <input type="hidden" name="action"   value="approved">
            <button class="btn-approve" type="submit">✅ Approve</button>
        </form>
        <form method="POST" style="display:inline" onsubmit="return confirm('Reject this leave request?')">
            <input type="hidden" name="review"   value="1">
            <input type="hidden" name="leave_id" value="<?=$l["id"]?>">
            <input type="hidden" name="action"   value="rejected">
            <button class="btn-reject" type="submit">❌ Reject</button>
        </form>
    </div>
    <?php endif; ?>
</div>
<?php endforeach; ?>
</div>
<?php endif; ?>

</div>
</body>
</html>