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

/* ── Save attendance ── */
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST["save_att"])) {
    $staffId   = (int)$_POST["staff_id"];
    $workDate  = $_POST["work_date"] ?? date("Y-m-d");
    $checkIn   = $_POST["check_in"]  ?: null;
    $checkOut  = $_POST["check_out"] ?: null;
    $status    = $_POST["status"]    ?? "present";
    $note      = trim($_POST["note"] ?? "");
    $allowed   = ["present","absent","late","half_day","holiday"];
    if (!in_array($status, $allowed)) $status = "present";

    $hours = null;
    if ($checkIn && $checkOut) {
        $diff  = strtotime($checkOut) - strtotime($checkIn);
        $hours = $diff > 0 ? round($diff / 3600, 2) : null;
    }

    $chk = $pdo->prepare("SELECT id FROM hr_attendance WHERE staff_id=? AND company_id=? AND work_date=?");
    $chk->execute([$staffId, $companyId, $workDate]);
    $existId = $chk->fetchColumn();

    if ($existId) {
        $pdo->prepare("UPDATE hr_attendance SET check_in=?,check_out=?,hours_worked=?,status=?,note=? WHERE id=?")
            ->execute([$checkIn, $checkOut, $hours, $status, $note, $existId]);
    } else {
        $pdo->prepare("INSERT INTO hr_attendance (staff_id,company_id,work_date,check_in,check_out,hours_worked,status,note) VALUES (?,?,?,?,?,?,?,?)")
            ->execute([$staffId, $companyId, $workDate, $checkIn, $checkOut, $hours, $status, $note]);
    }
    $fm = date("n", strtotime($workDate));
    $fy = date("Y", strtotime($workDate));
    header("Location: hr_attendance.php?msg=saved&month=$fm&year=$fy&staff_id=$staffId"); exit;
}

/* ── Delete ── */
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST["del_att"])) {
    $pdo->prepare("DELETE FROM hr_attendance WHERE id=? AND company_id=?")->execute([(int)$_POST["att_id"], $companyId]);
    header("Location: hr_attendance.php?msg=deleted&month={$_POST['month']}&year={$_POST['year']}&staff_id={$_POST['staff_id']}"); exit;
}

$fm       = (int)($_GET["month"]    ?? date("n"));
$fy       = (int)($_GET["year"]     ?? date("Y"));
$selStaff = (int)($_GET["staff_id"] ?? 0);
$msg      = $_GET["msg"] ?? "";

$allStaff = $pdo->prepare("SELECT u.id,u.name,cs.department FROM company_staff cs JOIN users u ON u.id=cs.user_id WHERE cs.company_id=? AND u.status='active' ORDER BY u.name");
$allStaff->execute([$companyId]);
$allStaff = $allStaff->fetchAll(PDO::FETCH_ASSOC);

if (!$selStaff && !empty($allStaff)) $selStaff = $allStaff[0]["id"];

$attRows = [];
if ($selStaff) {
    $st = $pdo->prepare("SELECT * FROM hr_attendance WHERE staff_id=? AND company_id=? AND MONTH(work_date)=? AND YEAR(work_date)=? ORDER BY work_date DESC");
    $st->execute([$selStaff, $companyId, $fm, $fy]);
    $attRows = $st->fetchAll(PDO::FETCH_ASSOC);
}

$mn = ["","January","February","March","April","May","June","July","August","September","October","November","December"];
$sc = ["present"=>["#dcfce7","#16a34a"],"absent"=>["#fee2e2","#dc2626"],"late"=>["#fef3c7","#d97706"],"half_day"=>["#ede9fe","#7c3aed"],"holiday"=>["#dbeafe","#2563eb"]];

