<?php
require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../includes/functions.php';
startSession(); requireLogin();
$db     = Database::getInstance();
$page   = 'Muster Report';
$month  = intval($_GET['month'] ?? date('n'));
$year   = intval($_GET['year']  ?? date('Y'));
$dept   = cleanInt($_GET['dept'] ?? 0);
$format = $_GET['format'] ?? 'html';
$months = ['','January','February','March','April','May','June','July','August','September','October','November','December'];

$depts      = $db->fetchAll("SELECT id,name FROM departments WHERE is_active=1 ORDER BY name");
$deptWhere  = $dept ? "AND e.department_id=$dept" : '';
// FIX (07 Jul 2026): scope to current org.
[$orgClause, $orgParams] = orgScopeClause($db, 'e.company_id');
$employees  = $db->fetchAll("SELECT e.id,e.employee_id AS emp_code,e.first_name,e.last_name,d.name AS dept
    FROM employees e LEFT JOIN departments d ON d.id=e.department_id
    WHERE e.status='active' AND $orgClause $deptWhere ORDER BY e.first_name", $orgParams);

$daysInMonth = date('t', mktime(0,0,0,$month,1,$year));

// Build muster data: empId -> date -> status
$musterData = [];
if ($employees) {
    $empIds = implode(',', array_column($employees,'id'));
    $rows   = $db->fetchAll("SELECT employee_id,muster_date,status FROM muster
        WHERE employee_id IN($empIds) AND MONTH(muster_date)=? AND YEAR(muster_date)=?",
        [$month,$year]);
    foreach ($rows as $r) $musterData[$r['employee_id']][$r['muster_date']] = $r['status'];
}

// Summary data
$summary = [];
if ($employees) {
    $empIds = implode(',', array_column($employees,'id'));
    $rows   = $db->fetchAll("SELECT * FROM muster_summary WHERE employee_id IN($empIds) AND month=? AND year=?", [$month,$year]);
    foreach ($rows as $r) $summary[$r['employee_id']] = $r;
}

$statusColors = ['P'=>'#dcfce7','A'=>'#fee2e2','H'=>'#fef9c3','L'=>'#dbeafe','WO'=>'#f3f4f6','PH'=>'#e0f2fe','CO'=>'#ede9fe','LOP'=>'#fde8d8'];
$statusText   = ['P'=>'#166534','A'=>'#991b1b','H'=>'#854d0e','L'=>'#1e40af','WO'=>'#6b7280','PH'=>'#0c4a6e','CO'=>'#5b21b6','LOP'=>'#9a3412'];

// CSV Export
if ($format === 'csv') {
    header('Content-Type: text/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename="muster_'.$months[$month].'_'.$year.'.csv"');
    header('Pragma: no-cache');
    $out = fopen('php://output','w');
    // Header row: Emp, Name, Dept, Day1..DayN, P, A, H, L, WO, LOP, OT
    $hdr = ['Emp Code','Name','Dept'];
    for($d=1;$d<=$daysInMonth;$d++) $hdr[] = $d;
    $hdr = array_merge($hdr,['Present','Absent','Half Day','Leave','Week Off','LOP','OT Hrs']);
    fputcsv($out,$hdr);
    foreach($employees as $e) {
        $row = [$e['emp_code'],$e['first_name'].' '.$e['last_name'],$e['dept']??''];
        for($d=1;$d<=$daysInMonth;$d++) {
            $ds = sprintf('%04d-%02d-%02d',$year,$month,$d);
            $row[] = $musterData[$e['id']][$ds] ?? '';
        }
        $s = $summary[$e['id']] ?? [];
        $row = array_merge($row,[$s['present_days']??0,$s['absent_days']??0,$s['half_days']??0,$s['leave_days']??0,$s['week_off_days']??0,$s['lop_days']??0,$s['ot_hours']??0]);
        fputcsv($out,$row);
    }
    fclose($out); exit;
}

include __DIR__ . '/../../includes/header.php';
?>
<div class="pc-card mb-3">
  <form method="GET" class="d-flex gap-2 flex-wrap align-items-end">
    <div><label class="pc-label">Month</label>
      <select name="month" class="form-select form-select-sm">
        <?php for($m=1;$m<=12;$m++): ?><option value="<?=$m?>" <?=$m===$month?'selected':''?>><?=$months[$m]?></option><?php endfor; ?>
      </select></div>
    <div><label class="pc-label">Year</label>
      <select name="year" class="form-select form-select-sm">
        <?php for($y=date('Y');$y>=date('Y')-2;$y--): ?><option value="<?=$y?>" <?=$y===$year?'selected':''?>><?=$y?></option><?php endfor; ?>
      </select></div>
    <div><label class="pc-label">Department</label>
      <select name="dept" class="form-select form-select-sm" style="width:160px">
        <option value="">All</option>
        <?php foreach($depts as $d): ?><option value="<?=$d['id']?>" <?=$dept==$d['id']?'selected':''?>><?=clean($d['name'])?></option><?php endforeach; ?>
      </select></div>
    <button class="btn btn-pc btn-sm"><i class="ti ti-search me-1"></i>View</button>
    <a href="?month=<?=$month?>&year=<?=$year?>&dept=<?=$dept?>&format=csv" class="btn btn-sm btn-outline-success"><i class="ti ti-download me-1"></i>Export CSV</a>
    <button type="button" onclick="window.print()" class="btn btn-sm btn-outline-secondary"><i class="ti ti-printer me-1"></i>Print</button>
  </form>
</div>

<!-- Summary Stats -->
<?php if($employees && $summary): ?>
<div class="row g-2 mb-3">
  <?php
  $totP=$totA=$totLop=$totOt=0;
  foreach($summary as $s) { $totP+=$s['present_days']; $totA+=$s['absent_days']; $totLop+=$s['lop_days']; $totOt+=$s['ot_hours']; }
  foreach([["Total Present",$totP,'green'],["Total Absent",$totA,'red'],["Total LOP",$totLop,'amber'],["Total OT Hrs",$totOt,'brand']] as [$lbl,$val,$clr]):
  ?>
  <div class="col-md-3"><div class="pc-stat py-2">
    <div class="pc-stat-val" style="font-size:20px;color:var(--pc-<?=$clr?>)"><?=$val?></div>
    <div class="pc-stat-label"><?=$lbl?></div>
  </div></div>
  <?php endforeach; ?>
</div>
<?php endif; ?>

<!-- Muster Grid -->
<div class="pc-card" style="overflow:hidden">
  <div class="pc-card-title"><?=$months[$month]?> <?=$year?> Muster — <?=count($employees)?> Employees</div>
  <div class="pc-table-wrap" style="overflow-x:auto">
    <table style="border-collapse:collapse;font-size:11px;white-space:nowrap;width:100%">
      <thead>
        <tr style="background:#f5f8fc">
          <th style="padding:6px 8px;border:1px solid var(--pc-border);min-width:90px;position:sticky;left:0;background:#f5f8fc">Emp</th>
          <th style="padding:6px 8px;border:1px solid var(--pc-border);min-width:120px;position:sticky;left:90px;background:#f5f8fc">Name</th>
          <?php for($d=1;$d<=$daysInMonth;$d++):
            $ds   = sprintf('%04d-%02d-%02d',$year,$month,$d);
            $dow  = date('D',$date=mktime(0,0,0,$month,$d,$year));
            $isWE = in_array($dow,['Sat','Sun']);
          ?>
          <th style="padding:4px 3px;border:1px solid var(--pc-border);text-align:center;width:28px;background:<?=$isWE?'#eff6ff':'#f5f8fc'?>;color:<?=$isWE?'var(--pc-blue)':'var(--pc-text2)'?>">
            <div><?=$d?></div><div style="font-size:8px"><?=$dow?></div>
          </th>
          <?php endfor; ?>
          <th style="padding:6px 4px;border:1px solid var(--pc-border);text-align:center;background:#dcfce7;color:#166534">P</th>
          <th style="padding:6px 4px;border:1px solid var(--pc-border);text-align:center;background:#fee2e2;color:#991b1b">A</th>
          <th style="padding:6px 4px;border:1px solid var(--pc-border);text-align:center;background:#fef9c3;color:#854d0e">H</th>
          <th style="padding:6px 4px;border:1px solid var(--pc-border);text-align:center;background:#dbeafe;color:#1e40af">L</th>
          <th style="padding:6px 4px;border:1px solid var(--pc-border);text-align:center;background:#f3f4f6;color:#6b7280">WO</th>
          <th style="padding:6px 4px;border:1px solid var(--pc-border);text-align:center;background:#fde8d8;color:#9a3412">LOP</th>
          <th style="padding:6px 4px;border:1px solid var(--pc-border);text-align:center;background:var(--pc-brand-light);color:var(--pc-brand)">OT</th>
        </tr>
      </thead>
      <tbody>
      <?php foreach($employees as $e):
        $ms = $musterData[$e['id']] ?? [];
        $sm = $summary[$e['id']] ?? [];
      ?>
      <tr>
        <td style="padding:5px 8px;border:1px solid var(--pc-border);font-weight:600;position:sticky;left:0;background:#fff"><?=clean($e['emp_code'])?></td>
        <td style="padding:5px 8px;border:1px solid var(--pc-border);font-weight:600;position:sticky;left:90px;background:#fff"><?=clean($e['first_name'].' '.$e['last_name'])?></td>
        <?php for($d=1;$d<=$daysInMonth;$d++):
          $ds  = sprintf('%04d-%02d-%02d',$year,$month,$d);
          $st  = $ms[$ds] ?? null;
          $dow = date('D',mktime(0,0,0,$month,$d,$year));
          $isWE= in_array($dow,['Sat','Sun']);
          $bg  = $st ? ($statusColors[$st]??'#fff') : ($isWE?'#eff6ff':'#fff');
          $tx  = $st ? ($statusText[$st]??'#333') : '#ccc';
        ?>
        <td style="padding:3px;border:1px solid var(--pc-border);text-align:center;background:<?=$bg?>;color:<?=$tx?>;font-weight:<?=$st?'800':'400'?>;font-size:9px">
          <?=$st??''?>
        </td>
        <?php endfor; ?>
        <td style="padding:4px;border:1px solid var(--pc-border);text-align:center;font-weight:700;color:#166534"><?=$sm['present_days']??'—'?></td>
        <td style="padding:4px;border:1px solid var(--pc-border);text-align:center;font-weight:700;color:#991b1b"><?=$sm['absent_days']??'—'?></td>
        <td style="padding:4px;border:1px solid var(--pc-border);text-align:center;color:#854d0e"><?=$sm['half_days']??'—'?></td>
        <td style="padding:4px;border:1px solid var(--pc-border);text-align:center;color:#1e40af"><?=$sm['leave_days']??'—'?></td>
        <td style="padding:4px;border:1px solid var(--pc-border);text-align:center;color:#6b7280"><?=$sm['week_off_days']??'—'?></td>
        <td style="padding:4px;border:1px solid var(--pc-border);text-align:center;font-weight:700;color:#9a3412"><?=$sm['lop_days']??'—'?></td>
        <td style="padding:4px;border:1px solid var(--pc-border);text-align:center;color:var(--pc-brand)"><?=$sm['ot_hours']??'—'?></td>
      </tr>
      <?php endforeach; ?>
      <?php if(!$employees): ?>
      <tr><td colspan="<?=$daysInMonth+9?>" style="text-align:center;padding:20px;color:var(--pc-text3)">No employees found</td></tr>
      <?php endif; ?>
      </tbody>
    </table>
  </div>
</div>
<style>@media print{.pc-topbar,.pc-sidebar,.pc-page-header,.pc-card:first-child{display:none!important}body{font-size:9px}}</style>
<?php include __DIR__ . '/../../includes/footer.php'; ?>