<?php
/* ============================================================================
 *  company/staff_view.php — one staff member's full profile for managers.
 *  Tabbed: Profile · Salary · Attendance · Leave · Loans (gated by modules).
 *  Attendance tab has its own month picker + full log inline. Bilingual EN/Lao.
 *  Usage: staff_view.php?id=<user_id>[&tab=attendance&amonth=M&ayear=Y]
 * ==========================================================================*/
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/modules.php';
require_once '../config/loans.php';
date_default_timezone_set('Asia/Vientiane');

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

$enabled = company_enabled_modules($pdo, $companyId);
$mod = fn($k) => module_on($enabled, $k);

/* profile */
$p = $pdo->prepare("SELECT u.id, u.name, u.username, u.email, u.phone, u.status,
        cs.staff_role, cs.position, cs.department, cs.joined_date, cs.full_name_lo, cs.nickname,
        cs.staff_code, cs.dob, cs.photo, cs.contract_file, cs.cv_file, cs.bank_name, cs.bank_account, cs.base_salary,
        cs.annual_leave_days
    FROM company_staff cs JOIN users u ON u.id = cs.user_id
    WHERE cs.company_id=? AND u.id=? LIMIT 1");
$p->execute([$companyId, $sid]);
$p = $p->fetch(PDO::FETCH_ASSOC);
if (!$p) { header("Location: staff.php"); exit; }

/* ── attendance edit helpers (recompute late/hours/OT) ── */
function sv_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 sv_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 sv_hms($v){ $v=trim((string)$v); if($v==='')return null; return strlen($v)===5?$v.':00':$v; }

/* ── POST: inline bulk edit of attendance ── */
if ($_SERVER['REQUEST_METHOD']==='POST' && ($_POST['action']??'')==='bulk_edit_att' && $mod('attendance')) {
    [$schedule,$grace]=sv_loadSchedule($pdo,$companyId);
    $allowed=["present","late","absent","half_day","holiday"];
    foreach (($_POST['rows']??[]) as $attId=>$f) {
        $attId=(int)$attId;
        $r=$pdo->prepare("SELECT * FROM hr_attendance WHERE id=? AND company_id=? AND staff_id=? LIMIT 1");
        $r->execute([$attId,$companyId,$sid]); $r=$r->fetch(PDO::FETCH_ASSOC);
        if(!$r) continue;
        $amIn=sv_hms($f['am_in']??''); $amOut=sv_hms($f['am_out']??'');
        $pmIn=sv_hms($f['pm_in']??''); $pmOut=sv_hms($f['pm_out']??'');
        $status=$f['status']??'present'; 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=sv_lateMins($amStart,$grace,$amIn); $pmLate=sv_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;
        $need=[]; if($amStart){$need[]=$amIn;$need[]=$amOut;} if($pmStart){$need[]=$pmIn;$need[]=$pmOut;}
        $incomplete=0; foreach($need as $n) if(!$n){$incomplete=1;break;}
        $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=?,ot_minutes=?,ot_status=?,is_incomplete=?
            WHERE id=? AND company_id=?")
            ->execute([$amIn,$amOut,$pmIn,$pmOut,$amLate,$pmLate,$checkIn,$checkOut,$lateTotal,$hours,$status,$otMin,$otStatus,$incomplete,$attId,$companyId]);
    }
    $q=http_build_query(['id'=>$sid,'tab'=>'attendance','amonth'=>(int)($_POST['amonth']??date('n')),'ayear'=>(int)($_POST['ayear']??date('Y')),'saved'=>1]);
    header("Location: staff_view.php?$q"); exit;
}

/* payroll cycle start day */
$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){}
$Y=(int)date('Y'); $M=(int)date('n'); $dnum=(int)date('j');

/* current cycle (used to default the attendance month picker) */
if ($cycleStart <= 1) {
    $curStart = sprintf('%04d-%02d-01',$Y,$M);
} else {
    if ($dnum >= $cycleStart) $curStart = sprintf('%04d-%02d-%02d',$Y,$M,$cycleStart);
    else $curStart = date('Y-m-d', strtotime(sprintf('%04d-%02d-%02d',$Y,$M,$cycleStart).' -1 month'));
}

/* selected attendance month (defaults to current cycle's start month) */
$selAM = (int)($_GET['amonth'] ?? (int)date('n',strtotime($curStart)));
$selAY = (int)($_GET['ayear'] ?? (int)date('Y',strtotime($curStart)));
if ($cycleStart <= 1) {
    $aStart = sprintf('%04d-%02d-01',$selAY,$selAM); $aEnd = date('Y-m-t',strtotime($aStart));
} else {
    $aStart = sprintf('%04d-%02d-%02d',$selAY,$selAM,$cycleStart);
    $aEnd   = date('Y-m-d', strtotime($aStart.' +1 month -1 day'));
}