/* Stats */
$stats = ["present"=>0,"absent"=>0,"late"=>0,"half_day"=>0,"holiday"=>0];
$totalHours = 0;
foreach ($attRows as $r) { if (isset($stats[$r["status"]])) $stats[$r["status"]]++; $totalHours += (float)$r["hours_worked"]; }
?>
<!DOCTYPE html>
<html lang="lo">
<head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Attendance — <?= 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;--bl:#2563eb;--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:1200px;margin:auto}
.alert{padding:12px 16px;border-radius:10px;margin-bottom:18px;font-size:13px;font-weight:600}
.al-s{background:var(--gl);color:var(--g);border:1.5px solid #86efac}
.al-d{background:var(--rl);color:var(--r);border:1.5px solid #fca5a5}
.fbar{display:flex;align-items:center;gap:10px;margin-bottom:18px;flex-wrap:wrap}
.fbar select{padding:9px 13px;border:1.5px solid var(--b);border-radius:9px;font-size:13px;font-family:inherit;outline:none;background:var(--s)}
.fbar select:focus{border-color:var(--p)}
.btn{display:inline-flex;align-items:center;gap:6px;padding:9px 18px;border-radius:9px;font-size:13px;font-weight:700;font-family:inherit;cursor:pointer;border:none;text-decoration:none;transition:all .15s}
.btn-p{background:linear-gradient(135deg,#084740,#0f766e);color:#fff}.btn-p:hover{opacity:.9}
.sum-row{display:grid;grid-template-columns:repeat(auto-fill,minmax(130px,1fr));gap:10px;margin-bottom:18px}
.sc{background:var(--s);border-radius:12px;padding:12px 16px;box-shadow:var(--sh);border:1px solid var(--b);text-align:center}
.sc .sv{font-size:22px;font-weight:800;margin-bottom:2px}
.sc .sl{font-size:11px;color:var(--m);font-weight:600;text-transform:uppercase}
.tc{background:var(--s);border-radius:var(--rad);box-shadow:var(--sh);border:1px solid var(--b);overflow:hidden;margin-bottom:20px}
.ch{padding:14px 20px;border-bottom:1px solid var(--b);display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:10px}
.ch h2{font-size:15px;font-weight:800}
table{width:100%;border-collapse:collapse}
thead th{background:#f8fafc;padding:10px 14px;text-align:left;font-size:11px;font-weight:700;color:var(--m);text-transform:uppercase;letter-spacing:.5px;border-bottom:1px solid var(--b);white-space:nowrap}
tbody tr{border-bottom:1px solid var(--b);transition:background .1s}
tbody tr:last-child{border-bottom:none}
tbody tr:hover{background:#f8fafc}
td{padding:11px 14px;font-size:13px;vertical-align:middle}
.badge{display:inline-flex;padding:3px 9px;border-radius:999px;font-size:11px;font-weight:700}
.bs{padding:5px 11px;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}
.be{border-color:#93c5fd;color:var(--bl);background:#eff6ff}.be:hover{background:var(--bl);color:#fff;border-color:var(--bl)}
.bd{border-color:#fca5a5;color:var(--r);background:var(--rl)}.bd:hover{background:var(--r);color:#fff;border-color:var(--r)}
.ba{border-color:#86efac;color:var(--g);background:var(--gl)}.ba:hover{background:var(--g);color:#fff;border-color:var(--g)}
.mo{display:none;position:fixed;inset:0;background:rgba(15,23,42,.5);z-index:999;align-items:center;justify-content:center;padding:20px}
.mo.open{display:flex}
.mbox{background:var(--s);border-radius:18px;padding:28px;max-width:460px;width:100%;box-shadow:0 24px 64px rgba(15,23,42,.22)}
.mbox h3{font-size:16px;font-weight:800;margin-bottom:16px;padding-bottom:12px;border-bottom:1px solid var(--b)}
.fr2{display:grid;grid-template-columns:1fr 1fr;gap:12px}
.fg{margin-bottom:13px}
.fg label{display:block;font-size:12px;font-weight:700;margin-bottom:4px}
.fg input,.fg select,.fg textarea{width:100%;padding:9px 12px;border:1.5px solid var(--b);border-radius:8px;font-size:13px;font-family:inherit;outline:none;background:#f8fafc}
.fg input:focus,.fg select:focus,.fg textarea:focus{border-color:var(--p);background:#fff}
.ma{display:flex;gap:10px;justify-content:flex-end;margin-top:6px}
.mc{background:#f1f5f9;color:var(--m);border:1.5px solid var(--b);padding:9px 18px;border-radius:8px;font-size:13px;font-weight:700;cursor:pointer;font-family:inherit}
.ms{background:linear-gradient(135deg,#084740,#0f766e);color:#fff;border:none;padding:9px 22px;border-radius:8px;font-size:13px;font-weight:700;cursor:pointer;font-family:inherit}
.empty{text-align:center;padding:40px;color:var(--m);font-size:13px}
@media(max-width:700px){.pb{padding:16px}.top-bar{padding:10px 16px}.fr2{grid-template-columns:1fr}}
</style>
</head>
<body>
<div class="top-bar">
    <a class="back" href="dashboard.php">← Dashboard</a>
    <h1>🕐 Attendance</h1>
</div>
<div class="pb">

<?php if($msg==="saved"): ?><div class="alert al-s">✅ Attendance saved.</div>
<?php elseif($msg==="deleted"): ?><div class="alert al-d">🗑️ Record deleted.</div><?php endif; ?>

<form method="GET" class="fbar">
    <select name="staff_id">
        <?php foreach($allStaff as $s): ?>
        <option value="<?=$s["id"]?>" <?=$s["id"]===$selStaff?"selected":""?>><?=htmlspecialchars($s["name"])?></option>
        <?php endforeach; ?>
    </select>
    <select name="month"><?php for($i=1;$i<=12;$i++): ?><option value="<?=$i?>" <?=$i===$fm?"selected":""?>><?=$mn[$i]?></option><?php endfor; ?></select>
    <select name="year"><?php for($y=date("Y");$y>=date("Y")-3;$y--): ?><option value="<?=$y?>" <?=$y===$fy?"selected":""?>><?=$y?></option><?php endfor; ?></select>
    <button class="btn btn-p" type="submit">View</button>
    <button class="btn btn-p" type="button" onclick="openAdd()">➕ Add Record</button>
</form>

<!-- Stats -->
<div class="sum-row">
    <div class="sc"><div class="sv" style="color:var(--g)"><?=$stats["present"]?></div><div class="sl">Present</div></div>
    <div class="sc"><div class="sv" style="color:var(--r)"><?=$stats["absent"]?></div><div class="sl">Absent</div></div>
    <div class="sc"><div class="sv" style="color:var(--a)"><?=$stats["late"]?></div><div class="sl">Late</div></div>
    <div class="sc"><div class="sv" style="color:#7c3aed"><?=$stats["half_day"]?></div><div class="sl">Half Day</div></div>
    <div class="sc"><div class="sv" style="color:var(--bl)"><?=$stats["holiday"]?></div><div class="sl">Holiday</div></div>
    <div class="sc"><div class="sv"><?=number_format($totalHours,1)?></div><div class="sl">Total Hrs</div></div>
</div>

<div class="tc">
    <div class="ch">
        <h2>📅 <?=$mn[$fm]?> <?=$fy?></h2>
        <?php $sname=array_column($allStaff,"name","id")[$selStaff]??""; ?>
        <span style="font-size:13px;color:var(--m);font-weight:600"><?=htmlspecialchars($sname)?></span>
    </div>
    <table>
        <thead><tr><th>Date</th><th>Day</th><th>Check In</th><th>Check Out</th><th>Hours</th><th>Status</th><th>Note</th><th></th></tr></thead>
        <tbody>
        <?php if(empty($attRows)): ?>
            <tr><td colspan="8"><div class="empty">No records. Click ➕ Add Record to start.</div></td></tr>
        <?php else: foreach($attRows as $r):
            $c=$sc[$r["status"]]??["#f1f5f9","#475569"];
        ?>
        <tr>
            <td style="font-weight:700"><?=date("d M Y",strtotime($r["work_date"]))?></td>
            <td style="color:var(--m)"><?=date("D",strtotime($r["work_date"]))?></td>
            <td><?=$r["check_in"] ?date("H:i",strtotime($r["check_in"])) :"—"?></td>
            <td><?=$r["check_out"]?date("H:i",strtotime($r["check_out"])):"—"?></td>
            <td><?=$r["hours_worked"]?number_format((float)$r["hours_worked"],1)." h":"—"?></td>
            <td><span class="badge" style="background:<?=$c[0]?>;color:<?=$c[1]?>"><?=ucfirst(str_replace("_"," ",$r["status"]))?></span></td>
            <td style="color:var(--m);font-size:12px"><?=htmlspecialchars($r["note"]?:"—")?></td>
            <td style="display:flex;gap:6px">
                <button class="bs be" onclick='editRecord(<?=htmlspecialchars(json_encode($r))?>)'>✏️</button>
                <form method="POST" style="display:inline" onsubmit="return confirm('Delete this record?')">
                    <input type="hidden" name="del_att"  value="1">
                    <input type="hidden" name="att_id"   value="<?=$r["id"]?>">
                    <input type="hidden" name="staff_id" value="<?=$selStaff?>">
                    <input type="hidden" name="month"    value="<?=$fm?>">
                    <input type="hidden" name="year"     value="<?=$fy?>">
                    <button class="bs bd" type="submit">🗑️</button>
                </form>
            </td>
        </tr>
        <?php endforeach; endif; ?>
        </tbody>
    </table>
</div>

</div>

<!-- Modal -->
<div class="mo" id="modal">
<div class="mbox">
    <h3 id="mTitle">🕐 Attendance Record</h3>
    <form method="POST">
        <input type="hidden" name="save_att"  value="1">
        <input type="hidden" name="staff_id"  value="<?=$selStaff?>">
        <div class="fr2">
            <div class="fg"><label>Date</label><input type="date" name="work_date" id="fwd" required></div>
            <div class="fg"><label>Status</label>
                <select name="status" id="fst">
                    <option value="present">✅ Present</option>
                    <option value="absent">❌ Absent</option>
                    <option value="late">⏰ Late</option>
                    <option value="half_day">🌓 Half Day</option>
                    <option value="holiday">🎌 Holiday</option>
                </select>
            </div>
        </div>
        <div class="fr2">
            <div class="fg"><label>Check In</label><input type="time" name="check_in"  id="fci"></div>
            <div class="fg"><label>Check Out</label><input type="time" name="check_out" id="fco"></div>
        </div>
        <div class="fg"><label>Note (optional)</label><textarea name="note" id="fno" rows="2"></textarea></div>
        <div class="ma">
            <button type="button" class="mc" onclick="document.getElementById('modal').classList.remove('open')">Cancel</button>
            <button type="submit" class="ms">💾 Save</button>
        </div>
    </form>
</div>
</div>

<script>
function openAdd(){
    document.getElementById('mTitle').textContent='➕ Add Attendance';
    document.getElementById('fwd').value=new Date().toISOString().slice(0,10);
    document.getElementById('fst').value='present';
    document.getElementById('fci').value='';
    document.getElementById('fco').value='';
    document.getElementById('fno').value='';
    document.getElementById('modal').classList.add('open');
}
function editRecord(r){
    document.getElementById('mTitle').textContent='✏️ Edit Attendance';
    document.getElementById('fwd').value=r.work_date;
    document.getElementById('fst').value=r.status;
    document.getElementById('fci').value=r.check_in||'';
    document.getElementById('fco').value=r.check_out||'';
    document.getElementById('fno').value=r.note||'';
    document.getElementById('modal').classList.add('open');
}
document.getElementById('modal').addEventListener('click',function(e){if(e.target===this)this.classList.remove('open')});
</script>
<?php require __DIR__ . '/../config/auto_update.php'; ?>
</body>
</html>