<?php
/* ============================================================================
 *  staff/my_attendance.php — a staff member's own monthly attendance.
 *  Shows EVERY day of the month, the late minutes per day, the monthly total
 *  late, and the late deduction: if total monthly late > 60 min, deduct one
 *  day's pay (base salary ÷ 22). Read-only. Bilingual EN/Lao.
 * ==========================================================================*/
session_start();
if (!isset($_SESSION["user_id"]) || empty($_SESSION["company_id"])) {
    header("Location: ../auth/login.php"); exit;
}
require_once '../config/database.php';
date_default_timezone_set('Asia/Vientiane');

$userId    = (int)$_SESSION["user_id"];
$companyId = (int)$_SESSION["company_id"];
$fm = (int)($_GET["month"] ?? date('n'));
$fy = (int)($_GET["year"]  ?? date('Y'));
if ($fm < 1 || $fm > 12) $fm = (int)date('n');

const LATE_GRACE_MIN = 60;   // free lateness per month
const DAY_DIVISOR    = 22;   // daily rate = salary / 22

/* base salary (for daily rate) */
$base = (float)($pdo->query("SELECT base_salary FROM company_staff WHERE user_id={$userId} AND company_id={$companyId} LIMIT 1")->fetchColumn() ?: 0);
$dailyRate = $base > 0 ? $base / DAY_DIVISOR : 0;

/* workdays + payroll cycle start day */
$workdays = [1,2,3,4,5];
$cycleStart = 1;
try {
    $wd = $pdo->prepare("SELECT workdays, cycle_start_day FROM att_rules WHERE company_id=? LIMIT 1");
    $wd->execute([$companyId]);
    $rr = $wd->fetch(PDO::FETCH_ASSOC) ?: [];
    if (!empty($rr['workdays'])) $workdays = array_filter(array_map('intval', explode(',', $rr['workdays'])));
    if (!empty($rr['cycle_start_day'])) $cycleStart = max(1, (int)$rr['cycle_start_day']);
} catch (Throwable $e) {}

/* the period for the selected month: starts on cycleStart of that month */
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'));
}

/* attendance rows within the period, keyed by date */
$st = $pdo->prepare("SELECT * FROM hr_attendance WHERE staff_id=? AND company_id=? AND work_date BETWEEN ? AND ?");
$st->execute([$userId, $companyId, $periodStart, $periodEnd]);
$byDate = [];
foreach ($st->fetchAll(PDO::FETCH_ASSOC) as $r) $byDate[$r['work_date']] = $r;

/* period totals */
$totalLate = 0; $present = 0;
foreach ($byDate as $r) {
    $totalLate += (int)($r['late_minutes'] ?? 0);
    if (in_array($r['status'], ['present','late','half_day'])) $present++;
}
$overGrace = $totalLate > LATE_GRACE_MIN;
$deduction = $overGrace ? $dailyRate : 0;

$today = date('Y-m-d');

