<?php
require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../includes/functions.php';
startSession(); requireLogin();
$db = Database::getInstance();
$page = 'My Attendance';
$user = currentUser();
$empId = $user['emp_id'];

$month = intval($_GET['month'] ?? date('n'));
$year  = intval($_GET['year']  ?? date('Y'));
$selEmpId = cleanInt($_GET['emp'] ?? ($empId ?: 0));
// FIX (07 Jul 2026): scope to org, and don't allow ?emp=<id> to view
// another organization's employee attendance/leave balance.
[$orgClause, $orgParams] = orgScopeClause($db, 'company_id');
$employees = $db->fetchAll("SELECT id, CONCAT(employee_id,' - ',first_name,' ',last_name) AS label FROM employees WHERE status='active' AND $orgClause ORDER BY first_name", $orgParams);
if ($selEmpId && !in_array($selEmpId, array_column($employees, 'id'))) { $selEmpId = 0; }

$muster = [];
if($selEmpId) {
    $rows = $db->fetchAll("SELECT * FROM muster WHERE employee_id=? AND MONTH(muster_date)=? AND YEAR(muster_date)=? ORDER BY muster_date", [$selEmpId,$month,$year]);
    foreach($rows as $r) $muster[$r['muster_date']] = $r;
}

$summary = $selEmpId ? $db->fetchOne("SELECT * FROM muster_summary WHERE employee_id=? AND month=? AND year=?", [$selEmpId,$month,$year]) : null;
$leaveBalance = $selEmpId ? $db->fetchAll("SELECT lb.*,lt.name AS leave_name,lt.code FROM employee_leave_balance lb JOIN leave_types lt ON lt.id=lb.leave_type_id WHERE lb.employee_id=? AND lb.year=?", [$selEmpId,$year]) : [];

$daysInMonth = date('t', mktime(0,0,0,$month,1,$year));
$firstDay    = date('N', mktime(0,0,0,$month,1,$year)); // 1=Mon

include __DIR__ . '/../../includes/header.php';
?>
<!-- Filters -->
<div class="pc-card mb-3">
  <form method="GET" class="d-flex gap-2 align-items-end flex-wrap">
    <div><label class="pc-label">Employee</label>
      <select name="emp" class="form-select form-select-sm" style="width:250px">
        <option value="">Select Employee</option>
        <?php foreach($employees as $e): ?><option value="<?=$e['id']?>" <?=$selEmpId==$e['id']?'selected':''?>><?=clean($e['label'])?></option><?php endforeach; ?>
      </select></div>
    <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?>" <?=$month==$m?'selected':''?>><?=date('F',mktime(0,0,0,$m,1))?></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')-3;$y--): ?><option value="<?=$y?>" <?=$year==$y?'selected':''?>><?=$y?></option><?php endfor; ?></select></div>
    <button class="btn btn-pc btn-sm"><i class="ti ti-search me-1"></i>View</button>
  </form>
</div>

<?php if($selEmpId): ?>
<!-- Summary cards -->
<div class="row g-3 mb-3">
  <?php $stats=[['Present','P',$summary['present_days']??0,'green','ti-check'],['On Duty','OD',$summary['od_days']??0,'purple','ti-briefcase'],['Absent','A',$summary['absent_days']??0,'red','ti-x'],['Leave','L',$summary['leave_days']??0,'blue','ti-calendar'],['LOP','LOP',$summary['lop_days']??0,'amber','ti-alert'],['OT Hrs','OT',number_format($summary['ot_hours']??0,1),'purple','ti-clock'],['Late','',$summary['late_count']??0,'red','ti-clock-exclamation']];
  foreach($stats as [$label,$code,$val,$color,$icon]): ?>
  <div class="col-6 col-md-2">
    <div class="pc-stat d-flex align-items-center gap-2">
      <div class="pc-stat-icon <?=$color?>" style="width:36px;height:36px;font-size:16px"><i class="ti <?=$icon?>"></i></div>
      <div><div class="pc-stat-val" style="font-size:18px"><?=$val?></div><div class="pc-stat-label" <?=$label==='Present'?'title="Includes On Duty days"':''?>><?=$label?></div></div>
    </div>
  </div>
  <?php endforeach; ?>
</div>