/* attendance: full log + stats for the selected period */
$attRows = [];
$att = ['present'=>0,'late'=>0,'lateDays'=>0,'ot'=>0,'hours'=>0,'incomplete'=>0];
if ($mod('attendance')) {
    $aq = $pdo->prepare("SELECT * FROM hr_attendance WHERE staff_id=? AND company_id=? AND work_date BETWEEN ? AND ? ORDER BY work_date ASC");
    $aq->execute([$sid,$companyId,$aStart,$aEnd]);
    $attRows = $aq->fetchAll(PDO::FETCH_ASSOC);
    foreach ($attRows as $r) {
        if (in_array($r['status'],['present','late','half_day'])) $att['present']++;
        $att['late'] += (int)$r['late_minutes']; if ((int)$r['late_minutes']>0) $att['lateDays']++;
        if (($r['ot_status']??'')==='approved') $att['ot'] += (int)$r['ot_minutes'];
        $att['hours'] += (float)$r['hours_worked'];
        if ((int)($r['is_incomplete']??0)) $att['incomplete']++;
    }
}

/* leave */
$ent = ($p['annual_leave_days']===null) ? 15 : (int)$p['annual_leave_days'];
$used = (int)($pdo->query("SELECT COALESCE(SUM(days),0) FROM hr_leave WHERE staff_id={$sid} AND company_id={$companyId} AND leave_type='annual' AND status='approved' AND YEAR(start_date)=".date('Y'))->fetchColumn());
$recentLeave = $pdo->prepare("SELECT leave_type,start_date,end_date,days,status,is_hourly,start_time,end_time FROM hr_leave WHERE staff_id=? AND company_id=? ORDER BY created_at DESC LIMIT 8");
$recentLeave->execute([$sid,$companyId]); $recentLeave=$recentLeave->fetchAll(PDO::FETCH_ASSOC);

/* salary */
$latestSal = $pdo->prepare("SELECT * FROM hr_salary WHERE staff_id=? AND company_id=? ORDER BY year DESC, month DESC LIMIT 1");
$latestSal->execute([$sid,$companyId]); $latestSal=$latestSal->fetch(PDO::FETCH_ASSOC);
$payHist = $pdo->prepare("SELECT month,year,base_salary,total_ot,total_allowances,deductions,net_pay,paid_at FROM hr_salary WHERE staff_id=? AND company_id=? ORDER BY year DESC, month DESC LIMIT 8");
$payHist->execute([$sid,$companyId]); $payHist=$payHist->fetchAll(PDO::FETCH_ASSOC);

/* loans */
$loanOut = loan_outstanding($pdo,$companyId,$sid);
$loans = $pdo->prepare("SELECT amount,monthly_payment,remaining,status FROM hr_loans WHERE staff_id=? AND company_id=? AND status IN('approved','pending') ORDER BY created_at DESC LIMIT 8");
$loans->execute([$sid,$companyId]); $loans=$loans->fetchAll(PDO::FETCH_ASSOC);

