<?php
/* ============================================================================
 *  company/ot_approvals.php — Phase C
 *  Manager approves / rejects overtime captured at check-out.
 *  Only APPROVED overtime is paid by the payroll generator.
 *  Bilingual EN/Lao · dd/mm/yyyy.
 * ==========================================================================*/
session_start();

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

require_once '../config/database.php';
require_once '../config/approvals.php';
date_default_timezone_set('Asia/Vientiane');

$companyId   = (int)$_SESSION["company_id"];
$companyName = $_SESSION["company_name"] ?? "My Company";
$me          = (int)$_SESSION["user_id"];

/* ── POST: approve / reject (single or bulk) ── */
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    try {
        $decision = $_POST["decision"] ?? '';
        $ids = array_filter(array_map('intval', (array)($_POST["att_id"] ?? [])));
        if ($ids && in_array($decision, ['approved','rejected'], true)) {
            if (appr_enabled($pdo, $companyId)) {
                /* two-stage: process each row through the chain */
                $sel = $pdo->prepare("SELECT staff_id, ot_status FROM hr_attendance WHERE id=? AND company_id=? AND ot_minutes>0 LIMIT 1");
                $done = 0;
                foreach ($ids as $aid) {
                    $sel->execute([$aid, $companyId]); $row = $sel->fetch(PDO::FETCH_ASSOC);
                    if (!$row) continue;
                    $staff = (int)$row['staff_id']; $cur = $row['ot_status'] ?: 'pending';
                    $ctx = appr_ctx($pdo, $companyId, $me, $staff);
                    if ($decision === 'rejected' && appr_can_reject($cur, $ctx)) {
                        $pdo->prepare("UPDATE hr_attendance SET ot_status='rejected', ot_mgr_reviewed_by=?, ot_mgr_reviewed_at=NOW() WHERE id=? AND company_id=?")->execute([$me,$aid,$companyId]);
                        notify_user($pdo,$staff,"❌ OT rejected","Your overtime was not approved.","staff/my_attendance.php"); $done++;
                    } elseif ($decision === 'approved' && ($next = appr_next($cur, $ctx))) {
                        if ($next === 'dept_ok') {
                            $pdo->prepare("UPDATE hr_attendance SET ot_status='dept_ok', ot_dept_reviewed_by=?, ot_dept_reviewed_at=NOW() WHERE id=? AND company_id=?")->execute([$me,$aid,$companyId]);
                            if ($ctx['ops']) notify_user($pdo,$ctx['ops'],"⏱️ OT needs final approval","Overtime passed the department manager.","company/ot_approvals.php");
                        } else {
                            $pdo->prepare("UPDATE hr_attendance SET ot_status='approved', ot_mgr_reviewed_by=?, ot_mgr_reviewed_at=NOW() WHERE id=? AND company_id=?")->execute([$me,$aid,$companyId]);
                            notify_user($pdo,$staff,"✅ OT approved","Your overtime was approved.","staff/my_attendance.php");
                        }
                        $done++;
                    }
                }
                $_SESSION["ot_flash"] = $done
                    ? ["ok","Updated {$done} overtime record(s).","ປັບປຸງ OT {$done} ລາຍການ."]
                    : ["err","Nothing updated — you may not be the approver at this stage.","ບໍ່ມີການປ່ຽນແປງ."];
            } else {
                /* legacy one-step bulk */
                $in = implode(',', array_fill(0, count($ids), '?'));
                $params = array_merge([$decision], $ids, [$companyId]);
                $pdo->prepare("UPDATE hr_attendance SET ot_status=? WHERE id IN ($in) AND company_id=?")->execute($params);
                $_SESSION["ot_flash"] = ["ok",
                    ($decision==='approved'?"Overtime approved.":"Overtime rejected."),
                    ($decision==='approved'?"ອະນຸມັດ OT ແລ້ວ.":"ປະຕິເສດ OT ແລ້ວ.")];
            }
        }
    } catch (Throwable $e) {
        $_SESSION["ot_flash"] = ["err", "Error: ".$e->getMessage(), "ຜິດພາດ: ".$e->getMessage()];
    }
    header("Location: ot_approvals.php" . (isset($_POST['view']) ? "?view=".urlencode($_POST['view']) : ""));
    exit;
}

$view  = $_GET["view"] ?? "pending";   // pending | approved | rejected
$valid = ['pending','approved','rejected'];
if (!in_array($view, $valid, true)) $view = "pending";

