<?php
/* ============================================================================
 *  staff/my_salary.php — a staff member's salary for the payroll cycle.
 *  Formula (target):
 *    NET = (Base salary + OT + Other income)
 *          − (Late deduction + Leave-over-15-days + Borrowed money)
 *  Built now: Base salary, approved OT, and the late-attendance deduction
 *  (total monthly late > 60 min → deduct 1 day = salary ÷ 22).
 *  Other income / leave-over-15 / borrow are shown as placeholders (0) for now.
 *  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';
require_once '../config/loans.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');

/* ── Re-authenticate before showing salary (privacy: stop someone who
      borrowed the phone from viewing pay). Unlock lasts a few minutes so
      month navigation doesn't keep re-asking. ── */
$SALARY_UNLOCK_TTL = 300; // seconds
$unlockErr = '';
if (isset($_POST['salary_pw'])) {
    $uq = $pdo->prepare("SELECT password FROM users WHERE id=? LIMIT 1");
    $uq->execute([$userId]);
    $hash = (string)($uq->fetchColumn() ?: '');
    if ($hash !== '' && password_verify((string)$_POST['salary_pw'], $hash)) {
        $_SESSION['salary_unlock'] = time();
        header('Location: my_salary.php?month='.$fm.'&year='.$fy); exit;
    }
    $unlockErr = 'Incorrect password · ລະຫັດຜ່ານບໍ່ຖືກຕ້ອງ';
}
$salaryUnlocked = isset($_SESSION['salary_unlock']) && (time() - (int)$_SESSION['salary_unlock'] <= $SALARY_UNLOCK_TTL);
if (!$salaryUnlocked) {
    if (!function_exists('esc')) { function esc($v){ return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); } }
    ?><!DOCTYPE html><html lang="lo"><head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Verify · My Salary</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&display=swap" rel="stylesheet">
    <style>
        *{box-sizing:border-box;margin:0;padding:0;}
        body{font-family:'Noto Sans Lao','Inter',Arial,sans-serif;background:#0f172a;color:#e2e8f0;min-height:100vh;display:flex;align-items:center;justify-content:center;padding:20px;}
        .lock{background:#111827;border:1px solid #1f2937;border-radius:18px;padding:30px 26px;width:100%;max-width:380px;box-shadow:0 20px 50px rgba(0,0,0,.5);text-align:center;}
        .lock .ic{font-size:40px;margin-bottom:10px;}
        .lock h1{font-size:19px;font-weight:800;color:#fff;margin-bottom:4px;}
        .lock p{font-size:13px;color:#94a3b8;margin-bottom:20px;line-height:1.5;}
        .lock input{width:100%;padding:13px 14px;border:1.5px solid #334155;border-radius:11px;background:#0b1220;color:#fff;font-size:16px;font-family:inherit;margin-bottom:12px;}
        .lock input:focus{outline:none;border-color:#2563eb;}
        .lock button{width:100%;padding:13px;border:none;border-radius:11px;background:#2563eb;color:#fff;font-weight:800;font-size:15px;cursor:pointer;font-family:inherit;}
        .lock button:hover{background:#1d4ed8;}
        .lock .err{background:#7f1d1d;color:#fecaca;border-radius:9px;padding:9px 12px;font-size:13px;font-weight:600;margin-bottom:14px;}
        .lock a{display:inline-block;margin-top:16px;color:#64748b;font-size:13px;text-decoration:none;font-weight:600;}
        .lock a:hover{color:#94a3b8;}
    </style></head><body>
        <form class="lock" method="POST" action="my_salary.php?month=<?= $fm ?>&year=<?= $fy ?>">
            <div class="ic">🔒</div>
            <h1 data-en="Confirm it's you" >ຢືນຢັນວ່າແມ່ນທ່ານ</h1>
            <p>ໃສ່ລະຫັດຜ່ານຂອງທ່ານ ເພື່ອເບິ່ງເງິນເດືອນ<br>Enter your password to view your salary</p>
            <?php if ($unlockErr): ?><div class="err">⚠️ <?= esc($unlockErr) ?></div><?php endif; ?>
            <input type="password" name="salary_pw" placeholder="Password · ລະຫັດຜ່ານ" autofocus autocomplete="current-password" required>
            <button type="submit">🔓 <span>Unlock · ປົດລັອກ</span></button>
            <a href="../customer/desktop.php">← Back</a>
        </form>
    </body></html><?php
    exit;
}

const LATE_GRACE_MIN = 60;
const DAY_DIVISOR    = 22;
const HOURS_PER_DAY  = 8;

/* base salary + OT 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;
$hourlyRate = $base > 0 ? $base / (DAY_DIVISOR * HOURS_PER_DAY) : 0;

/* OT rate: latest hr_salary row if set, else derived hourly rate */
$otRate = 0;
try {
    $orr = $pdo->prepare("SELECT ot_rate FROM hr_salary WHERE staff_id=? AND company_id=? ORDER BY year DESC, month DESC LIMIT 1");
    $orr->execute([$userId, $companyId]);
    $otRate = (float)($orr->fetchColumn() ?: 0);
} catch (Throwable $e) {}
if ($otRate <= 0) $otRate = $hourlyRate;

/* 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) {}

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 totals within period */
$totalLate = 0; $otMinutes = 0; $present = 0;
$st = $pdo->prepare("SELECT late_minutes, ot_minutes, ot_status, status FROM hr_attendance WHERE staff_id=? AND company_id=? AND work_date BETWEEN ? AND ?");
$st->execute([$userId, $companyId, $periodStart, $periodEnd]);
foreach ($st->fetchAll(PDO::FETCH_ASSOC) as $r) {
    $totalLate += (int)($r['late_minutes'] ?? 0);
    if (($r['ot_status'] ?? '') === 'approved') $otMinutes += (int)($r['ot_minutes'] ?? 0);
    if (in_array($r['status'], ['present','late','half_day'])) $present++;
}

/* ── income ── */
$otHours = round($otMinutes / 60, 2);
$otPay   = round($otHours * $otRate, 0);
$otherIncome = 0;        // future

/* ── deductions ── */
$lateDeduction  = $totalLate > LATE_GRACE_MIN ? round($dailyRate, 0) : 0;
$leaveDeduction = 0;     // future: leave over 15 days
$borrow         = loan_period_deduction($pdo, $companyId, $userId, $periodStart);  // loan repayment this cycle
$loanOutstanding = loan_outstanding($pdo, $companyId, $userId);

$income     = $base + $otPay + $otherIncome;
$deductions = $lateDeduction + $leaveDeduction + $borrow;
$net        = $income - $deductions;

$mn   = ["","January","February","March","April","May","June","July","August","September","October","November","December"];
$mnLo = ["","ມັງກອນ","ກຸມພາ","ມີນາ","ເມສາ","ພຶດສະພາ","ມິຖຸນາ","ກໍລະກົດ","ສິງຫາ","ກັນຍາ","ຕຸລາ","ພະຈິກ","ທັນວາ"];
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 Salary</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;}
        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:4px;}
        .range{font-size:13px;color:var(--muted);font-weight:700;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;}
        .net-card{background:linear-gradient(135deg,#042f2e,#0f766e);border-radius:18px;padding:22px;color:#fff;margin-bottom:16px;text-align:center;}
        .net-card .nl{font-size:12px;color:rgba(255,255,255,.78);text-transform:uppercase;letter-spacing:.5px;font-weight:700;}
        .net-card .nv{font-size:34px;font-weight:800;margin-top:4px;}
        .net-card .ns{font-size:12px;color:rgba(255,255,255,.7);margin-top:6px;}
        .card{background:var(--surface);border:1px solid var(--border);border-radius:14px;box-shadow:0 2px 14px rgba(15,23,42,.06);padding:6px 16px;margin-bottom:14px;}
        .sec{font-size:12px;font-weight:800;text-transform:uppercase;letter-spacing:.5px;padding:14px 0 6px;}
        .sec.in{color:#15803d;}.sec.de{color:var(--red);}
        .r{display:flex;justify-content:space-between;align-items:center;gap:10px;padding:11px 0;border-bottom:1px solid var(--border);font-size:14px;}
        .r:last-child{border-bottom:none;}
        .k{color:var(--text);font-weight:600;display:flex;align-items:center;gap:7px;}
        .k .sub{font-size:11px;color:var(--muted);font-weight:500;}
        .v{font-weight:800;}
        .v.plus{color:#15803d;}.v.minus{color:var(--red);}
        .soon{font-size:9px;font-weight:800;background:#fef3c7;color:#92400e;padding:1px 6px;border-radius:999px;}
        .tot{display:flex;justify-content:space-between;padding:12px 0 2px;font-weight:800;font-size:15px;border-top:2px solid var(--border);margin-top:4px;}
        .formula{font-size:11px;color:var(--muted);text-align:center;line-height:1.6;padding:8px 0 20px;}
    </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 Salary">My Salary</h1>
    <div class="range">📅 <?= 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>

    <div class="net-card">
        <div class="nl" data-lo="ເງິນເດືອນສຸດທິ" data-en="Net pay">Net pay</div>
        <div class="nv">₭ <?= kip($net) ?></div>
        <div class="ns" data-lo="ປະມານການ — ລໍຖ້າ HR ຢືນຢັນ" data-en="Estimate — pending HR confirmation">Estimate — pending HR confirmation</div>
    </div>

    <!-- income -->
    <div class="card">
        <div class="sec in" data-lo="ລາຍຮັບ" data-en="Income">Income</div>
        <div class="r">
            <span class="k" data-lo="ເງິນເດືອນພື້ນຖານ" data-en="Base salary">Base salary</span>
            <span class="v plus"><?= $base>0 ? '₭ '.kip($base) : '—' ?></span>
        </div>
        <div class="r">
            <span class="k"><span data-lo="ໂມງລ່ວງເວລາ (OT)" data-en="Overtime (OT)">Overtime (OT)</span>
                <?php if ($otHours>0): ?><span class="sub"><?= $otHours ?>h × ₭<?= kip($otRate) ?></span><?php endif; ?></span>
            <span class="v plus"><?= $otPay>0 ? '₭ '.kip($otPay) : '₭ 0' ?></span>
        </div>
        <div class="r">
            <span class="k"><span data-lo="ລາຍຮັບອື່ນໆ" data-en="Other income">Other income</span> <span class="soon" data-lo="ໄວໆ" data-en="soon">soon</span></span>
            <span class="v plus">₭ 0</span>
        </div>
        <div class="tot"><span data-lo="ລວມລາຍຮັບ" data-en="Total income">Total income</span><span style="color:#15803d">₭ <?= kip($income) ?></span></div>
    </div>

    <!-- deductions -->
    <div class="card">
        <div class="sec de" data-lo="ລາຍການຫັກ" data-en="Deductions">Deductions</div>
        <div class="r">
            <span class="k"><span data-lo="ຫັກມາຊ້າ" data-en="Late deduction">Late deduction</span>
                <span class="sub"><?= $totalLate ?>′ <?= $lateDeduction>0 ? '· &gt;60 → 1 day' : '· ≤60 grace' ?></span></span>
            <span class="v minus"><?= $lateDeduction>0 ? '− ₭ '.kip($lateDeduction) : '₭ 0' ?></span>
        </div>
        <div class="r">
            <span class="k"><span data-lo="ລາພັກເກີນ 15 ວັນ" data-en="Leave over 15 days">Leave over 15 days</span> <span class="soon" data-lo="ໄວໆ" data-en="soon">soon</span></span>
            <span class="v minus">₭ 0</span>
        </div>
        <div class="r">
            <span class="k"><span data-lo="ການກູ້ຢືມ" data-en="Borrowed money">Borrowed money</span>
                <?php if ($loanOutstanding>0): ?><span class="sub"><span data-lo="ຄ້າງ" data-en="left">left</span> ₭<?= kip($loanOutstanding) ?></span><?php endif; ?></span>
            <span class="v minus"><?= $borrow>0 ? '− ₭ '.kip($borrow) : '₭ 0' ?></span>
        </div>
        <div class="tot"><span data-lo="ລວມຫັກ" data-en="Total deductions">Total deductions</span><span style="color:var(--red)">− ₭ <?= kip($deductions) ?></span></div>
    </div>

    <div class="formula"
         data-lo="ສູດ: (ເງິນເດືອນ + OT + ລາຍຮັບອື່ນ) − (ມາຊ້າ + ລາພັກເກີນ 15 ວັນ + ເງິນກູ້) = ສຸດທິ"
         data-en="Formula: (Salary + OT + Other) − (Late + Leave over 15 days + Borrow) = Net">
        Formula: (Salary + OT + Other) − (Late + Leave over 15 days + Borrow) = Net
    </div>

    <?php if ($base <= 0): ?>
    <div class="formula" style="color:var(--amber);font-weight:700;"
         data-lo="⚠ ຍັງບໍ່ໄດ້ຕັ້ງເງິນເດືອນພື້ນຖານ — ກະລຸນາແຈ້ງ HR."
         data-en="⚠ Base salary not set yet — please contact HR.">⚠ Base salary not set yet — contact HR.</div>
    <?php endif; ?>
</div>

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