<!-- Calendar -->
<div class="row g-3">
  <div class="col-lg-8">
    <div class="pc-card">
      <div class="pc-card-title"><?=date('F Y',mktime(0,0,0,$month,1,$year))?> — Attendance Calendar</div>
      <div style="display:grid;grid-template-columns:repeat(7,1fr);gap:4px;margin-bottom:8px">
        <?php foreach(['Mon','Tue','Wed','Thu','Fri','Sat','Sun'] as $d): ?>
        <div style="text-align:center;font-size:10px;font-weight:700;color:var(--pc-text2);padding:4px"><?=$d?></div>
        <?php endforeach; ?>
        <!-- Empty cells -->
        <?php for($i=1;$i<$firstDay;$i++): ?><div></div><?php endfor; ?>
        <?php for($d=1;$d<=$daysInMonth;$d++):
          $dateStr = sprintf('%04d-%02d-%02d',$year,$month,$d);
          $m = $muster[$dateStr] ?? null;
          $status = $m['status'] ?? (date('Y-m-d')>$dateStr?'A':'future');
          $isToday = $dateStr===date('Y-m-d');
          $colorMap=['P'=>'#dcfce7','A'=>'#fee2e2','H'=>'#fef9c3','L'=>'#dbeafe','WO'=>'#f3f4f6','PH'=>'#e0f2fe','LOP'=>'#fde8d8','CO'=>'#ede9fe','OD'=>'#ede9fe','future'=>'#fff'];
          $textMap=['P'=>'#166534','A'=>'#991b1b','H'=>'#854d0e','L'=>'#1e40af','WO'=>'#6b7280','PH'=>'#0c4a6e','LOP'=>'#9a3412','CO'=>'#5b21b6','OD'=>'#6d28d9','future'=>'#9ca3af'];
        ?>
        <div style="background:<?=$colorMap[$status]??'#fff'?>;color:<?=$textMap[$status]??'#333'?>;border-radius:6px;padding:6px 4px;text-align:center;font-size:11px;border:<?=$isToday?'2px solid var(--pc-brand)':'1px solid #e5e7eb'?>"
          title="<?=$dateStr.($m?' | In: '.($m['in_time']??'—').' Out: '.($m['out_time']??'—'):'')?>">
          <div style="font-weight:700"><?=$d?></div>
          <div style="font-size:9px;font-weight:800"><?=$status==='future'?'':$status?></div>
          <?php if($m && $m['in_time']): ?><div style="font-size:8px"><?=substr($m['in_time'],0,5)?></div><?php endif; ?>
        </div>
        <?php endfor; ?>
      </div>
      <!-- Legend -->
      <div class="d-flex flex-wrap gap-2 mt-2">
        <?php foreach(['P'=>['Present','#dcfce7','#166534'],'A'=>['Absent','#fee2e2','#991b1b'],'H'=>['Half Day','#fef9c3','#854d0e'],'L'=>['Leave','#dbeafe','#1e40af'],'WO'=>['Week Off','#f3f4f6','#6b7280'],'PH'=>['Holiday','#e0f2fe','#0c4a6e'],'OD'=>['On Duty','#ede9fe','#6d28d9']] as $code=>[$label,$bg,$tc]): ?>
        <div class="d-flex align-items-center gap-1" style="font-size:10px">
          <div style="width:14px;height:14px;background:<?=$bg?>;border-radius:3px;border:1px solid #e5e7eb"></div>
          <span style="color:<?=$tc?>"><?=$label?></span>
        </div>
        <?php endforeach; ?>
      </div>
    </div>
  </div>
  <div class="col-lg-4">
    <div class="pc-card mb-3">
      <div class="pc-card-title">Leave Balance <?=$year?></div>
      <?php foreach($leaveBalance as $lb):
        $remaining = $lb['allocated'] - $lb['used'];
        $pct = $lb['allocated'] > 0 ? round(($remaining/$lb['allocated'])*100) : 0;
      ?>
      <div class="mb-3">
        <div class="d-flex justify-content-between mb-1" style="font-size:12px">
          <span class="fw-semibold"><?=clean($lb['leave_name'])?> <span class="text-muted">(<?=clean($lb['code'])?>)</span></span>
          <span class="fw-bold" style="color:var(--pc-brand)"><?=$remaining?>/<?=$lb['allocated']?></span>
        </div>
        <div class="pc-progress"><div class="pc-progress-fill" style="width:<?=$pct?>%"></div></div>
        <div class="d-flex justify-content-between mt-1" style="font-size:10px;color:var(--pc-text3)">
          <span>Used: <?=$lb['used']?></span><span>CF: <?=$lb['carry_forward']??0?></span>
        </div>
      </div>
      <?php endforeach; if(!$leaveBalance): ?><div class="text-muted text-center small">No balance data</div><?php endif; ?>
    </div>
    <!-- Recent attendance log -->
    <div class="pc-card">
      <div class="pc-card-title">Recent Punch Log</div>
      <?php
      $logs = $selEmpId ? $db->fetchAll("SELECT * FROM attendance_log WHERE employee_id=? ORDER BY log_date DESC, in_time DESC LIMIT 10", [$selEmpId]) : [];
      foreach($logs as $log): ?>
      <div class="d-flex justify-content-between py-1 border-bottom" style="font-size:12px">
        <span><?=date('d M',strtotime($log['log_date']))?></span>
        <span class="text-muted">In: <?=substr($log['in_time']??'—',11,5)?></span>
        <span class="text-muted">Out: <?=substr($log['out_time']??'—',11,5)?></span>
        <span class="badge" style="font-size:9px;background:var(--pc-brand-light);color:var(--pc-brand)"><?=ucfirst($log['source'])?></span>
      </div>
      <?php endforeach; if(!$logs): ?><div class="text-muted text-center small py-2">No punch records</div><?php endif; ?>
    </div>
  </div>
</div>
<?php endif; ?>
<?php include __DIR__ . '/../../includes/footer.php'; ?>