$statusIn = $view === 'pending' ? "a.ot_status IN ('pending','dept_ok')" : "a.ot_status = ?";
$sql = "
    SELECT a.*, u.name AS staff_name, s.name AS shift_name
    FROM hr_attendance a
    JOIN users u ON u.id = a.staff_id
    LEFT JOIN att_shifts s ON s.id = a.shift_id
    WHERE a.company_id = ? AND a.ot_minutes > 0 AND $statusIn
    ORDER BY a.work_date DESC, u.name
    LIMIT 300";
$rows = $pdo->prepare($sql);
$rows->execute($view === 'pending' ? [$companyId] : [$companyId, $view]);
$rows = $rows->fetchAll(PDO::FETCH_ASSOC);

/* counts for tabs */
$cnt = ['pending'=>0,'approved'=>0,'rejected'=>0,'dept_ok'=>0];
$cst = $pdo->prepare("SELECT ot_status, COUNT(*) c FROM hr_attendance WHERE company_id=? AND ot_minutes>0 GROUP BY ot_status");
$cst->execute([$companyId]);
foreach ($cst->fetchAll(PDO::FETCH_ASSOC) as $r) { if (isset($cnt[$r['ot_status']])) $cnt[$r['ot_status']] = (int)$r['c']; }
$cnt['pending'] += $cnt['dept_ok'];   // pending tab = both in-progress stages

$flash = $_SESSION["ot_flash"] ?? null;
unset($_SESSION["ot_flash"]);