$tab = preg_replace('/[^a-z]/','', strtolower($_GET['tab'] ?? 'profile'));
$mn=["","January","February","March","April","May","June","July","August","September","October","November","December"];
$mnLo=["","ມັງກອນ","ກຸມພາ","ມີນາ","ເມສາ","ພຶດສະພາ","ມິຖຸນາ","ກໍລະກົດ","ສິງຫາ","ກັນຍາ","ຕຸລາ","ພະຈິກ","ທັນວາ"];
function kip($n){ return number_format((float)$n,0); }
function dmy($v){ return ($v && $v!=='0000-00-00') ? date('d/m/Y',strtotime($v)) : '—'; }
function sv($v){ return ($v===null||$v==='')?'—':htmlspecialchars($v); }
function tm($v){ $v=substr((string)$v,0,5); return $v?:'—'; }
?>
<!DOCTYPE html>
<html lang="lo">
<head>
    <?php $pwaTheme='#0f766e'; include __DIR__.'/../config/pwa_head.php'; ?>
    <title><?= htmlspecialchars($p['name']) ?> — Staff</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;--radius:14px;--shadow:0 2px 14px rgba(15,23,42,.07);}
        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;}
        .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:1000px;margin:auto;padding:22px 18px;}
        .hero{background:linear-gradient(135deg,#042f2e,#0f766e);border-radius:18px;padding:22px;color:#fff;display:flex;align-items:center;gap:18px;flex-wrap:wrap;margin-bottom:14px;}
        .ph{width:84px;height:84px;border-radius:18px;object-fit:cover;border:2px solid rgba(255,255,255,.5);background:rgba(255,255,255,.15);display:flex;align-items:center;justify-content:center;font-size:34px;font-weight:800;flex-shrink:0;}
        .hname{font-size:22px;font-weight:800;line-height:1.2;}
        .hsub{font-size:13px;color:rgba(255,255,255,.82);margin-top:4px;}
        .htags{display:flex;gap:6px;margin-top:8px;flex-wrap:wrap;}
        .htag{background:rgba(255,255,255,.16);font-size:11px;font-weight:800;padding:3px 10px;border-radius:999px;}
        .acts{margin-left:auto;display:flex;gap:8px;flex-wrap:wrap;}
        .act{background:rgba(255,255,255,.16);color:#fff;border:1px solid rgba(255,255,255,.25);padding:8px 13px;border-radius:9px;text-decoration:none;font-size:12px;font-weight:800;}
        /* tab bar */
        .tabs{display:flex;gap:7px;flex-wrap:wrap;margin-bottom:16px;position:sticky;top:60px;z-index:50;}
        .tabbtn{background:var(--surface);border:1.5px solid var(--border);color:var(--muted);padding:10px 18px;border-radius:11px;font-size:14px;font-weight:800;cursor:pointer;font-family:inherit;box-shadow:var(--shadow);display:inline-flex;align-items:center;gap:7px;}
        .tabbtn.active{background:var(--primary);border-color:var(--primary);color:#fff;}
        .panel{display:none;}
        .panel.active{display:block;}
        .card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);box-shadow:var(--shadow);padding:6px 20px 18px;}
        .card+.card{margin-top:14px;}
        .ch{display:flex;justify-content:space-between;align-items:center;padding:16px 0 8px;flex-wrap:wrap;gap:10px;}
        .ch h2{font-size:17px;font-weight:800;}
        .ch a{font-size:12px;color:var(--primary);font-weight:700;text-decoration:none;}
        .r{display:flex;justify-content:space-between;gap:12px;padding:11px 0;border-bottom:1px solid var(--border);font-size:14px;}
        .r:last-child{border-bottom:none;}
        .k{color:var(--muted);font-weight:600;}.v{font-weight:700;text-align:right;word-break:break-word;}
        .stat3{display:grid;grid-template-columns:repeat(auto-fit,minmax(90px,1fr));gap:10px;margin:10px 0;}
        .sb{background:#f8fafc;border:1px solid var(--border);border-radius:10px;padding:13px 8px;text-align:center;}
        .sb .v{font-size:22px;font-weight:800;}.sb .l{font-size:11px;color:var(--muted);font-weight:600;margin-top:2px;}
        .tag{display:inline-block;padding:2px 9px;border-radius:999px;font-size:11px;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.blue{background:var(--blue-lt);color:#1e40af;}.tag.gray{background:#f1f5f9;color:var(--muted);}
        .filelink{display:inline-flex;align-items:center;gap:5px;color:var(--primary);font-weight:700;text-decoration:none;background:#f0fdfa;border:1.5px solid #99f6e4;padding:5px 11px;border-radius:8px;font-size:12px;}
        .period{font-size:13px;color:var(--muted);font-weight:700;margin:6px 0;}
        .bar{height:8px;background:#eef2f6;border-radius:999px;overflow:hidden;margin-top:6px;}.bar>span{display:block;height:100%;background:#16a34a;}
        .mini{font-size:13px;color:var(--muted);padding:9px 0;border-bottom:1px solid var(--border);display:flex;justify-content:space-between;gap:8px;}
        .mini:last-child{border-bottom:none;}
        .picker{display:flex;gap:8px;flex-wrap:wrap;}
        .picker select{padding:9px 12px;border:1.5px solid var(--border);border-radius:9px;font-size:14px;font-family:inherit;background:#fff;}
        .tbl-wrap{overflow-x:auto;margin-top:6px;}
        table{width:100%;border-collapse:collapse;font-size:13px;min-width:640px;}
        th{text-align:left;font-size:11px;text-transform:uppercase;letter-spacing:.3px;color:var(--muted);padding:9px;border-bottom:2px solid var(--border);background:#f8fafc;white-space:nowrap;}
        td{padding:9px;border-bottom:1px solid var(--border);vertical-align:middle;white-space:nowrap;}
        tr:last-child td{border-bottom:none;}
        .tt{font-weight:700;}.mut{color:var(--muted);}
        .thumb{width:30px;height:30px;border-radius:6px;object-fit:cover;cursor:pointer;border:1px solid var(--border);vertical-align:middle;}
        .ed{width:100%;min-width:96px;padding:6px 8px;border:1.5px solid var(--border);border-radius:8px;font-family:inherit;font-size:13px;}
        .plc{display:block;font-size:10px;color:var(--muted);margin-top:3px;line-height:1.25;max-width:150px;white-space:normal;}
        .empty{text-align:center;color:var(--muted);padding:26px;}
        .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;}
        @media(max-width:640px){.acts{margin-left:0;width:100%;}.tabs{top:56px;}.tabbtn{padding:9px 13px;font-size:13px;}}
    </style>
</head>
<body>

<div class="top-bar">
    <a class="back-link" href="staff.php">← <span data-lo="ລາຍຊື່ພະນັກງານ" data-en="Staff List">Staff List</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">

    <!-- hero -->
    <div class="hero">
        <?php if (!empty($p['photo'])): ?>
            <img class="ph" src="../<?= htmlspecialchars($p['photo']) ?>" alt="">
        <?php else: ?>
            <div class="ph"><?= strtoupper(mb_substr($p['name'],0,1)) ?></div>
        <?php endif; ?>
        <div>
            <div class="hname"><?= htmlspecialchars($p['name']) ?></div>
            <div class="hsub">
                <?= sv($p['position']) ?><?php if ($p['department']): ?> · <?= htmlspecialchars($p['department']) ?><?php endif; ?>
            </div>
            <div class="htags">
                <?php if ($p['staff_code']): ?><span class="htag">ID: <?= htmlspecialchars($p['staff_code']) ?></span><?php endif; ?>
                <span class="htag"><?= $p['staff_role']==='admin'?'👑 Admin':'👤 Staff' ?></span>
                <span class="htag"><?= $p['status']==='active'?'✅ Active':'⛔ Inactive' ?></span>
            </div>
        </div>
        <div class="acts">
            <a class="act" href="staff_form.php?id=<?= $sid ?>">✏️ <span data-lo="ແກ້ໄຂ" data-en="Edit">Edit</span></a>
        </div>
    </div>

    <!-- tab bar -->
    <div class="tabs">
        <button class="tabbtn" data-tab="profile" onclick="showTab('profile')">👤 <span data-lo="ຂໍ້ມູນ" data-en="Profile">Profile</span></button>
        <?php if ($mod('payroll')): ?><button class="tabbtn" data-tab="salary" onclick="showTab('salary')">💵 <span data-lo="ເງິນເດືອນ" data-en="Salary">Salary</span></button><?php endif; ?>
        <?php if ($mod('attendance')): ?><button class="tabbtn" data-tab="attendance" onclick="showTab('attendance')">🕐 <span data-lo="ການເຂົ້າວຽກ" data-en="Attendance">Attendance</span></button><?php endif; ?>
        <?php if ($mod('leave')): ?><button class="tabbtn" data-tab="leave" onclick="showTab('leave')">🌴 <span data-lo="ການລາພັກ" data-en="Leave">Leave</span></button><?php endif; ?>
        <?php if ($mod('payroll')): ?><button class="tabbtn" data-tab="loans" onclick="showTab('loans')">💳 <span data-lo="ການກູ້ຢືມ" data-en="Loans">Loans</span></button><?php endif; ?>
    </div>

    <!-- PROFILE -->
    <div class="panel" id="tab-profile">
        <div class="card">
            <div class="ch"><h2 data-lo="ຂໍ້ມູນສ່ວນຕົວ" data-en="Profile">Profile</h2>
                <a href="staff_form.php?id=<?= $sid ?>" data-lo="ແກ້ໄຂ →" data-en="Edit →">Edit →</a></div>
            <div class="r"><span class="k" data-lo="ຊື່ (ອັງກິດ)" data-en="Name (EN)">Name (EN)</span><span class="v"><?= sv($p['name']) ?></span></div>
            <div class="r"><span class="k" data-lo="ຊື່ (ລາວ)" data-en="Name (Lao)">Name (Lao)</span><span class="v"><?= sv($p['full_name_lo']) ?></span></div>
            <div class="r"><span class="k" data-lo="ຊື່ຫຼິ້ນ" data-en="Nickname">Nickname</span><span class="v"><?= sv($p['nickname']) ?></span></div>
            <div class="r"><span class="k" data-lo="ລະຫັດພະນັກງານ" data-en="Staff ID">Staff ID</span><span class="v"><?= sv($p['staff_code']) ?></span></div>
            <div class="r"><span class="k" data-lo="ຕຳແໜ່ງ" data-en="Position">Position</span><span class="v"><?= sv($p['position']) ?></span></div>
            <div class="r"><span class="k" data-lo="ພະແນກ" data-en="Department">Department</span><span class="v"><?= sv($p['department']) ?></span></div>
            <div class="r"><span class="k" data-lo="ເບີໂທ" data-en="Phone">Phone</span><span class="v"><?= sv($p['phone']) ?></span></div>
            <div class="r"><span class="k" data-lo="ອີເມວ" data-en="Email">Email</span><span class="v"><?= sv($p['email']) ?></span></div>
            <div class="r"><span class="k" data-lo="ວັນເກີດ" data-en="Date of Birth">Date of Birth</span><span class="v"><?= dmy($p['dob']) ?></span></div>
            <div class="r"><span class="k" data-lo="ວັນເລີ່ມວຽກ" data-en="Joined">Joined</span><span class="v"><?= dmy($p['joined_date']) ?></span></div>
            <div class="r"><span class="k" data-lo="ທະນາຄານ" data-en="Bank">Bank</span><span class="v"><?= sv($p['bank_name']) ?><?php if($p['bank_account']): ?> · <?= htmlspecialchars($p['bank_account']) ?><?php endif; ?></span></div>
            <div class="r"><span class="k" data-lo="ເອກະສານ" data-en="Documents">Documents</span><span class="v">
                <?php if($p['contract_file']): ?><a class="filelink" href="../<?= htmlspecialchars($p['contract_file']) ?>" target="_blank">📎 <span data-lo="ສັນຍາ" data-en="Contract">Contract</span></a> <?php endif; ?>
                <?php if($p['cv_file']): ?><a class="filelink" href="../<?= htmlspecialchars($p['cv_file']) ?>" target="_blank">📎 CV</a><?php endif; ?>
                <?php if(!$p['contract_file'] && !$p['cv_file']): ?>—<?php endif; ?>
            </span></div>
        </div>
    </div>

    <?php if ($mod('payroll')): ?>
    <!-- SALARY -->
    <div class="panel" id="tab-salary">
        <div class="card">
            <div class="ch"><h2 data-lo="ເງິນເດືອນ" data-en="Salary">Salary</h2><a href="hr_salary.php" data-lo="ໜ້າເງິນເດືອນ →" data-en="Payroll page →">Payroll page →</a></div>
            <div class="r"><span class="k" data-lo="ເງິນເດືອນພື້ນຖານ" data-en="Base salary">Base salary</span><span class="v"><?= $p['base_salary']!==null ? '₭ '.kip($p['base_salary']) : '— <span class="tag amber">set it</span>' ?></span></div>
            <?php if ($latestSal): ?>
            <div class="r"><span class="k" data-lo="ໃບແຈ້ງລ່າສຸດ" data-en="Latest payslip">Latest payslip</span><span class="v"><?= $mn[(int)$latestSal['month']] ?> <?= $latestSal['year'] ?> <?= $latestSal['paid_at']?'<span class="tag green">Paid</span>':'<span class="tag amber">Draft</span>' ?></span></div>
            <div class="r"><span class="k" data-lo="ສຸດທິ" data-en="Net pay">Net pay</span><span class="v">₭ <?= kip($latestSal['net_pay']) ?></span></div>
            <?php else: ?>
            <div class="r"><span class="k" data-lo="ໃບແຈ້ງເງິນເດືອນ" data-en="Payslips">Payslips</span><span class="v" data-lo="ຍັງບໍ່ມີ — ສ້າງທີ່ Auto Payroll" data-en="None yet — run Auto Payroll">None yet — run Auto Payroll</span></div>
            <?php endif; ?>
        </div>
        <?php if ($payHist): ?>
        <div class="card">
            <div class="ch"><h2 data-lo="ປະຫວັດການຈ່າຍ" data-en="Pay history">Pay history</h2></div>
            <div class="tbl-wrap">
            <table>
                <thead><tr>
                    <th data-lo="ເດືອນ" data-en="Month">Month</th>
                    <th data-lo="ລວມ" data-en="Gross">Gross</th>
                    <th data-lo="ຫັກ" data-en="Deduct">Deduct</th>
                    <th data-lo="ສຸດທິ" data-en="Net">Net</th>
                    <th data-lo="ສະຖານະ" data-en="Status">Status</th>
                </tr></thead>
                <tbody>
                <?php foreach ($payHist as $h): ?>
                    <tr>
                        <td class="tt"><?= $mn[(int)$h['month']] ?> <?= $h['year'] ?></td>
                        <td>₭ <?= kip((float)$h['base_salary']+(float)$h['total_ot']+(float)$h['total_allowances']) ?></td>
                        <td>₭ <?= kip($h['deductions']) ?></td>
                        <td class="tt">₭ <?= kip($h['net_pay']) ?></td>
                        <td><?= $h['paid_at']?'<span class="tag green">Paid</span>':'<span class="tag amber">Draft</span>' ?></td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
            </div>
        </div>
        <?php endif; ?>
    </div>
    <?php endif; ?>

    <?php if ($mod('attendance')): ?>
    <!-- ATTENDANCE -->
    <div class="panel" id="tab-attendance">
        <div class="card">
            <div class="ch">
                <h2 data-lo="ການເຂົ້າວຽກ" data-en="Attendance">Attendance</h2>
                <form method="GET" class="picker">
                    <input type="hidden" name="id" value="<?= $sid ?>">
                    <input type="hidden" name="tab" value="attendance">
                    <select name="amonth" onchange="this.form.submit()">
                        <?php for($i=1;$i<=12;$i++): ?>
                            <option value="<?= $i ?>" <?= $i===$selAM?'selected':'' ?> data-en="<?= $mn[$i] ?>" data-lo="<?= $mnLo[$i] ?>"><?= $mn[$i] ?></option>
                        <?php endfor; ?>
                    </select>
                    <select name="ayear" onchange="this.form.submit()">
                        <?php for($y=date('Y')-1;$y<=date('Y')+1;$y++): ?>
                            <option value="<?= $y ?>" <?= $y===$selAY?'selected':'' ?>><?= $y ?></option>
                        <?php endfor; ?>
                    </select>
                </form>
            </div>
            <div class="period">📅 <?= date('d/m/Y',strtotime($aStart)) ?> – <?= date('d/m/Y',strtotime($aEnd)) ?></div>

            <?php if (isset($_GET['saved'])): ?>
                <div style="background:var(--green-lt);color:#15803d;padding:10px 14px;border-radius:9px;font-size:13px;font-weight:700;margin-bottom:10px;" data-lo="ບັນທຶກການເຂົ້າວຽກແລ້ວ ✓" data-en="Attendance saved ✓">Attendance saved ✓</div>
            <?php endif; ?>

            <!-- edit toolbar -->
            <?php if ($attRows): ?>
            <div style="display:flex;gap:8px;margin-bottom:10px;">
                <button type="button" class="tabbtn" id="btnEdit" style="padding:7px 15px;font-size:13px;box-shadow:none;" onclick="attEdit(true)">✏️ <span data-lo="ແກ້ໄຂ" data-en="Edit">Edit</span></button>
                <button type="submit" form="attForm" class="tabbtn active" id="btnSave" style="padding:7px 15px;font-size:13px;box-shadow:none;display:none;">💾 <span data-lo="ບັນທຶກ" data-en="Save">Save</span></button>
                <button type="button" class="tabbtn" id="btnCancel" style="padding:7px 15px;font-size:13px;box-shadow:none;display:none;" onclick="attEdit(false)"><span data-lo="ຍົກເລີກ" data-en="Cancel">Cancel</span></button>
            </div>
            <?php endif; ?>

            <div class="stat3">
                <div class="sb"><div class="v" style="color:#16a34a"><?= $att['present'] ?></div><div class="l" data-lo="ມາວຽກ" data-en="Present">Present</div></div>
                <div class="sb"><div class="v" style="color:#d97706"><?= $att['late'] ?>′</div><div class="l" data-lo="ມາຊ້າ" data-en="Late">Late</div></div>
                <div class="sb"><div class="v" style="color:#dc2626"><?= $att['lateDays'] ?></div><div class="l" data-lo="ມື້ມາຊ້າ" data-en="Late days">Late days</div></div>
                <div class="sb"><div class="v" style="color:#2563eb"><?= round($att['ot']/60,1) ?>h</div><div class="l" data-lo="OT" data-en="OT">OT</div></div>
                <div class="sb"><div class="v"><?= number_format($att['hours'],1) ?>h</div><div class="l" data-lo="ຊມລວມ" data-en="Total hrs">Total hrs</div></div>
            </div>

            <form method="POST" id="attForm">
            <input type="hidden" name="action" value="bulk_edit_att">
            <input type="hidden" name="amonth" value="<?= $selAM ?>">
            <input type="hidden" name="ayear" value="<?= $selAY ?>">
            <div class="tbl-wrap">
            <table id="attTable">
                <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>
                </tr></thead>
                <tbody>
                <?php if (!$attRows): ?>
                    <tr><td colspan="8" class="empty" data-lo="ບໍ່ມີຂໍ້ມູນສຳລັບເດືອນນີ້." data-en="No records for this month.">No records for this month.</td></tr>
                <?php else: foreach ($attRows as $r): $rid=(int)$r['id'];
                    $statuses=['present'=>['green','Present','ມາວຽກ'],'late'=>['amber','Late','ມາຊ້າ'],'absent'=>['red','Absent','ຂາດວຽກ'],'half_day'=>['blue','Half day','ເຄິ່ງວັນ'],'holiday'=>['gray','Holiday','ມື້ພັກ']];
                ?>
                    <tr>
                        <td><span class="tt"><?= date('d/m',strtotime($r['work_date'])) ?></span> <span class="mut" style="font-size:11px"><?= date('D',strtotime($r['work_date'])) ?></span>
                            <?php if((int)($r['is_incomplete']??0)): ?> <span class="tag red" data-lo="ບໍ່ຄົບ" data-en="Incomplete">Incomplete</span><?php endif; ?>
                            <?php if(!empty($r['offsite_reason'])): ?><span class="plc" style="color:#92400e;">📝 <?= htmlspecialchars($r['offsite_reason']) ?></span><?php endif; ?></td>
                        <td>
                            <span class="vw"><span class="tt"><?= tm($r['am_in']) ?></span><?php if((int)($r['am_late']??0)>0): ?> <span class="tag amber"><?= (int)$r['am_late'] ?>′</span><?php endif; ?><?php if($r['am_in_photo']): ?> <img class="thumb" src="../<?= htmlspecialchars($r['am_in_photo']) ?>" onclick="showPhoto(this.src)" alt=""><?php endif; ?><?php if(!empty($r['am_in_place'])): ?><span class="plc">📍 <?= htmlspecialchars($r['am_in_place']) ?></span><?php endif; ?></span>
                            <input class="ed" type="time" name="rows[<?= $rid ?>][am_in]" value="<?= substr((string)$r['am_in'],0,5) ?>" style="display:none">
                        </td>
                        <td>
                            <span class="vw"><span class="tt"><?= tm($r['am_out']) ?></span><?php if($r['am_out_photo']): ?> <img class="thumb" src="../<?= htmlspecialchars($r['am_out_photo']) ?>" onclick="showPhoto(this.src)" alt=""><?php endif; ?><?php if(!empty($r['am_out_place'])): ?><span class="plc">📍 <?= htmlspecialchars($r['am_out_place']) ?></span><?php endif; ?></span>
                            <input class="ed" type="time" name="rows[<?= $rid ?>][am_out]" value="<?= substr((string)$r['am_out'],0,5) ?>" style="display:none">
                        </td>
                        <td>
                            <span class="vw"><span class="tt"><?= tm($r['pm_in']) ?></span><?php if((int)($r['pm_late']??0)>0): ?> <span class="tag amber"><?= (int)$r['pm_late'] ?>′</span><?php endif; ?><?php if($r['pm_in_photo']): ?> <img class="thumb" src="../<?= htmlspecialchars($r['pm_in_photo']) ?>" onclick="showPhoto(this.src)" alt=""><?php endif; ?><?php if(!empty($r['pm_in_place'])): ?><span class="plc">📍 <?= htmlspecialchars($r['pm_in_place']) ?></span><?php endif; ?></span>
                            <input class="ed" type="time" name="rows[<?= $rid ?>][pm_in]" value="<?= substr((string)$r['pm_in'],0,5) ?>" style="display:none">
                        </td>
                        <td>
                            <span class="vw"><span class="tt"><?= tm($r['pm_out']) ?></span><?php if($r['pm_out_photo']): ?> <img class="thumb" src="../<?= htmlspecialchars($r['pm_out_photo']) ?>" onclick="showPhoto(this.src)" alt=""><?php endif; ?><?php if(!empty($r['pm_out_place'])): ?><span class="plc">📍 <?= htmlspecialchars($r['pm_out_place']) ?></span><?php endif; ?></span>
                            <input class="ed" type="time" name="rows[<?= $rid ?>][pm_out]" value="<?= substr((string)$r['pm_out'],0,5) ?>" style="display:none">
                        </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>
                            <span class="vw"><?php $sc=$statuses[$r['status']]??['gray',$r['status'],$r['status']]; echo '<span class="tag '.$sc[0].'">'.htmlspecialchars($r['status']).'</span>'; ?></span>
                            <select class="ed" name="rows[<?= $rid ?>][status]" style="display:none;padding:6px 8px;border:1.5px solid var(--border);border-radius:8px;font-family:inherit;font-size:13px;">
                                <?php foreach ($statuses as $sk=>$sm): ?>
                                    <option value="<?= $sk ?>" <?= $r['status']===$sk?'selected':'' ?> data-en="<?= $sm[1] ?>" data-lo="<?= $sm[2] ?>"><?= $sm[1] ?></option>
                                <?php endforeach; ?>
                            </select>
                        </td>
                    </tr>
                <?php endforeach; endif; ?>
                </tbody>
            </table>
            </div>
            </form>
            <p style="font-size:12px;color:var(--muted);margin-top:12px;" data-lo="ກົດທີ່ຮູບເພື່ອເບິ່ງຂະໜາດໃຫຍ່. ບັນທຶກແລ້ວ ລະບົບຄິດໄລ່ ມາຊ້າ/ຊມ/OT ໃໝ່." data-en="Tap a photo to enlarge. On save, late/hours/OT recalculate automatically.">Tap a photo to enlarge. On save, late/hours/OT recalculate automatically.</p>
        </div>
    </div>
    <?php endif; ?>

    <?php if ($mod('leave')): ?>
    <!-- LEAVE -->
    <div class="panel" id="tab-leave">
        <div class="card">
            <div class="ch"><h2 data-lo="ການລາພັກ" data-en="Leave">Leave</h2><a href="leave_balances.php" data-lo="ໂຄຕາ →" data-en="Balances →">Balances →</a></div>
            <div class="stat3">
                <div class="sb"><div class="v"><?= $ent ?></div><div class="l" data-lo="ປະຈຳປີ" data-en="Annual">Annual</div></div>
                <div class="sb"><div class="v" style="color:#d97706"><?= $used ?></div><div class="l" data-lo="ໃຊ້ໄປ" data-en="Used">Used</div></div>
                <div class="sb"><div class="v" style="color:#16a34a"><?= max(0,$ent-$used) ?></div><div class="l" data-lo="ເຫຼືອ" data-en="Left">Left</div></div>
            </div>
            <?php if ($recentLeave): foreach ($recentLeave as $l): ?>
                <div class="mini">
                    <span><?= ucfirst($l['leave_type']) ?> · <?php if((int)($l['is_hourly']??0)): ?><?= date('d/m',strtotime($l['start_date'])) ?> <?= substr($l['start_time'],0,5) ?>-<?= substr($l['end_time'],0,5) ?><?php else: ?><?= date('d/m',strtotime($l['start_date'])) ?>–<?= date('d/m',strtotime($l['end_date'])) ?> (<?= (int)$l['days'] ?>d)<?php endif; ?></span>
                    <span class="tag <?= $l['status']==='approved'?'green':($l['status']==='rejected'?'red':($l['status']==='pending'?'amber':'gray')) ?>"><?= ucfirst($l['status']) ?></span>
                </div>
            <?php endforeach; else: ?>
                <div class="mini" data-lo="ບໍ່ມີຄຳຂໍລາພັກ" data-en="No leave requests">No leave requests</div>
            <?php endif; ?>
        </div>
    </div>
    <?php endif; ?>

    <?php if ($mod('payroll')): ?>
    <!-- LOANS -->
    <div class="panel" id="tab-loans">
        <div class="card">
            <div class="ch"><h2 data-lo="ການກູ້ຢືມ" data-en="Loans">Loans</h2><a href="loans.php" data-lo="ຈັດການ →" data-en="Manage →">Manage →</a></div>
            <div class="r"><span class="k" data-lo="ຍອດຄ້າງ" data-en="Outstanding">Outstanding</span><span class="v" style="color:<?= $loanOut>0?'#dc2626':'inherit' ?>">₭ <?= kip($loanOut) ?></span></div>
            <?php if ($loans): foreach ($loans as $l): $paid=max(0,(float)$l['amount']-(float)$l['remaining']); $pct=(float)$l['amount']>0?min(100,round($paid/(float)$l['amount']*100)):0; ?>
                <div class="mini" style="display:block;">
                    <div style="display:flex;justify-content:space-between;">
                        <span>₭ <?= kip($l['amount']) ?> · <span data-lo="ຕໍ່ເດືອນ" data-en="mo.">mo.</span> ₭<?= kip($l['monthly_payment']) ?></span>
                        <span class="tag <?= $l['status']==='approved'?'blue':'amber' ?>"><?= $l['status']==='approved'?'Repaying':'Pending' ?></span>
                    </div>
                    <?php if ($l['status']==='approved'): ?><div class="bar"><span style="width:<?= $pct ?>%"></span></div><?php endif; ?>
                </div>
            <?php endforeach; else: ?>
                <div class="mini" data-lo="ບໍ່ມີການກູ້ຢືມ" data-en="No loans">No loans</div>
            <?php endif; ?>
        </div>
    </div>
    <?php endif; ?>

</div>

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

<script>
function showPhoto(src){var m=document.getElementById('pmodal');document.getElementById('pmodalImg').src=src;m.style.display='flex';}
function attEdit(on){
    document.querySelectorAll('#attTable .vw').forEach(e=>e.style.display=on?'none':'');
    document.querySelectorAll('#attTable .ed').forEach(e=>e.style.display=on?'':'none');
    var b1=document.getElementById('btnEdit'),b2=document.getElementById('btnSave'),b3=document.getElementById('btnCancel');
    if(b1)b1.style.display=on?'none':'';
    if(b2)b2.style.display=on?'':'none';
    if(b3)b3.style.display=on?'':'none';
}
function showTab(name){
    document.querySelectorAll('.panel').forEach(p=>p.classList.remove('active'));
    document.querySelectorAll('.tabbtn').forEach(b=>b.classList.remove('active'));
    var panel=document.getElementById('tab-'+name);
    var btn=document.querySelector('.tabbtn[data-tab="'+name+'"]');
    if(panel&&btn){panel.classList.add('active');btn.classList.add('active');
        var u=new URL(window.location);u.searchParams.set('tab',name);history.replaceState(null,'',u);}
    else { showTab('profile'); }
}
(function(){
    var t=new URLSearchParams(window.location.search).get('tab')||'profile';
    if(!document.getElementById('tab-'+t)) t='profile';
    showTab(t);
})();
</script>

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