<?php
ob_start();
session_start();
if (!isset($_SESSION["user_id"]) || empty($_SESSION["company_id"])) { header("Location: ../auth/login.php"); exit; }
require_once '../config/database.php';
require_once '../config/approvals.php';
$companyId = (int)$_SESSION["company_id"];
$me        = (int)$_SESSION["user_id"];
$isAdmin   = ($_SESSION["role"] ?? '') === 'company_admin';
// Admins and configured reviewers (dept manager / Operation Manager / Owner / delegate) may open this page.
if (!$isAdmin && !appr_is_reviewer($pdo, $companyId, $me)) { header("Location: ../customer/desktop.php"); exit; }
// Back button target: admins go to the company dashboard, staff managers to their own home.
$backUrl = $isAdmin ? 'dashboard.php' : '../customer/company_home.php';
$apprSet = appr_settings($pdo, $companyId);
$opsId   = (int)$apprSet['ops'];   // Operation Manager (final approver), 0 if none

/* Make sure the reviewer columns exist (blank page if an UPDATE hits a missing column). */
foreach ([
    'reviewed_by'      => 'INT NULL',
    'dept_reviewed_by' => 'INT NULL',
    'dept_reviewed_at' => 'DATETIME NULL',
    'mgr_reviewed_by'  => 'INT NULL',
    'mgr_reviewed_at'  => 'DATETIME NULL',
] as $col => $ddl) {
    try {
        if (!$pdo->query("SHOW COLUMNS FROM hr_leave LIKE ".$pdo->quote($col))->fetch()) {
            $pdo->exec("ALTER TABLE hr_leave ADD COLUMN `$col` $ddl");
        }
    } catch (Throwable $e) {}
}
/* The status column may be an ENUM that predates the 'dept_ok' stage — widen it
   to VARCHAR so all workflow values (pending, dept_ok, approved, rejected) fit. */
try {
    $sc = $pdo->query("SHOW COLUMNS FROM hr_leave LIKE 'status'")->fetch(PDO::FETCH_ASSOC);
    if ($sc && stripos((string)$sc['Type'], 'varchar') === false) {
        $pdo->exec("ALTER TABLE hr_leave MODIFY COLUMN `status` VARCHAR(20) NOT NULL DEFAULT 'pending'");
    }
} catch (Throwable $e) {}
// Departments this non-admin manages (for filtering the list + authorizing approval).
$myDeptNames = [];
$iAmOpsOrOwner = false;
if (!$isAdmin) {
    $iAmOpsOrOwner =
        ($apprSet['ops'] === $me) || ($apprSet['owner'] === $me) ||
        ($apprSet['ops'] > 0   && appr_delegate_of($pdo,$companyId,$apprSet['ops'])   === $me) ||
        ($apprSet['owner'] > 0 && appr_delegate_of($pdo,$companyId,$apprSet['owner']) === $me);
    try {
        $dq = $pdo->prepare("SELECT name FROM company_departments WHERE company_id=? AND manager_user_id=?");
        $dq->execute([$companyId, $me]);
        foreach ($dq->fetchAll(PDO::FETCH_COLUMN) as $dn) { $myDeptNames[] = mb_strtolower(trim((string)$dn)); }
        // also departments where I'm the manager's delegate
        $dq2 = $pdo->prepare("SELECT name, manager_user_id FROM company_departments WHERE company_id=? AND manager_user_id IS NOT NULL");
        $dq2->execute([$companyId]);
        foreach ($dq2->fetchAll(PDO::FETCH_ASSOC) as $row) {
            if (appr_delegate_of($pdo,$companyId,(int)$row['manager_user_id']) === $me) { $myDeptNames[] = mb_strtolower(trim((string)$row['name'])); }
        }
    } catch (Throwable $e) {}
    $myDeptNames = array_values(array_unique($myDeptNames));
}

