<?php
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/includes/auth.php';
require_once __DIR__ . '/includes/db.php';
require_login();
$mysqli = db();

$month = isset($_GET['month']) ? max(1, min(12, (int)$_GET['month'])) : (int)date('n');
$year = isset($_GET['year']) ? (int)$_GET['year'] : (int)date('Y');
$first = sprintf('%04d-%02d-01', $year, $month);
$last = date('Y-m-t', strtotime($first));

$stmt = $mysqli->prepare('SELECT p.id, e.full_name AS employee_name, p.gross_salary, p.total_incentives, p.total_allowances, p.total_advances, p.total_deductions, p.net_salary, p.paid_on FROM salary_payroll p LEFT JOIN employees e ON e.id=p.employee_id WHERE p.period_month=? AND p.period_year=? ORDER BY e.full_name');
$stmt->bind_param('ii', $month, $year);
$stmt->execute();
$res = $stmt->get_result();
$rows = [];
while ($r = $res->fetch_assoc()) { $rows[] = $r; }

$sum = [
  'gross' => 0, 'inc' => 0, 'allw' => 0, 'adv' => 0, 'ded' => 0, 'net' => 0,
  'paid' => 0, 'unpaid' => 0,
];
foreach ($rows as $r) {
  $sum['gross'] += (float)$r['gross_salary'];
  $sum['inc']   += (float)$r['total_incentives'];
  $sum['allw']  += (float)$r['total_allowances'];
  $sum['adv']   += (float)$r['total_advances'];
  $sum['ded']   += (float)$r['total_deductions'];
  $sum['net']   += (float)$r['net_salary'];
  if (!empty($r['paid_on'])) $sum['paid']++; else $sum['unpaid']++;
}

function fmt_money($n){ return number_format((float)$n, 2, '.', ','); }
$periodLabel = sprintf('%04d-%02d', $year, $month);
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Payroll Monthly Report - <?= htmlspecialchars($periodLabel) ?></title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <style>
    @media print {
      .no-print { display: none !important; }
      .table th, .table td { padding: .35rem .5rem; }
    }
    body { padding: 16px; }
  </style>
</head>
<body>
  <div class="container-fluid">
    <div class="d-flex justify-content-between align-items-center mb-3">
      <div>
        <h4 class="mb-0">Payroll Monthly Report</h4>
        <div class="text-muted">Period: <?= htmlspecialchars($periodLabel) ?></div>
      </div>
      <div class="no-print">
        <button class="btn btn-sm btn-primary" onclick="window.print()"><i class="bi bi-printer"></i> Print</button>
      </div>
    </div>

    <div class="row g-3 mb-3">
      <div class="col-6 col-md-3"><div class="card"><div class="card-body"><div class="small text-muted">Gross Total</div><div class="fw-bold">LKR <?= fmt_money($sum['gross']) ?></div></div></div></div>
      <div class="col-6 col-md-3"><div class="card"><div class="card-body"><div class="small text-muted">OT</div><div class="fw-bold">LKR <?= fmt_money($sum['inc']) ?></div></div></div></div>
      <div class="col-6 col-md-3"><div class="card"><div class="card-body"><div class="small text-muted">Allowances</div><div class="fw-bold">LKR <?= fmt_money($sum['allw']) ?></div></div></div></div>
      <div class="col-6 col-md-3"><div class="card"><div class="card-body"><div class="small text-muted">Advances</div><div class="fw-bold">LKR <?= fmt_money($sum['adv']) ?></div></div></div></div>
      <div class="col-6 col-md-3"><div class="card"><div class="card-body"><div class="small text-muted">Deductions</div><div class="fw-bold">LKR <?= fmt_money($sum['ded']) ?></div></div></div></div>
      <div class="col-6 col-md-3"><div class="card"><div class="card-body"><div class="small text-muted">Net Total</div><div class="fw-bold">LKR <?= fmt_money($sum['net']) ?></div></div></div></div>
      <div class="col-6 col-md-3"><div class="card"><div class="card-body"><div class="small text-muted">Paid Count</div><div class="fw-bold"><?= (int)$sum['paid'] ?></div></div></div></div>
      <div class="col-6 col-md-3"><div class="card"><div class="card-body"><div class="small text-muted">Unpaid Count</div><div class="fw-bold"><?= (int)$sum['unpaid'] ?></div></div></div></div>
    </div>

    <div class="table-responsive">
      <table class="table table-sm table-bordered align-middle">
        <thead class="table-light">
          <tr>
            <th>Employee</th>
            <th class="text-end">Gross</th>
            <th class="text-end">OT</th>
            <th class="text-end">Allowances</th>
            <th class="text-end">Advances</th>
            <th class="text-end">Deductions</th>
            <th class="text-end">Net</th>
            <th>Status</th>
          </tr>
        </thead>
        <tbody>
          <?php if (!$rows): ?>
            <tr><td colspan="8" class="text-center text-muted">No payroll entries</td></tr>
          <?php else: foreach ($rows as $p): ?>
            <tr>
              <td><?= htmlspecialchars($p['employee_name'] ?? '') ?></td>
              <td class="text-end">LKR <?= fmt_money($p['gross_salary']) ?></td>
              <td class="text-end">LKR <?= fmt_money($p['total_incentives']) ?></td>
              <td class="text-end">LKR <?= fmt_money($p['total_allowances']) ?></td>
              <td class="text-end">LKR <?= fmt_money($p['total_advances']) ?></td>
              <td class="text-end">LKR <?= fmt_money($p['total_deductions']) ?></td>
              <td class="text-end">LKR <?= fmt_money($p['net_salary']) ?></td>
              <td><?= $p['paid_on'] ? 'Paid' : 'Unpaid' ?></td>
            </tr>
          <?php endforeach; endif; ?>
        </tbody>
      </table>
    </div>
  </div>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">
</body>
</html>
