<?php
/* ═══════════════════════════════════════════
   ROUTING: serve different pages from one file
   OR copy each section to its own file.
   Page is determined by the filename.
   ═══════════════════════════════════════════ */
session_start();

if (!isset($_SESSION["user_id"]) || $_SESSION["role"] !== "staff") {
    header("Location: ../auth/login.php"); exit;
}

require_once '../config/database.php';

$userId    = (int)$_SESSION["user_id"];
$companyId = (int)$_SESSION["company_id"];
$page      = basename(__FILE__, ".php"); // my_salary | my_attendance | my_leave | my_allowances | my_payslips

/* ── Leave submission ── */
$leaveMsg = "";
if ($page === "my_leave" && $_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST["submit_leave"])) {
    $type      = $_POST["leave_type"]  ?? "annual";
    $startDate = $_POST["start_date"]  ?? "";
    $endDate   = $_POST["end_date"]    ?? "";
    $reason    = trim($_POST["reason"] ?? "");
    $allowed   = ["annual","sick","unpaid","maternity","other"];
    if (!in_array($type, $allowed)) $type = "annual";

    if ($startDate && $endDate && $endDate >= $startDate) {
        $days = (int)((strtotime($endDate) - strtotime($startDate)) / 86400) + 1;
        $pdo->prepare("
            INSERT INTO hr_leave (staff_id, company_id, leave_type, start_date, end_date, days, reason, status, created_at)
            VALUES (?,?,?,?,?,?,?,'pending',NOW())
        ")->execute([$userId, $companyId, $type, $startDate, $endDate, $days, $reason]);
        $leaveMsg = "success";
    } else {
        $leaveMsg = "error";
    }
}

/* ── Data fetching ── */
$monthFilter = (int)($_GET["month"] ?? date("n"));
$yearFilter  = (int)($_GET["year"]  ?? date("Y"));

$salaryRows = $attendanceRows = $leaveRows = $allowanceRows = $payslipRows = [];

if ($page === "my_salary") {
    $st = $pdo->prepare("
        SELECT * FROM hr_salary
        WHERE staff_id=? AND company_id=?
        ORDER BY year DESC, month DESC
    ");
    $st->execute([$userId, $companyId]);
    $salaryRows = $st->fetchAll(PDO::FETCH_ASSOC);
}

if ($page === "my_attendance") {
    $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([$userId, $companyId, $monthFilter, $yearFilter]);
    $attendanceRows = $st->fetchAll(PDO::FETCH_ASSOC);
}

if ($page === "my_leave") {
    $st = $pdo->prepare("
        SELECT * FROM hr_leave WHERE staff_id=? AND company_id=?
        ORDER BY created_at DESC LIMIT 50
    ");
    $st->execute([$userId, $companyId]);
    $leaveRows = $st->fetchAll(PDO::FETCH_ASSOC);
}

if ($page === "my_allowances") {
    $st = $pdo->prepare("
        SELECT * FROM hr_allowances WHERE staff_id=? AND company_id=?
        ORDER BY type ASC
    ");
    $st->execute([$userId, $companyId]);
    $allowanceRows = $st->fetchAll(PDO::FETCH_ASSOC);
}

if ($page === "my_payslips") {
    $st = $pdo->prepare("
        SELECT p.*, s.base_salary, s.total_ot, s.total_allowances, s.deductions, s.net_pay, s.ot_hours
        FROM hr_payslips p
        JOIN hr_salary s ON s.id = p.salary_id
        WHERE p.staff_id=? AND p.company_id=?
        ORDER BY p.year DESC, p.month DESC
    ");
    $st->execute([$userId, $companyId]);
    $payslipRows = $st->fetchAll(PDO::FETCH_ASSOC);
}

$monthNames = ["","January","February","March","April","May","June","July","August","September","October","November","December"];
$statusColors = [
    "present"  => ["#dcfce7","#16a34a"],
    "absent"   => ["#fee2e2","#dc2626"],
    "late"     => ["#fef3c7","#d97706"],
    "half_day" => ["#ede9fe","#7c3aed"],
    "holiday"  => ["#dbeafe","#2563eb"],
];
$leaveColors = [
    "pending"  => ["#fef3c7","#d97706"],
    "approved" => ["#dcfce7","#16a34a"],
    "rejected" => ["#fee2e2","#dc2626"],
];
?>
<!DOCTYPE html>
<html lang="lo">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <?php
    $titles = [
        "my_salary"     => "My Salary",
        "my_attendance" => "My Attendance",
        "my_leave"      => "My Leave",
        "my_allowances" => "My Allowances",
        "my_payslips"   => "My Payslips",
    ];
    ?>
    <title><?= $titles[$page] ?? "Staff Portal" ?> — <?= htmlspecialchars($_SESSION["company_name"]) ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+Lao:wght@400;600;700;800&family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <style>
        *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
        :root {
            --primary: #2563eb; --surface: #ffffff; --bg: #f0f4f8;
            --border: #e2e8f0; --text: #0f172a; --muted: #64748b;
            --green: #16a34a; --green-lt: #dcfce7;
            --red: #dc2626; --red-lt: #fee2e2;
            --amber: #d97706; --amber-lt: #fef3c7;
            --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 */
        .top-bar { background: var(--surface); border-bottom: 1px solid var(--border); 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-link { display: inline-flex; align-items: center; gap: 6px; color: var(--muted); text-decoration: none; font-size: 13px; font-weight: 600; padding: 6px 12px; border-radius: 8px; border: 1.5px solid var(--border); transition: all .15s; }
        .back-link:hover { border-color: var(--primary); color: var(--primary); }
        .top-bar h1 { font-size: 17px; font-weight: 800; flex: 1; }

        .page-body { padding: 28px 32px; max-width: 1000px; margin: auto; }

        /* filter bar */
        .filter-bar { display: flex; align-items: center; gap: 10px; margin-bottom: 20px; flex-wrap: wrap; }
        .filter-bar select, .filter-bar input { padding: 8px 12px; border: 1.5px solid var(--border); border-radius: 8px; font-size: 13px; font-family: inherit; outline: none; }
        .filter-bar select:focus { border-color: var(--primary); }
        .btn-filter { padding: 8px 18px; border-radius: 8px; background: var(--primary); color: #fff; border: none; font-size: 13px; font-weight: 700; cursor: pointer; font-family: inherit; }

        /* table card */
        .table-card { background: var(--surface); border-radius: var(--radius); box-shadow: var(--shadow); border: 1px solid var(--border); overflow: hidden; margin-bottom: 24px; }
        .card-header { padding: 16px 20px; border-bottom: 1px solid var(--border); display: flex; align-items: center; justify-content: space-between; }
        .card-title { font-size: 15px; font-weight: 800; }
        table { width: 100%; border-collapse: collapse; }
        thead th { background: #f8fafc; padding: 11px 16px; text-align: left; font-size: 11px; font-weight: 700; color: var(--muted); text-transform: uppercase; letter-spacing: .5px; border-bottom: 1px solid var(--border); }
        tbody tr { border-bottom: 1px solid var(--border); transition: background .1s; }
        tbody tr:last-child { border-bottom: none; }
        tbody tr:hover { background: #f8fafc; }
        td { padding: 12px 16px; font-size: 13px; vertical-align: middle; }

        .badge { display: inline-flex; align-items: center; padding: 3px 10px; border-radius: 999px; font-size: 11px; font-weight: 700; }

        /* leave form */
        .leave-form-card { background: var(--surface); border-radius: var(--radius); box-shadow: var(--shadow); border: 1px solid var(--border); padding: 24px; margin-bottom: 24px; }
        .form-row2 { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; }
        .form-group { margin-bottom: 16px; }
        label { display: block; font-size: 13px; font-weight: 700; color: var(--text); margin-bottom: 6px; }
        input[type="date"], select, textarea { width: 100%; padding: 10px 13px; border: 1.5px solid var(--border); border-radius: 9px; font-size: 13px; font-family: inherit; outline: none; background: #f8fafc; }
        input:focus, select:focus, textarea:focus { border-color: var(--primary); background: #fff; }
        .btn-submit { padding: 11px 24px; background: linear-gradient(135deg,#1e3a5f,#2563eb); color: #fff; border: none; border-radius: 9px; font-size: 14px; font-weight: 700; cursor: pointer; font-family: inherit; }

        .alert { padding: 12px 16px; border-radius: 10px; margin-bottom: 18px; font-size: 13px; font-weight: 600; }
        .alert-success { background: var(--green-lt); color: var(--green); border: 1.5px solid #86efac; }
        .alert-error   { background: var(--red-lt);   color: var(--red);   border: 1.5px solid #fca5a5; }

        /* allowance cards */
        .allow-grid { display: grid; grid-template-columns: repeat(auto-fill,minmax(200px,1fr)); gap: 14px; }
        .allow-card { background: var(--surface); border-radius: var(--radius); box-shadow: var(--shadow); border: 1px solid var(--border); padding: 18px; }
        .allow-type { font-size: 13px; font-weight: 700; color: var(--text); }
        .allow-val  { font-size: 22px; font-weight: 800; color: var(--primary); margin-top: 4px; }
        .allow-sub  { font-size: 11px; color: var(--muted); margin-top: 3px; }

        /* payslip row */
        .print-btn { display: inline-flex; align-items: center; gap: 5px; padding: 5px 12px; border-radius: 7px; border: 1.5px solid #93c5fd; color: var(--primary); background: #eff6ff; font-size: 12px; font-weight: 700; cursor: pointer; font-family: inherit; transition: all .15s; text-decoration: none; }
        .print-btn:hover { background: var(--primary); color: #fff; border-color: var(--primary); }

        .empty { text-align: center; padding: 50px; color: var(--muted); }
        .empty .icon { font-size: 44px; margin-bottom: 10px; }

        @media (max-width: 700px) { .page-body { padding: 16px; } .top-bar { padding: 10px 16px; } .form-row2 { grid-template-columns: 1fr; } }
    </style>
</head>
<body>

<div class="top-bar">
    <a class="back-link" href="dashboard.php">← Dashboard</a>
    <h1>
        <?php
        $icons = ["my_salary"=>"💵","my_attendance"=>"🕐","my_leave"=>"🏖️","my_allowances"=>"🎁","my_payslips"=>"🧾"];
        echo ($icons[$page] ?? "") . " " . ($titles[$page] ?? "");
        ?>
    </h1>
</div>

<div class="page-body">

<?php /* ══════════ MY SALARY ══════════ */ ?>
<?php if ($page === "my_salary"): ?>
    <div class="table-card">
        <div class="card-header">
            <div class="card-title">Salary History</div>
        </div>
        <table>
            <thead>
                <tr>
                    <th>Period</th>
                    <th>Base Salary</th>
                    <th>OT Hours</th>
                    <th>OT Pay</th>
                    <th>Allowances</th>
                    <th>Deductions</th>
                    <th>Net Pay</th>
                    <th>Status</th>
                </tr>
            </thead>
            <tbody>
            <?php if (empty($salaryRows)): ?>
                <tr><td colspan="8"><div class="empty"><div class="icon">💵</div><p>No salary records yet.</p></div></td></tr>
            <?php else: ?>
                <?php foreach ($salaryRows as $r): ?>
                <tr>
                    <td style="font-weight:700;"><?= $monthNames[(int)$r['month']] ?> <?= $r['year'] ?></td>
                    <td>₭ <?= number_format((float)$r['base_salary'],0) ?></td>
                    <td><?= number_format((float)$r['ot_hours'],1) ?> hrs</td>
                    <td>₭ <?= number_format((float)$r['total_ot'],0) ?></td>
                    <td>₭ <?= number_format((float)$r['total_allowances'],0) ?></td>
                    <td style="color:var(--red);">- ₭ <?= number_format((float)$r['deductions'],0) ?></td>
                    <td style="font-weight:800;color:var(--primary);font-size:15px;">₭ <?= number_format((float)$r['net_pay'],0) ?></td>
                    <td>
                        <?php if ($r['paid_at']): ?>
                            <span class="badge" style="background:var(--green-lt);color:var(--green);">✅ Paid</span>
                        <?php else: ?>
                            <span class="badge" style="background:var(--amber-lt);color:var(--amber);">⏳ Pending</span>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
            <?php endif; ?>
            </tbody>
        </table>
    </div>
<?php endif; ?>

<?php /* ══════════ MY ATTENDANCE ══════════ */ ?>
<?php if ($page === "my_attendance"): ?>
    <form method="GET" class="filter-bar">
        <select name="month">
            <?php for ($i=1; $i<=12; $i++): ?>
                <option value="<?= $i ?>" <?= $i === $monthFilter ? "selected" : "" ?>><?= $monthNames[$i] ?></option>
            <?php endfor; ?>
        </select>
        <select name="year">
            <?php for ($y = date("Y"); $y >= date("Y")-3; $y--): ?>
                <option value="<?= $y ?>" <?= $y === $yearFilter ? "selected" : "" ?>><?= $y ?></option>
            <?php endfor; ?>
        </select>
        <button class="btn-filter" type="submit">View</button>
    </form>

    <div class="table-card">
        <div class="card-header">
            <div class="card-title">Attendance — <?= $monthNames[$monthFilter] ?> <?= $yearFilter ?></div>
            <span style="font-size:13px;color:var(--muted);">
                <?= count(array_filter($attendanceRows, fn($r) => $r['status'] === 'present')) ?> days present
            </span>
        </div>
        <table>
            <thead>
                <tr><th>Date</th><th>Check In</th><th>Check Out</th><th>Hours</th><th>Status</th><th>Note</th></tr>
            </thead>
            <tbody>
            <?php if (empty($attendanceRows)): ?>
                <tr><td colspan="6"><div class="empty"><div class="icon">🕐</div><p>No attendance records for this period.</p></div></td></tr>
            <?php else: ?>
                <?php foreach ($attendanceRows as $r):
                    $sc = $statusColors[$r['status']] ?? ["#f1f5f9","#475569"];
                ?>
                <tr>
                    <td style="font-weight:700;"><?= date("d M Y (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)." hrs" : "—" ?></td>
                    <td><span class="badge" style="background:<?= $sc[0] ?>;color:<?= $sc[1] ?>;"><?= ucfirst(str_replace("_"," ",$r['status'])) ?></span></td>
                    <td style="color:var(--muted);font-size:12px;"><?= htmlspecialchars($r['note'] ?: "—") ?></td>
                </tr>
                <?php endforeach; ?>
            <?php endif; ?>
            </tbody>
        </table>
    </div>
<?php endif; ?>

<?php /* ══════════ MY LEAVE ══════════ */ ?>
<?php if ($page === "my_leave"): ?>

    <?php if ($leaveMsg === "success"): ?>
        <div class="alert alert-success">✅ Leave request submitted successfully. Awaiting approval.</div>
    <?php elseif ($leaveMsg === "error"): ?>
        <div class="alert alert-error">⚠️ Invalid dates. End date must be on or after start date.</div>
    <?php endif; ?>

    <!-- Submit leave form -->
    <div class="leave-form-card">
        <div style="font-size:15px;font-weight:800;margin-bottom:18px;padding-bottom:12px;border-bottom:1px solid var(--border);">
            📝 New Leave Request
        </div>
        <form method="POST">
            <input type="hidden" name="submit_leave" value="1">
            <div class="form-row2">
                <div class="form-group">
                    <label>Leave Type</label>
                    <select name="leave_type">
                        <option value="annual">🏖️ Annual Leave</option>
                        <option value="sick">🤒 Sick Leave</option>
                        <option value="unpaid">💸 Unpaid Leave</option>
                        <option value="maternity">🤱 Maternity Leave</option>
                        <option value="other">📋 Other</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>Days (auto-calculated)</label>
                    <input type="text" id="days-preview" readonly placeholder="Select dates below" style="background:#f8fafc;color:var(--muted);">
                </div>
            </div>
            <div class="form-row2">
                <div class="form-group">
                    <label>Start Date</label>
                    <input type="date" name="start_date" id="start_date" required onchange="calcDays()">
                </div>
                <div class="form-group">
                    <label>End Date</label>
                    <input type="date" name="end_date" id="end_date" required onchange="calcDays()">
                </div>
            </div>
            <div class="form-group">
                <label>Reason</label>
                <textarea name="reason" rows="2" placeholder="Optional reason…"></textarea>
            </div>
            <button class="btn-submit" type="submit">📤 Submit Request</button>
        </form>
    </div>

    <!-- Leave history -->
    <div class="table-card">
        <div class="card-header"><div class="card-title">Leave History</div></div>
        <table>
            <thead><tr><th>Type</th><th>From</th><th>To</th><th>Days</th><th>Reason</th><th>Status</th><th>Submitted</th></tr></thead>
            <tbody>
            <?php if (empty($leaveRows)): ?>
                <tr><td colspan="7"><div class="empty"><div class="icon">🏖️</div><p>No leave requests yet.</p></div></td></tr>
            <?php else: ?>
                <?php foreach ($leaveRows as $r):
                    $lc = $leaveColors[$r['status']] ?? ["#f1f5f9","#475569"];
                    $typeLabels = ["annual"=>"🏖️ Annual","sick"=>"🤒 Sick","unpaid"=>"💸 Unpaid","maternity"=>"🤱 Maternity","other"=>"📋 Other"];
                ?>
                <tr>
                    <td><span class="badge" style="background:#f1f5f9;color:var(--text);"><?= $typeLabels[$r['leave_type']] ?? $r['leave_type'] ?></span></td>
                    <td><?= date("d M Y", strtotime($r['start_date'])) ?></td>
                    <td><?= date("d M Y", strtotime($r['end_date'])) ?></td>
                    <td style="font-weight:700;"><?= $r['days'] ?></td>
                    <td style="color:var(--muted);font-size:12px;"><?= htmlspecialchars($r['reason'] ?: "—") ?></td>
                    <td><span class="badge" style="background:<?= $lc[0] ?>;color:<?= $lc[1] ?>;"><?= ucfirst($r['status']) ?></span></td>
                    <td style="color:var(--muted);font-size:12px;"><?= date("d M Y", strtotime($r['created_at'])) ?></td>
                </tr>
                <?php endforeach; ?>
            <?php endif; ?>
            </tbody>
        </table>
    </div>
<?php endif; ?>

<?php /* ══════════ MY ALLOWANCES ══════════ */ ?>
<?php if ($page === "my_allowances"): ?>
    <?php if (empty($allowanceRows)): ?>
        <div class="empty" style="background:var(--surface);border-radius:var(--radius);padding:60px;box-shadow:var(--shadow);">
            <div class="icon">🎁</div>
            <p>No allowances assigned yet.</p>
        </div>
    <?php else: ?>
        <?php $total = array_sum(array_column($allowanceRows,'amount')); ?>
        <div style="background:linear-gradient(135deg,#1e3a5f,#2563eb);border-radius:14px;padding:20px 24px;color:#fff;margin-bottom:20px;display:flex;justify-content:space-between;align-items:center;">
            <div>
                <div style="font-size:12px;opacity:.75;text-transform:uppercase;letter-spacing:.5px;">Total Monthly Allowances</div>
                <div style="font-size:28px;font-weight:800;margin-top:4px;">₭ <?= number_format($total,0) ?></div>
            </div>
            <span style="font-size:36px;opacity:.6;">🎁</span>
        </div>
        <div class="allow-grid">
            <?php foreach ($allowanceRows as $r): ?>
            <div class="allow-card">
                <div class="allow-type"><?= htmlspecialchars($r['type']) ?></div>
                <div class="allow-val">₭ <?= number_format((float)$r['amount'],0) ?></div>
                <div class="allow-sub">
                    <?= $r['is_recurring'] ? "🔄 Monthly" : "One-time" ?>
                    <?php if ($r['effective_from']): ?> · From <?= date("d M Y", strtotime($r['effective_from'])) ?><?php endif; ?>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
<?php endif; ?>

<?php /* ══════════ MY PAYSLIPS ══════════ */ ?>
<?php if ($page === "my_payslips"): ?>
    <div class="table-card">
        <div class="card-header"><div class="card-title">Payslip History</div></div>
        <table>
            <thead><tr><th>Period</th><th>Base</th><th>OT</th><th>Allowances</th><th>Deductions</th><th>Net Pay</th><th>Payslip</th></tr></thead>
            <tbody>
            <?php if (empty($payslipRows)): ?>
                <tr><td colspan="7"><div class="empty"><div class="icon">🧾</div><p>No payslips generated yet.</p></div></td></tr>
            <?php else: ?>
                <?php foreach ($payslipRows as $r): ?>
                <tr>
                    <td style="font-weight:700;"><?= $monthNames[(int)$r['month']] ?> <?= $r['year'] ?></td>
                    <td>₭ <?= number_format((float)$r['base_salary'],0) ?></td>
                    <td>₭ <?= number_format((float)$r['total_ot'],0) ?></td>
                    <td>₭ <?= number_format((float)$r['total_allowances'],0) ?></td>
                    <td style="color:var(--red);">- ₭ <?= number_format((float)$r['deductions'],0) ?></td>
                    <td style="font-weight:800;color:var(--primary);font-size:15px;">₭ <?= number_format((float)$r['net_pay'],0) ?></td>
                    <td>
                        <a class="print-btn"
                            href="print_payslip.php?id=<?= $r['id'] ?>"
                            target="_blank">
                            🖨️ View / Print
                        </a>
                    </td>
                </tr>
                <?php endforeach; ?>
            <?php endif; ?>
            </tbody>
        </table>
    </div>
<?php endif; ?>

</div><!-- /page-body -->

<script>
/* Days calculator for leave form */
function calcDays() {
    const s = document.getElementById('start_date')?.value;
    const e = document.getElementById('end_date')?.value;
    const p = document.getElementById('days-preview');
    if (!p) return;
    if (s && e && e >= s) {
        const days = Math.round((new Date(e) - new Date(s)) / 86400000) + 1;
        p.value = days + " day" + (days !== 1 ? "s" : "");
    } else {
        p.value = "";
    }
}
</script>
</body>
</html>