/* ── Approve / Reject (two-stage when an Operation Manager is set) ── */
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST["review"])) {
  try {
    $id   = (int)$_POST["leave_id"];
    $want = $_POST["action"] === "approved" ? "approve" : "reject";
    $r = $pdo->prepare("SELECT l.staff_id, l.status, cs.department
                        FROM hr_leave l
                        LEFT JOIN company_staff cs ON cs.user_id=l.staff_id AND cs.company_id=l.company_id
                        WHERE l.id=? AND l.company_id=? LIMIT 1");
    $r->execute([$id, $companyId]); $req = $r->fetch(PDO::FETCH_ASSOC);
    $msg = "noauth";
    if ($req) {
        $staff    = (int)$req['staff_id'];
        $inProg   = in_array($req['status'],['pending','dept_ok'],true);
        $reqDept  = mb_strtolower(trim((string)($req['department'] ?? '')));
        $canFinal = $isAdmin || $iAmOpsOrOwner;                                   // admin / Operation Manager / Owner finalize
        $isDeptMgr = (!$isAdmin && !$iAmOpsOrOwner && $reqDept !== '' && in_array($reqDept, $myDeptNames, true));

        if ($canFinal && $inProg) {
            if ($want === "reject") {
                $pdo->prepare("UPDATE hr_leave SET status='rejected', reviewed_by=?, mgr_reviewed_by=?, mgr_reviewed_at=NOW() WHERE id=? AND company_id=?")->execute([$me,$me,$id,$companyId]);
                notify_user($pdo,$staff,"❌ Leave rejected","Your leave request was rejected.","staff/leave.php");
                $msg = "rejected";
            } else {
                $pdo->prepare("UPDATE hr_leave SET status='approved', reviewed_by=?, mgr_reviewed_by=?, mgr_reviewed_at=NOW() WHERE id=? AND company_id=?")->execute([$me,$me,$id,$companyId]);
                notify_user($pdo,$staff,"✅ Leave approved","Your leave request was approved.","staff/leave.php");
                $msg = "approved";
            }
        } elseif ($isDeptMgr && $req['status'] === 'pending') {
            /* Department manager acts on the FIRST stage for their own department's staff. */
            if ($want === "reject") {
                $pdo->prepare("UPDATE hr_leave SET status='rejected', reviewed_by=?, dept_reviewed_by=?, dept_reviewed_at=NOW() WHERE id=? AND company_id=?")->execute([$me,$me,$id,$companyId]);
                notify_user($pdo,$staff,"❌ Leave rejected","Your leave request was rejected.","staff/leave.php");
                $msg = "rejected";
            } elseif ($opsId > 0) {
                $pdo->prepare("UPDATE hr_leave SET status='dept_ok', dept_reviewed_by=?, dept_reviewed_at=NOW() WHERE id=? AND company_id=?")->execute([$me,$id,$companyId]);
                notify_user($pdo,$opsId,"🏖️ Leave needs final approval","A leave request passed the department manager.","company/hr_leave.php");
                $msg = "dept_ok";
            } else {
                $pdo->prepare("UPDATE hr_leave SET status='approved', reviewed_by=?, dept_reviewed_by=?, dept_reviewed_at=NOW() WHERE id=? AND company_id=?")->execute([$me,$me,$id,$companyId]);
                notify_user($pdo,$staff,"✅ Leave approved","Your leave request was approved.","staff/leave.php");
                $msg = "approved";
            }
        } elseif (false) {
            /* one-step legacy */
            $action = $want === "approve" ? "approved" : "rejected";
            $pdo->prepare("UPDATE hr_leave SET status=?, reviewed_by=? WHERE id=? AND company_id=?")->execute([$action,$me,$id,$companyId]);
            notify_user($pdo,$staff, $action==='approved'?"✅ Leave approved":"❌ Leave rejected", $action==='approved'?"Your leave request was approved.":"Your leave request was rejected.","staff/leave.php");
            $msg = $action;
        }
    }
  } catch (Throwable $e) {
      if (ob_get_level()) ob_end_clean();
      http_response_code(500);
      echo '<div style="font-family:sans-serif;padding:24px;color:#b91c1c;font-size:15px;line-height:1.5;">'
         . '<b>Approval error</b><br>'.htmlspecialchars($e->getMessage())
         . '<br><br><a href="hr_leave.php" style="color:#2563eb;">← Back</a></div>';
      exit;
  }
    header("Location: hr_leave.php?msg=$msg"); exit;
}

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

$isDeptMgrView = (!$isAdmin && !$iAmOpsOrOwner);

/* Which tab a status belongs to, from THIS viewer's perspective.
   A department manager's job ends once he approves (status -> dept_ok), so
   for him dept_ok/approved both count as "Approved" and leave his Pending. */
function leave_bucket($status, $isDeptMgrView){
    $s = strtolower((string)$status);
    if ($s === 'rejected') return 'rejected';
    if ($isDeptMgrView) {
        if ($s === 'pending') return 'pending';
        if ($s === 'dept_ok' || $s === 'approved') return 'approved';
        return 'other';
    }
    if ($s === 'approved') return 'approved';
    if ($s === 'pending' || $s === 'dept_ok') return 'pending';
    return 'other';
}

/* Fetch everything, then scope + bucket in PHP so stats, tabs and list agree. */
$allLeaves = $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=?
    ORDER BY l.created_at DESC
    LIMIT 300
");
$allLeaves->execute([$companyId]);
$allLeaves = $allLeaves->fetchAll(PDO::FETCH_ASSOC);

// department managers only see their own department(s)
if ($isDeptMgrView) {
    $allLeaves = array_values(array_filter($allLeaves, function($l) use ($myDeptNames) {
        return in_array(mb_strtolower(trim((string)($l['department'] ?? ''))), $myDeptNames, true);
    }));
}

// counts per tab (match what this viewer sees)
$cmap = ["pending"=>0,"approved"=>0,"rejected"=>0];
foreach ($allLeaves as $l) { $b = leave_bucket($l['status'], $isDeptMgrView); if (isset($cmap[$b])) $cmap[$b]++; }
$cmap["all"] = count($allLeaves);

// displayed list = the selected tab
if ($filterStatus === 'all') {
    $leaves = $allLeaves;
} else {
    $leaves = array_values(array_filter($allLeaves, function($l) use ($filterStatus, $isDeptMgrView) {
        return leave_bucket($l['status'], $isDeptMgrView) === $filterStatus;
    }));
}

$msg = $_GET["msg"] ?? "";
$typeLabels = ["annual"=>"🏖️ Annual","sick"=>"🤒 Sick","short"=>"⏱️ Short-term","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="<?= htmlspecialchars($backUrl) ?>"<?= $isAdmin ? '' : ' onclick="if(document.referrer){history.back();return false;}"' ?>>← <?= $isAdmin ? 'Dashboard' : 'Home' ?></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==="dept_ok"): ?><div class="alert al-ok">✅ Approved — sent to the Operation Manager for final approval.</div>
<?php elseif($msg==="rejected"): ?><div class="alert al-rj">❌ Leave request rejected.</div>
<?php elseif($msg==="noauth"): ?><div class="alert al-rj">⚠️ You are not the approver for this request at its current stage.</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"><?=$cmap["all"]?? (($cmap["pending"]??0)+($cmap["approved"]??0)+($cmap["rejected"]??0))?></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<?= (!$isAdmin && !$iAmOpsOrOwner) ? ' for your department' : '' ?>.</p>
<?php if(!$isAdmin && !$iAmOpsOrOwner && empty($myDeptNames)): ?>
<p style="margin-top:10px;font-size:13px;color:#94a3b8;">You aren't set as a department manager yet. Ask your admin to set you as your department's Manager in <b>Approval Settings</b>.</p>
<?php endif; ?>
</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">
            <?php $lab = appr_label($l["status"]); $lc=["amber"=>["#fef3c7","#d97706"],"blue"=>["#dbeafe","#1e40af"],"green"=>["#dcfce7","#16a34a"],"red"=>["#fee2e2","#dc2626"],"gray"=>["#f1f5f9","#475569"]][$lab[0]]; ?>
            <span class="badge" style="background:<?=$lc[0]?>;color:<?=$lc[1]?>"><?=htmlspecialchars($lab[1])?></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
    /* who can act on this row */
    $inProgress = in_array($l["status"],["pending","dept_ok"],true);
    if ($isAdmin || $iAmOpsOrOwner) {
        // admin / Operation Manager / Owner can finalize any in-progress request
        $canApprove = $inProgress;
        $canReject  = $inProgress;
        $approveLabel = "✅ Approve";
    } else {
        // department manager: acts on the FIRST stage for their own department's staff
        $inMyDept = in_array(mb_strtolower(trim((string)($l["department"] ?? ''))), $myDeptNames, true);
        $canApprove = ($l["status"]==="pending") && $inMyDept;
        $canReject  = $canApprove;
        $approveLabel = ($opsId > 0) ? "✅ Approve (to Manager)" : "✅ Approve";
    }
    ?>
    <?php if($canApprove || $canReject): ?>
    <div class="lc-actions">
        <?php if($canApprove): ?>
        <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"><?=$approveLabel?></button>
        </form>
        <?php endif; ?>
        <?php if($canReject): ?>
        <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>
        <?php endif; ?>
    </div>
    <?php endif; ?>
</div>
<?php endforeach; ?>
</div>
<?php endif; ?>

</div>
<?php require __DIR__ . '/../config/auto_update.php'; ?>
</body>
</html>