<?php
/* ============================================================================
 *  company/attendance_log.php — manager view of the 4-punch selfie attendance.
 *  Per staff / month: morning & afternoon in/out with selfie thumbnails,
 *  late & incomplete flags, and an Edit form that recomputes late/hours/OT.
 *  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';
date_default_timezone_set('Asia/Vientiane');

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

/* ── schedule helpers ── */
function loadSchedule(PDO $pdo, int $companyId): array {
    $grace = 5; $sched = [];
    $st = $pdo->prepare("SELECT extra FROM att_rules WHERE company_id=? LIMIT 1");
    $st->execute([$companyId]);
    $extra = $st->fetchColumn();
    if ($extra) {
        $ex = json_decode($extra, true);
        if (is_array($ex)) {
            if (!empty($ex['schedule'])) foreach ($ex['schedule'] as $k=>$v) $sched[(int)$k]=$v;
            if (isset($ex['grace'])) $grace=(int)$ex['grace'];
        }
    }
    return [$sched, $grace];
}
function lateMins($schedHM,$grace,$nowHMS){
    if (!$schedHM || !$nowHMS) return 0;
    $g=strtotime($schedHM)+$grace*60; $d=strtotime($nowHMS)-$g;
    return $d>0 ? (int)floor($d/60) : 0;
}
function hms($v){ $v=trim((string)$v); if($v==='')return null; return strlen($v)===5 ? $v.':00' : $v; }

[$schedule, $grace] = loadSchedule($pdo, $companyId);