$mn   = ["","January","February","March","April","May","June","July","August","September","October","November","December"];
$mnLo = ["","ມັງກອນ","ກຸມພາ","ມີນາ","ເມສາ","ພຶດສະພາ","ມິຖຸນາ","ກໍລະກົດ","ສິງຫາ","ກັນຍາ","ຕຸລາ","ພະຈິກ","ທັນວາ"];
$dwLo = [1=>'ຈ',2=>'ອ',3=>'ພ',4=>'ພຫ',5=>'ສຸ',6=>'ສ',7=>'ທ'];
function kip($n){ return number_format((float)$n, 0); }
?>
<!DOCTYPE html>
<html lang="lo">
<head>
    <?php $pwaTheme='#0f766e'; include __DIR__.'/../config/pwa_head.php'; ?>
    <title>My Attendance</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;--amber:#d97706;--amber-lt:#fef3c7;--red:#dc2626;--red-lt:#fee2e2;--blue:#2563eb;--blue-lt:#dbeafe;}
        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:calc(12px + env(safe-area-inset-top,0px)) 16px 12px;display:flex;justify-content:space-between;
            align-items:center;gap:10px;position:sticky;top:0;z-index:100;box-shadow:0 1px 6px rgba(15,23,42,.06);}
        .back-link{display:inline-flex;align-items:center;gap:6px;background:#f1f5f9;color:var(--text);border:1.5px solid var(--border);padding:7px 13px;border-radius:8px;text-decoration:none;font-size:13px;font-weight:700;}
        .lang-bar{display:flex;gap:7px;}
        .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;}
        .page{max-width:560px;margin:auto;padding:16px;}
        h1{font-size:19px;font-weight:800;margin-bottom:12px;}
        .controls{display:flex;gap:8px;margin-bottom:14px;}
        .controls select{flex:1;padding:9px 12px;border:1.5px solid var(--border);border-radius:9px;font-size:14px;font-family:inherit;background:#fff;}
        .summary{background:linear-gradient(135deg,#042f2e,#0f766e);border-radius:16px;padding:18px;color:#fff;margin-bottom:14px;}
        .srow{display:flex;justify-content:space-between;gap:10px;margin-bottom:10px;}
        .srow:last-child{margin-bottom:0;}
        .sbox{flex:1;background:rgba(255,255,255,.12);border-radius:12px;padding:12px;text-align:center;}
        .sbox .v{font-size:20px;font-weight:800;}.sbox .l{font-size:11px;color:rgba(255,255,255,.78);margin-top:2px;}
        .ded{border-radius:12px;padding:12px 14px;font-size:13px;font-weight:700;}
        .ded.ok{background:rgba(255,255,255,.14);}
        .ded.bad{background:rgba(220,38,38,.32);}
        .note{font-size:11px;color:rgba(255,255,255,.72);margin-top:8px;line-height:1.5;}
        .list{background:var(--surface);border:1px solid var(--border);border-radius:14px;overflow:hidden;box-shadow:0 2px 14px rgba(15,23,42,.06);}
        .drow{display:flex;align-items:center;gap:12px;padding:11px 14px;border-bottom:1px solid var(--border);}
        .drow:last-child{border-bottom:none;}
        .drow.off{background:#f8fafc;}
        .drow.today{background:#f0fdfa;}
        .dday{min-width:54px;}
        .dnum{font-size:16px;font-weight:800;}
        .dwk{font-size:11px;color:var(--muted);font-weight:700;margin-left:3px;}
        .dmid{flex:1;font-size:13px;color:var(--muted);}
        .dmid b{color:var(--text);font-weight:700;}
        .dright{text-align:right;}
        .tag{display:inline-block;padding:2px 9px;border-radius:999px;font-size:11px;font-weight:800;}
        .tag.amber{background:var(--amber-lt);color:#92400e;}.tag.green{background:var(--green-lt);color:#15803d;}
        .tag.red{background:var(--red-lt);color:#991b1b;}.tag.gray{background:#f1f5f9;color:var(--muted);}.tag.blue{background:var(--blue-lt);color:#1e40af;}
    </style>
</head>
<body>

<div class="top-bar">
    <a class="back-link" href="../customer/company_home.php">← <span data-lo="ກັບຄືນ" data-en="Back">Back</span></a>
    <div class="lang-bar">
        <button class="lang-btn" id="btn-lo" onclick="setLang('lo')">🇱🇦 ລາວ</button>
        <button class="lang-btn" id="btn-en" onclick="setLang('en')">🇬🇧 EN</button>
    </div>
</div>

<div class="page">
    <h1 data-lo="ປະຫວັດການເຂົ້າວຽກ" data-en="My Attendance">My Attendance</h1>
    <div style="font-size:13px;color:var(--muted);font-weight:700;margin:-6px 0 12px;">
        📅 <?= date('d/m/Y', strtotime($periodStart)) ?> – <?= date('d/m/Y', strtotime($periodEnd)) ?>
    </div>

    <form method="GET" class="controls">
        <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>

    <!-- monthly summary -->
    <div class="summary">
        <div class="srow">
            <div class="sbox"><div class="v" style="color:#fff"><?= $present ?></div><div class="l" data-lo="ມາວຽກ" data-en="Present">Present</div></div>
            <div class="sbox"><div class="v" style="color:<?= $overGrace?'#fca5a5':'#fff' ?>"><?= $totalLate ?>′</div><div class="l" data-lo="ມາຊ້າລວມ" data-en="Total late">Total late</div></div>
            <div class="sbox"><div class="v" style="color:#fff">₭ <?= $dailyRate>0?kip($dailyRate):'—' ?></div><div class="l" data-lo="ອັດຕາ/ວັນ" data-en="Daily rate">Daily rate</div></div>
        </div>
        <?php if ($overGrace): ?>
            <div class="ded bad">
                ⚠️ <span data-lo="ມາຊ້າເກີນ 60 ນາທີ → ຫັກ 1 ວັນ = ₭ <?= kip($deduction) ?>"
                         data-en="Late over 60 min → deduct 1 day = ₭ <?= kip($deduction) ?>">Late over 60 min → deduct 1 day = ₭ <?= kip($deduction) ?></span>
            </div>
        <?php else: ?>
            <div class="ded ok">
                ✅ <span data-lo="ມາຊ້າ <?= $totalLate ?>/60 ນາທີ — ຍັງບໍ່ຖືກຫັກ"
                         data-en="Late <?= $totalLate ?>/60 min — no deduction yet">Late <?= $totalLate ?>/60 min — no deduction yet</span>
            </div>
        <?php endif; ?>
        <div class="note" data-lo="ກົດ: ມາຊ້າລວມເກີນ 60 ນາທີ/ເດືອນ ຈະຫັກ 1 ວັນ (ເງິນເດືອນ ÷ 22)."
             data-en="Rule: total lateness over 60 min/month deducts one day (salary ÷ 22).">Rule: total lateness over 60 min/month deducts one day (salary ÷ 22).</div>
    </div>

    <!-- every day of the payroll cycle -->
    <div class="list">
        <?php for ($ts = strtotime($periodStart); $ts <= strtotime($periodEnd); $ts += 86400):
            $dateStr = date('Y-m-d', $ts);
            $dayNum = (int)date('j', $ts);
            $iso = (int)date('N', $ts);
            $isWork = in_array($iso, $workdays);
            $isToday = ($dateStr === $today);
            $isFuture = ($dateStr > $today);
            $rec = $byDate[$dateStr] ?? null;
            $late = $rec ? (int)($rec['late_minutes'] ?? 0) : 0;
            $rowCls = (!$isWork ? 'off ' : '') . ($isToday ? 'today' : '');
        ?>
        <div class="drow <?= trim($rowCls) ?>">
            <div class="dday">
                <span class="dnum"><?= $dayNum ?></span>
                <span class="dwk" data-lo="<?= $dwLo[$iso] ?>" data-en="<?= date('D', strtotime($dateStr)) ?>"><?= date('D', strtotime($dateStr)) ?></span>
            </div>
            <div class="dmid">
                <?php if ($rec && $rec['check_in']): ?>
                    <b><?= substr($rec['check_in'],0,5) ?></b><?php if (!empty($rec['check_out'])): ?> – <b><?= substr($rec['check_out'],0,5) ?></b><?php endif; ?>
                <?php elseif (!$isWork): ?>
                    <span data-lo="ມື້ພັກ" data-en="Day off">Day off</span>
                <?php elseif ($isFuture): ?>
                    —
                <?php else: ?>
                    <span data-lo="ບໍ່ມີບັນທຶກ" data-en="No record">No record</span>
                <?php endif; ?>
            </div>
            <div class="dright">
                <?php if ($late > 0): ?>
                    <span class="tag amber"><span data-lo="ຊ້າ" data-en="Late">Late</span> <?= $late ?>′</span>
                <?php elseif ($rec && in_array($rec['status'], ['present','late','half_day'])): ?>
                    <span class="tag green" data-lo="ຕົງເວລາ" data-en="On time">On time</span>
                <?php elseif ($rec && $rec['status']==='absent'): ?>
                    <span class="tag red" data-lo="ຂາດ" data-en="Absent">Absent</span>
                <?php elseif ($rec && $rec['status']==='holiday'): ?>
                    <span class="tag blue" data-lo="ພັກ" data-en="Holiday">Holiday</span>
                <?php endif; ?>
            </div>
        </div>
        <?php endfor; ?>
    </div>
</div>

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