function fmtMin($m){ $m=(int)$m; $h=intdiv($m,60); $r=$m%60; return ($h?"{$h}h ":"")."{$r}m"; }
?>
<!DOCTYPE html>
<html lang="lo">
<head>
    <?php $pwaTheme = '#0f766e'; include __DIR__ . '/../config/pwa_head.php'; ?>
    <title><?= htmlspecialchars($companyName) ?> — OT Approvals</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">
    <script src="../assets/lang.js" defer></script>
    <style>
        *,*::before,*::after{box-sizing:border-box;margin:0;padding:0;}
        :root{--primary:#0f766e;--surface:#fff;--bg:#f0f4f8;--border:#e2e8f0;--text:#0f172a;--muted:#64748b;
            --green:#16a34a;--green-lt:#dcfce7;--red:#dc2626;--red-lt:#fee2e2;--amber:#d97706;--amber-lt:#fef3c7;
            --blue:#2563eb;--blue-lt:#dbeafe;--radius:16px;--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 24px;display:flex;
            justify-content:space-between;align-items:center;gap:16px;position:sticky;top:0;z-index:100;
            box-shadow:0 1px 6px rgba(15,23,42,.06);flex-wrap:wrap;}
        .brand{display:flex;align-items:center;gap:10px;}
        .brand-logo{width:34px;height:34px;background:linear-gradient(135deg,#084740,#0f766e);border-radius:9px;
            display:flex;align-items:center;justify-content:center;color:#fff;font-weight:800;font-size:14px;}
        .brand-name{font-size:14px;font-weight:700;}.brand-sub{font-size:11px;color:var(--muted);}
        .top-right{display:flex;align-items:center;gap:12px;}
        .lang-btn{padding:4px 11px;border-radius:999px;border:1.5px solid var(--border);background:var(--surface);
            font-size:11px;font-weight:700;color:var(--muted);cursor:pointer;font-family:inherit;}
        .lang-btn.active{background:var(--primary);border-color:var(--primary);color:#fff;}
        .back-link{background:#f1f5f9;color:var(--text);border:1.5px solid var(--border);padding:6px 13px;
            border-radius:8px;text-decoration:none;font-size:12px;font-weight:700;}
        .page{padding:24px;max-width:1000px;margin:auto;}
        .hero{background:linear-gradient(135deg,#042f2e,#0f766e);border-radius:18px;padding:22px 26px;margin-bottom:20px;color:#fff;}
        .hero h1{font-size:22px;font-weight:800;margin-bottom:4px;}
        .hero p{font-size:13px;color:rgba(255,255,255,.8);}
        .tabs{display:flex;gap:8px;margin-bottom:18px;flex-wrap:wrap;}
        .tab{padding:9px 16px;border-radius:999px;border:1.5px solid var(--border);background:var(--surface);
            text-decoration:none;font-size:13px;font-weight:700;color:var(--muted);display:inline-flex;gap:7px;align-items:center;}
        .tab.active{background:var(--primary);border-color:var(--primary);color:#fff;}
        .tab .b{background:rgba(0,0,0,.12);padding:1px 8px;border-radius:999px;font-size:11px;}
        .tab.active .b{background:rgba(255,255,255,.25);}
        .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;font-size:13px;}
        th{text-align:left;font-size:11px;text-transform:uppercase;letter-spacing:.4px;color:var(--muted);
            padding:11px 12px;border-bottom:2px solid var(--border);background:#f8fafc;}
        td{padding:11px 12px;border-bottom:1px solid var(--border);vertical-align:middle;}
        tr:last-child td{border-bottom:none;}
        .empty{color:var(--muted);font-size:14px;padding:30px;text-align:center;}
        .staffname{font-weight:700;}
        .tag{display:inline-block;padding:2px 9px;border-radius:999px;font-size:11px;font-weight:800;}
        .tag.blue{background:var(--blue-lt);color:#1e40af;}.tag.green{background:var(--green-lt);color:#15803d;}
        .tag.red{background:var(--red-lt);color:#991b1b;}.tag.gray{background:#f1f5f9;color:var(--muted);}
        .btn{padding:8px 14px;border-radius:8px;border:none;font-size:12px;font-weight:700;cursor:pointer;font-family:inherit;}
        .btn-ok{background:var(--green);color:#fff;}.btn-no{background:var(--red-lt);color:var(--red);border:1.5px solid #fca5a5;}
        .flash{padding:12px 16px;border-radius:10px;margin-bottom:18px;font-size:14px;font-weight:600;}
        .flash.ok{background:var(--green-lt);color:#15803d;}.flash.err{background:var(--red-lt);color:var(--red);}
        .bulk{display:flex;gap:10px;align-items:center;padding:12px;border-top:1px solid var(--border);background:#f8fafc;flex-wrap:wrap;}
        .tbl-wrap{overflow-x:auto;}
        @media(max-width:640px){.page{padding:14px;}table{min-width:640px;}}
    </style>
</head>
<body>

<div class="top-bar">
    <div class="brand">
        <div class="brand-logo">CO</div>
        <div>
            <div class="brand-name"><?= htmlspecialchars($companyName) ?></div>
            <div class="brand-sub" data-lo="ອະນຸມັດ OT" data-en="OT Approvals">ອະນຸມັດ OT</div>
        </div>
    </div>
    <div class="top-right">
        <button class="lang-btn" id="btn-lo" onclick="setLang('lo')">🇱🇦 ລາວ</button>
        <button class="lang-btn" id="btn-en" onclick="setLang('en')">🇬🇧 EN</button>
        <a class="back-link" href="dashboard.php">← <span data-lo="ກັບຄືນ" data-en="Back">ກັບຄືນ</span></a>
    </div>
</div>

<div class="page">

    <div class="hero">
        <h1 data-lo="ອະນຸມັດໂມງລ່ວງເວລາ (OT)" data-en="Overtime Approvals">ອະນຸມັດໂມງລ່ວງເວລາ (OT)</h1>
        <p data-lo="ກວດ ແລະ ອະນຸມັດ OT ທີ່ລະບົບບັນທຶກຕອນລົງອອກ. ສະເພາະ OT ທີ່ອະນຸມັດເທົ່ານັ້ນຈຶ່ງຈ່າຍເງິນ."
           data-en="Review the overtime the system captured at check-out. Only approved OT is paid.">
           Only approved OT is paid.
        </p>
    </div>

    <?php if ($flash): ?>
        <div class="flash <?= $flash[0]==='ok'?'ok':'err' ?>" data-en="<?= htmlspecialchars($flash[1]) ?>" data-lo="<?= htmlspecialchars($flash[2]) ?>"><?= htmlspecialchars($flash[2]) ?></div>
    <?php endif; ?>

    <div class="tabs">
        <a class="tab <?= $view==='pending'?'active':'' ?>" href="?view=pending">
            <span data-lo="ລໍຖ້າ" data-en="Pending">Pending</span><span class="b"><?= $cnt['pending'] ?></span></a>
        <a class="tab <?= $view==='approved'?'active':'' ?>" href="?view=approved">
            <span data-lo="ອະນຸມັດ" data-en="Approved">Approved</span><span class="b"><?= $cnt['approved'] ?></span></a>
        <a class="tab <?= $view==='rejected'?'active':'' ?>" href="?view=rejected">
            <span data-lo="ປະຕິເສດ" data-en="Rejected">Rejected</span><span class="b"><?= $cnt['rejected'] ?></span></a>
    </div>

    <form method="POST" id="otForm">
        <input type="hidden" name="view" value="<?= htmlspecialchars($view) ?>">
        <input type="hidden" name="decision" id="decision" value="">
        <div class="card">
            <div class="tbl-wrap">
            <table>
                <thead><tr>
                    <?php if ($view==='pending'): ?><th style="width:34px"><input type="checkbox" onclick="toggleAll(this)"></th><?php endif; ?>
                    <th data-lo="ວັນທີ" data-en="Date">Date</th>
                    <th data-lo="ພະນັກງານ" data-en="Staff">Staff</th>
                    <th data-lo="ກະ" data-en="Shift">Shift</th>
                    <th data-lo="ເຂົ້າ-ອອກ" data-en="In–Out">In–Out</th>
                    <th data-lo="OT" data-en="OT">OT</th>
                    <?php if ($view!=='pending'): ?><th data-lo="ສະຖານະ" data-en="Status">Status</th><?php endif; ?>
                </tr></thead>
                <tbody>
                <?php if (!$rows): ?>
                    <tr><td colspan="7" class="empty" data-lo="ບໍ່ມີລາຍການ." data-en="Nothing here.">Nothing here.</td></tr>
                <?php else: foreach ($rows as $r): ?>
                    <tr>
                        <?php if ($view==='pending'): ?>
                        <td><input type="checkbox" class="rowchk" name="att_id[]" value="<?= (int)$r['id'] ?>"></td>
                        <?php endif; ?>
                        <td><strong><?= date('d/m/Y', strtotime($r['work_date'])) ?></strong></td>
                        <td class="staffname"><?= htmlspecialchars($r['staff_name']) ?>
                            <?php if ($view==='pending' && ($r['ot_status']??'')==='dept_ok'): ?>
                                <span class="tag blue" data-lo="ລໍຖ້າ: ຜູ້ຈັດການ" data-en="Waiting: Operation Mgr">Waiting: Operation Mgr</span>
                            <?php elseif ($view==='pending'): ?>
                                <span class="tag amber" data-lo="ລໍຖ້າ: ຫົວໜ້າພະແນກ" data-en="Waiting: Dept Mgr">Waiting: Dept Mgr</span>
                            <?php endif; ?>
                        </td>
                        <td><?= $r['shift_name'] ? htmlspecialchars($r['shift_name']) : '<span class="tag gray">—</span>' ?></td>
                        <td><?= $r['check_in']?substr($r['check_in'],0,5):'—' ?> – <?= $r['check_out']?substr($r['check_out'],0,5):'—' ?></td>
                        <td><span class="tag blue"><?= fmtMin($r['ot_minutes']) ?></span></td>
                        <?php if ($view!=='pending'): ?>
                        <td><?= $view==='approved'
                                ? '<span class="tag green" data-lo="ອະນຸມັດ" data-en="Approved">Approved</span>'
                                : '<span class="tag red" data-lo="ປະຕິເສດ" data-en="Rejected">Rejected</span>' ?></td>
                        <?php endif; ?>
                    </tr>
                <?php endforeach; endif; ?>
                </tbody>
            </table>
            </div>

            <?php if ($view==='pending' && $rows): ?>
            <div class="bulk">
                <span style="font-size:12px;color:var(--muted);" data-lo="ເລືອກລາຍການ ແລ້ວ:" data-en="Select rows, then:">Select rows, then:</span>
                <button type="button" class="btn btn-ok" onclick="submitDecision('approved')" data-lo="✓ ອະນຸມັດ" data-en="✓ Approve">✓ Approve</button>
                <button type="button" class="btn btn-no" onclick="submitDecision('rejected')" data-lo="✕ ປະຕິເສດ" data-en="✕ Reject">✕ Reject</button>
            </div>
            <?php endif; ?>
        </div>
    </form>

    <div style="text-align:center;color:var(--muted);font-size:12px;padding:14px 0 24px;">
        <a href="payroll_generate.php" style="color:var(--primary);font-weight:700;text-decoration:none;"
           data-lo="ໄປສ້າງເງິນເດືອນຈາກການເຂົ້າວຽກ →" data-en="Go to payroll generation →">Go to payroll generation →</a>
    </div>

</div>

<script>
function toggleAll(box){ document.querySelectorAll('.rowchk').forEach(c=>c.checked=box.checked); }
function submitDecision(d){
    const any = document.querySelectorAll('.rowchk:checked').length;
    if (!any){ alert(window._lang==='en'?'Select at least one row.':'ກະລຸນາເລືອກຢ່າງໜ້ອຍໜຶ່ງລາຍການ.'); return; }
    document.getElementById('decision').value = d;
    document.getElementById('otForm').submit();
}
</script>

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