/* ── POST: edit a day ── */
if ($_SERVER["REQUEST_METHOD"] === "POST" && ($_POST["action"] ?? '')==="edit") {
    try {
        $id = (int)$_POST["att_id"];
        $r = $pdo->prepare("SELECT * FROM hr_attendance WHERE id=? AND company_id=? LIMIT 1");
        $r->execute([$id,$companyId]); $r=$r->fetch(PDO::FETCH_ASSOC);
        if (!$r) throw new Exception("Record not found.");

        $amIn=hms($_POST["am_in"]??''); $amOut=hms($_POST["am_out"]??'');
        $pmIn=hms($_POST["pm_in"]??''); $pmOut=hms($_POST["pm_out"]??'');
        $note=trim($_POST["note"]??''); $status=$_POST["status"]??'present';
        $allowed=["present","late","absent","half_day","holiday"]; if(!in_array($status,$allowed))$status='present';

        $iso=(int)date('N',strtotime($r['work_date']));
        $sd=$schedule[$iso]??[];
        $amStart=$sd['am_start']??null; $pmStart=$sd['pm_start']??null;
        $amLate=lateMins($amStart,$grace,$amIn); $pmLate=lateMins($pmStart,$grace,$pmIn);

        $secs=0;
        if($amIn&&$amOut){$d=strtotime($amOut)-strtotime($amIn); if($d>0)$secs+=$d;}
        if($pmIn&&$pmOut){$d=strtotime($pmOut)-strtotime($pmIn); if($d>0)$secs+=$d;}
        $hours=round($secs/3600,2);

        $checkIn=$amIn?:$pmIn; $checkOut=$pmOut?:$amOut; $lateTotal=$amLate+$pmLate;

        /* incomplete: scheduled punches missing */
        $need=[]; if($amStart){$need[]=$amIn;$need[]=$amOut;} if($pmStart){$need[]=$pmIn;$need[]=$pmOut;}
        $incomplete=0; foreach($need as $n) if(!$n){$incomplete=1;break;}

        /* OT recompute on last out */
        $endHM=$pmStart?($sd['pm_end']??null):($sd['am_end']??null);
        $lastOut=$pmStart?$pmOut:$amOut;
        $otMin=(int)$r['ot_minutes']; $otStatus=$r['ot_status']?:'none';
        if($endHM && $lastOut){
            $over=strtotime($lastOut)-strtotime($endHM); $otMin=$over>0?(int)floor($over/60):0;
            if($otMin<=0){$otStatus='none';}
            elseif($otStatus!=='approved'){$otStatus='pending';}
        }

        $pdo->prepare("UPDATE hr_attendance SET am_in=?,am_out=?,pm_in=?,pm_out=?,am_late=?,pm_late=?,
            check_in=?,check_out=?,late_minutes=?,hours_worked=?,status=?,note=?,ot_minutes=?,ot_status=?,
            is_incomplete=? WHERE id=? AND company_id=?")
            ->execute([$amIn,$amOut,$pmIn,$pmOut,$amLate,$pmLate,$checkIn,$checkOut,$lateTotal,$hours,
                       $status,$note,$otMin,$otStatus,$incomplete,$id,$companyId]);
        $_SESSION["al_flash"]=["ok","Attendance updated.","ແກ້ໄຂການເຂົ້າວຽກແລ້ວ."];
    } catch (Throwable $e) {
        $_SESSION["al_flash"]=["err","Error: ".$e->getMessage(),"ຜິດພາດ: ".$e->getMessage()];
    }
    $q=http_build_query(['staff_id'=>$_POST['staff_id']??0,'month'=>$_POST['month']??date('n'),'year'=>$_POST['year']??date('Y')]);
    header("Location: attendance_log.php?$q"); exit;
}

/* ── filters ── */
$staffList=$pdo->prepare("SELECT u.id,u.name 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");
$staffList->execute([$companyId]); $staffList=$staffList->fetchAll(PDO::FETCH_ASSOC);

$selStaff=(int)($_GET["staff_id"]??0);
if(!$selStaff && $staffList) $selStaff=(int)$staffList[0]['id'];
$fm=(int)($_GET["month"]??date('n')); $fy=(int)($_GET["year"]??date('Y'));

/* payroll cycle period for the selected month (e.g. 22nd → 21st) */
$cycleStart=1;
try { $c=$pdo->prepare("SELECT cycle_start_day FROM att_rules WHERE company_id=? LIMIT 1"); $c->execute([$companyId]); $cv=$c->fetchColumn(); if($cv)$cycleStart=max(1,(int)$cv); } catch(Throwable $e){}
if($cycleStart<=1){
    $periodStart=sprintf('%04d-%02d-01',$fy,$fm);
    $periodEnd=date('Y-m-t',strtotime($periodStart));
}else{
    $periodStart=sprintf('%04d-%02d-%02d',$fy,$fm,$cycleStart);
    $periodEnd=date('Y-m-d',strtotime($periodStart.' +1 month -1 day'));
}

$rows=[];
if($selStaff){
    $st=$pdo->prepare("SELECT * FROM hr_attendance WHERE staff_id=? AND company_id=? AND work_date BETWEEN ? AND ? ORDER BY work_date ASC");
    $st->execute([$selStaff,$companyId,$periodStart,$periodEnd]); $rows=$st->fetchAll(PDO::FETCH_ASSOC);
}

/* stats */
$nPresent=0;$nLate=0;$nIncomplete=0;$otTotal=0;
foreach($rows as $r){
    if(in_array($r['status'],['present','late','half_day']))$nPresent++;
    if((int)$r['late_minutes']>0)$nLate++;
    if((int)($r['is_incomplete']??0))$nIncomplete++;
    if(($r['ot_status']??'')==='approved')$otTotal+=(int)$r['ot_minutes'];
}

$flash=$_SESSION["al_flash"]??null; unset($_SESSION["al_flash"]);
$mn=["","January","February","March","April","May","June","July","August","September","October","November","December"];
$mnLo=["","ມັງກອນ","ກຸມພາ","ມີນາ","ເມສາ","ພຶດສະພາ","ມິຖຸນາ","ກໍລະກົດ","ສິງຫາ","ກັນຍາ","ຕຸລາ","ພະຈິກ","ທັນວາ"];

function tcell($val,$photo,$late=null,$place=null){
    if(!$val) return '<span class="mut">—</span>';
    $h='<div class="tcell"><span class="tt">'.substr($val,0,5).'</span>';
    if($late!==null && (int)$late>0) $h.='<span class="lt">'.(int)$late.'′</span>';
    if($photo) $h.='<img class="thumb" src="../'.htmlspecialchars($photo).'" onclick="showPhoto(this.src)" alt="">';
    $h.='</div>';
    if($place) $h.='<div class="plc" title="'.htmlspecialchars($place).'">📍 '.htmlspecialchars($place).'</div>';
    return $h;
}
?>
<!DOCTYPE html>
<html lang="lo">
<head>
    <?php $pwaTheme='#0f766e'; include __DIR__.'/../config/pwa_head.php'; ?>
    <title><?= htmlspecialchars($companyName) ?> — Attendance Log</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: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{background:var(--surface);border-bottom:1px solid var(--border);padding:12px 24px;display:flex;
            justify-content:space-between;align-items:center;gap:14px;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:10px;}
        .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:22px 20px;max-width:1150px;margin:auto;}
        h1{font-size:20px;font-weight:800;margin-bottom:16px;}
        .controls{display:flex;gap:10px;flex-wrap:wrap;margin-bottom:16px;}
        .controls select{padding:9px 12px;border:1.5px solid var(--border);border-radius:9px;font-size:14px;font-family:inherit;background:#fff;}
        .stats{display:flex;gap:10px;flex-wrap:wrap;margin-bottom:16px;}
        .stat{background:var(--surface);border:1px solid var(--border);border-radius:12px;padding:10px 16px;box-shadow:var(--shadow);min-width:110px;}
        .stat .v{font-size:20px;font-weight:800;}.stat .l{font-size:11px;color:var(--muted);font-weight:600;text-transform:uppercase;letter-spacing:.3px;}
        .flash{padding:12px 16px;border-radius:10px;margin-bottom:16px;font-size:14px;font-weight:600;}
        .flash.ok{background:var(--green-lt);color:#15803d;}.flash.err{background:var(--red-lt);color:var(--red);}
        .card{background:var(--surface);border-radius:var(--radius);box-shadow:var(--shadow);border:1px solid var(--border);overflow:hidden;}
        .tbl-wrap{overflow-x:auto;}
        table{width:100%;border-collapse:collapse;font-size:13px;min-width:860px;}
        th{text-align:left;font-size:11px;text-transform:uppercase;letter-spacing:.3px;color:var(--muted);padding:10px;border-bottom:2px solid var(--border);background:#f8fafc;white-space:nowrap;}
        td{padding:9px 10px;border-bottom:1px solid var(--border);vertical-align:middle;}
        tr:last-child td{border-bottom:none;}
        .mut{color:var(--muted);}
        .tcell{display:flex;align-items:center;gap:6px;}
        .tt{font-weight:700;}
        .lt{background:var(--amber-lt);color:#92400e;font-size:10px;font-weight:800;padding:1px 6px;border-radius:999px;}
        .thumb{width:30px;height:30px;border-radius:6px;object-fit:cover;cursor:pointer;border:1px solid var(--border);}
        .plc{font-size:10px;color:var(--muted);margin-top:3px;max-width:150px;white-space:normal;line-height:1.25;}
        .tag{display:inline-block;padding:2px 8px;border-radius:999px;font-size:10px;font-weight:800;}
        .tag.green{background:var(--green-lt);color:#15803d;}.tag.amber{background:var(--amber-lt);color:#92400e;}
        .tag.red{background:var(--red-lt);color:#991b1b;}.tag.gray{background:#f1f5f9;color:var(--muted);}.tag.blue{background:var(--blue-lt);color:#1e40af;}
        .btn{padding:6px 12px;border-radius:8px;border:1.5px solid var(--border);background:#f1f5f9;color:var(--text);font-size:12px;font-weight:700;cursor:pointer;font-family:inherit;}
        .empty{text-align:center;color:var(--muted);padding:30px;}
        /* photo modal */
        .pmodal{display:none;position:fixed;inset:0;background:rgba(0,0,0,.85);z-index:300;align-items:center;justify-content:center;padding:20px;}
        .pmodal img{max-width:100%;max-height:85vh;border-radius:12px;}
        .pmodal .x{position:absolute;top:18px;right:22px;color:#fff;font-size:34px;cursor:pointer;font-weight:700;}
        /* edit modal */
        .emodal{display:none;position:fixed;inset:0;background:rgba(15,23,42,.5);z-index:310;align-items:center;justify-content:center;padding:16px;}
        .ebox{background:#fff;border-radius:16px;max-width:460px;width:100%;padding:22px;box-shadow:0 20px 60px rgba(0,0,0,.3);max-height:90vh;overflow:auto;}
        .ebox h3{font-size:17px;font-weight:800;margin-bottom:4px;}
        .ebox .sub{font-size:12px;color:var(--muted);margin-bottom:16px;}
        .erow{display:flex;gap:10px;margin-bottom:12px;}
        .efg{flex:1;}
        .efg label{display:block;font-size:12px;font-weight:700;color:#374151;margin-bottom:5px;}
        .efg input,.efg select,.efg textarea{width:100%;padding:9px 11px;border:1.5px solid var(--border);border-radius:9px;font-size:14px;font-family:inherit;}
        .eactions{display:flex;gap:10px;margin-top:8px;}
        .btn-primary{background:var(--primary);color:#fff;border:none;padding:11px 18px;border-radius:9px;font-weight:800;font-size:14px;cursor:pointer;font-family:inherit;}
        .btn-ghost{background:#f1f5f9;border:1.5px solid var(--border);padding:11px 16px;border-radius:9px;font-weight:700;cursor:pointer;font-family:inherit;}
        @media(max-width:640px){.page{padding:14px;}.erow{flex-direction:column;gap:0;}}
    </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="ບັນທຶກການເຂົ້າວຽກ" data-en="Attendance Log">ບັນທຶກການເຂົ້າວຽກ</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">
    <h1 data-lo="ບັນທຶກການເຂົ້າວຽກ ແລະ ຮູບ" data-en="Attendance Log & Selfies">Attendance Log &amp; Selfies</h1>
    <div style="font-size:13px;color:var(--muted);font-weight:700;margin:-8px 0 14px;">
        📅 <?= date('d/m/Y', strtotime($periodStart)) ?> – <?= date('d/m/Y', strtotime($periodEnd)) ?>
    </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; ?>

    <form method="GET" class="controls">
        <select name="staff_id" onchange="this.form.submit()">
            <?php foreach ($staffList as $s): ?>
                <option value="<?= (int)$s['id'] ?>" <?= $selStaff===(int)$s['id']?'selected':'' ?>><?= htmlspecialchars($s['name']) ?></option>
            <?php endforeach; ?>
        </select>
        <select name="month" onchange="this.form.submit()">
            <?php for($i=1;$i<=12;$i++): ?>
                <option value="<?= $i ?>" <?= $i===$fm?'selected':'' ?> data-en="<?= $mn[$i] ?>" data-lo="<?= $mnLo[$i] ?>"><?= $mn[$i] ?></option>
            <?php endfor; ?>
        </select>
        <select name="year" onchange="this.form.submit()">
            <?php for($y=date('Y')-1;$y<=date('Y')+1;$y++): ?>
                <option value="<?= $y ?>" <?= $y===$fy?'selected':'' ?>><?= $y ?></option>
            <?php endfor; ?>
        </select>
    </form>

    <div class="stats">
        <div class="stat"><div class="v" style="color:#16a34a"><?= $nPresent ?></div><div class="l" data-lo="ມາວຽກ" data-en="Present">Present</div></div>
        <div class="stat"><div class="v" style="color:#d97706"><?= $nLate ?></div><div class="l" data-lo="ມາຊ້າ" data-en="Late days">Late days</div></div>
        <div class="stat"><div class="v" style="color:#dc2626"><?= $nIncomplete ?></div><div class="l" data-lo="ບໍ່ຄົບ" data-en="Incomplete">Incomplete</div></div>
        <div class="stat"><div class="v" style="color:#2563eb"><?= round($otTotal/60,1) ?>h</div><div class="l" data-lo="OT ອະນຸມັດ" data-en="OT approved">OT approved</div></div>
    </div>

    <div class="card">
        <div class="tbl-wrap">
        <table>
            <thead><tr>
                <th data-lo="ວັນທີ" data-en="Date">Date</th>
                <th data-lo="ເຂົ້າ ເຊົ້າ" data-en="AM In">AM In</th>
                <th data-lo="ອອກ ເຊົ້າ" data-en="AM Out">AM Out</th>
                <th data-lo="ເຂົ້າ ບ່າຍ" data-en="PM In">PM In</th>
                <th data-lo="ອອກ ບ່າຍ" data-en="PM Out">PM Out</th>
                <th data-lo="ຊມ" data-en="Hrs">Hrs</th>
                <th>OT</th>
                <th data-lo="ສະຖານະ" data-en="Status">Status</th>
                <th></th>
            </tr></thead>
            <tbody>
            <?php if (!$rows): ?>
                <tr><td colspan="9" class="empty" data-lo="ບໍ່ມີຂໍ້ມູນສຳລັບເດືອນນີ້." data-en="No records for this month.">No records for this month.</td></tr>
            <?php else: foreach ($rows as $r):
                $dow=(int)date('N',strtotime($r['work_date']));
            ?>
                <tr>
                    <td><strong><?= date('d/m', strtotime($r['work_date'])) ?></strong>
                        <span class="mut" style="font-size:11px"><?= date('D',strtotime($r['work_date'])) ?></span>
                        <?php if((int)($r['is_incomplete']??0)): ?><br><span class="tag red" data-lo="ບໍ່ຄົບ" data-en="Incomplete">Incomplete</span><?php endif; ?>
                        <?php if((int)($r['is_offsite']??0)): ?><br><span class="tag gray" data-lo="ນອກບ່ອນ" data-en="Off-site">Off-site</span><?php endif; ?>
                        <?php if(!empty($r['offsite_reason'])): ?><div class="plc" style="color:#92400e;">📝 <?= htmlspecialchars($r['offsite_reason']) ?></div><?php endif; ?>
                    </td>
                    <td><?= tcell($r['am_in']??null,$r['am_in_photo']??null,$r['am_late']??0,$r['am_in_place']??null) ?></td>
                    <td><?= tcell($r['am_out']??null,$r['am_out_photo']??null,null,$r['am_out_place']??null) ?></td>
                    <td><?= tcell($r['pm_in']??null,$r['pm_in_photo']??null,$r['pm_late']??0,$r['pm_in_place']??null) ?></td>
                    <td><?= tcell($r['pm_out']??null,$r['pm_out_photo']??null,null,$r['pm_out_place']??null) ?></td>
                    <td><?= $r['hours_worked']!==null ? number_format((float)$r['hours_worked'],2) : '—' ?></td>
                    <td><?php if((int)$r['ot_minutes']>0): ?>
                        <span class="tag <?= $r['ot_status']==='approved'?'green':($r['ot_status']==='rejected'?'red':'blue') ?>"><?= round($r['ot_minutes']/60,1) ?>h</span>
                        <?php else: ?><span class="mut">—</span><?php endif; ?></td>
                    <td><?php
                        $sc=['present'=>'green','late'=>'amber','absent'=>'red','half_day'=>'blue','holiday'=>'gray'];
                        $cls=$sc[$r['status']]??'gray';
                        echo '<span class="tag '.$cls.'">'.htmlspecialchars($r['status']).'</span>';
                    ?></td>
                    <td><button class="btn" type="button"
                        onclick='openEdit(<?= json_encode([
                            'id'=>$r['id'],'date'=>date('d/m/Y',strtotime($r['work_date'])),
                            'am_in'=>substr((string)$r['am_in'],0,5),'am_out'=>substr((string)$r['am_out'],0,5),
                            'pm_in'=>substr((string)$r['pm_in'],0,5),'pm_out'=>substr((string)$r['pm_out'],0,5),
                            'status'=>$r['status'],'note'=>$r['note']??''
                        ], JSON_UNESCAPED_UNICODE|JSON_HEX_APOS|JSON_HEX_QUOT) ?>)'
                        data-lo="ແກ້ໄຂ" data-en="Edit">Edit</button></td>
                </tr>
            <?php endforeach; endif; ?>
            </tbody>
        </table>
        </div>
    </div>

    <p style="font-size:12px;color:var(--muted);margin-top:12px;" data-lo="ກົດທີ່ຮູບເພື່ອເບິ່ງຂະໜາດໃຫຍ່. ຮູບຈະຖືກລຶບອັດຕະໂນມັດຫຼັງ 3 ເດືອນ."
       data-en="Tap a photo to enlarge. Selfies are auto-deleted after 3 months.">Tap a photo to enlarge. Selfies auto-delete after 3 months.</p>
</div>

<!-- photo modal -->
<div class="pmodal" id="pmodal" onclick="this.style.display='none'">
    <span class="x">&times;</span>
    <img id="pmodalImg" src="" alt="">
</div>

<!-- edit modal -->
<div class="emodal" id="emodal">
    <div class="ebox">
        <h3 data-lo="ແກ້ໄຂການເຂົ້າວຽກ" data-en="Edit attendance">Edit attendance</h3>
        <div class="sub" id="editDate"></div>
        <form method="POST">
            <input type="hidden" name="action" value="edit">
            <input type="hidden" name="att_id" id="e_id">
            <input type="hidden" name="staff_id" value="<?= $selStaff ?>">
            <input type="hidden" name="month" value="<?= $fm ?>">
            <input type="hidden" name="year" value="<?= $fy ?>">
            <div class="erow">
                <div class="efg"><label data-lo="ເຂົ້າ ເຊົ້າ" data-en="Morning In">Morning In</label><input type="time" name="am_in" id="e_am_in"></div>
                <div class="efg"><label data-lo="ອອກ ເຊົ້າ" data-en="Morning Out">Morning Out</label><input type="time" name="am_out" id="e_am_out"></div>
            </div>
            <div class="erow">
                <div class="efg"><label data-lo="ເຂົ້າ ບ່າຍ" data-en="Afternoon In">Afternoon In</label><input type="time" name="pm_in" id="e_pm_in"></div>
                <div class="efg"><label data-lo="ອອກ ບ່າຍ" data-en="Afternoon Out">Afternoon Out</label><input type="time" name="pm_out" id="e_pm_out"></div>
            </div>
            <div class="erow">
                <div class="efg"><label data-lo="ສະຖານະ" data-en="Status">Status</label>
                    <select name="status" id="e_status">
                        <option value="present" data-lo="ມາວຽກ" data-en="Present">Present</option>
                        <option value="late" data-lo="ມາຊ້າ" data-en="Late">Late</option>
                        <option value="absent" data-lo="ຂາດວຽກ" data-en="Absent">Absent</option>
                        <option value="half_day" data-lo="ເຄິ່ງວັນ" data-en="Half day">Half day</option>
                        <option value="holiday" data-lo="ມື້ພັກ" data-en="Holiday">Holiday</option>
                    </select>
                </div>
            </div>
            <div class="erow">
                <div class="efg"><label data-lo="ໝາຍເຫດ" data-en="Note">Note</label><textarea name="note" id="e_note" rows="2"></textarea></div>
            </div>
            <div class="sub" data-lo="ບັນທຶກແລ້ວ ລະບົບຈະຄິດໄລ່ ມາຊ້າ, ຊມ ແລະ OT ໃໝ່ໂດຍອັດຕະໂນມັດ." data-en="On save, late, hours and OT are recalculated automatically.">On save, late/hours/OT recalculate automatically.</div>
            <div class="eactions">
                <button type="submit" class="btn-primary" data-lo="💾 ບັນທຶກ" data-en="💾 Save">💾 Save</button>
                <button type="button" class="btn-ghost" onclick="document.getElementById('emodal').style.display='none'" data-lo="ຍົກເລີກ" data-en="Cancel">Cancel</button>
            </div>
        </form>
    </div>
</div>

<script>
function showPhoto(src){document.getElementById('pmodalImg').src=src;document.getElementById('pmodal').style.display='flex';}
function openEdit(r){
    document.getElementById('e_id').value=r.id;
    document.getElementById('editDate').textContent=r.date;
    document.getElementById('e_am_in').value=r.am_in||'';
    document.getElementById('e_am_out').value=r.am_out||'';
    document.getElementById('e_pm_in').value=r.pm_in||'';
    document.getElementById('e_pm_out').value=r.pm_out||'';
    document.getElementById('e_status').value=r.status||'present';
    document.getElementById('e_note').value=r.note||'';
    document.getElementById('emodal').style.display='flex';
}
</script>

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