<?php
$page_title = 'My Attendance';
require_once __DIR__ . '/header.php';

$month = $_GET['month'] ?? date('Y-m');
$attendances = $db->query("SELECT * FROM emp_attendance WHERE employee_id={$emp_id} AND DATE_FORMAT(date, '%Y-%m') = '{$month}' ORDER BY date DESC")->fetchAll();
?>

<div class="card">
  <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px;">
    <div>
      <h3 style="margin:0;color:#0f172a;">Attendance Log</h3>
      <p style="margin:4px 0 0;font-size:.85rem;color:#64748b;">Showing records for <?= date('F Y', strtotime($month.'-01')) ?></p>
    </div>
    <form method="GET" style="display:flex;gap:10px;">
      <input type="month" name="month" value="<?= h($month) ?>" style="padding:8px;border:1px solid #cbd5e1;border-radius:6px;outline:none;">
      <button type="submit" class="btn-logout" style="background:#2557d6;color:#fff;border:none;">View</button>
    </form>
  </div>
  
  <div class="table-wrap" style="margin-top:0;">
    <table>
      <thead>
        <tr>
          <th>Date</th>
          <th>Check In</th>
          <th>Check Out</th>
          <th>Status</th>
          <th>Working Hours</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach($attendances as $a): ?>
        <?php 
          $in = $a['check_in'] ? strtotime($a['check_in']) : 0;
          $out = $a['check_out'] ? strtotime($a['check_out']) : 0;
          $hrs = ($in && $out) ? round(($out - $in)/3600, 1) : '-';
          
          $c = 'success';
          if($a['status']==='Absent') $c='danger';
          if($a['status']==='Half Day' || $a['status']==='Late') $c='warning';
        ?>
        <tr>
          <td><strong><?= date('D, d M', strtotime($a['date'])) ?></strong></td>
          <td><?= $in ? date('h:i A', $in) : '-' ?></td>
          <td><?= $out ? date('h:i A', $out) : '-' ?></td>
          <td><span class="badge badge-<?= $c ?>" style="padding:4px 8px;border-radius:4px;font-size:.75rem;"><?= h($a['status']) ?></span></td>
          <td style="color:#475569;font-weight:600;"><?= $hrs !== '-' ? $hrs.' hrs' : '-' ?></td>
        </tr>
        <?php endforeach; ?>
        <?php if(!$attendances): ?>
        <tr><td colspan="5" style="text-align:center;padding:30px;color:#64748b;">No attendance records found for this month.</td></tr>
        <?php endif; ?>
      </tbody>
    </table>
  </div>
</div>

<?php require_once __DIR__ . '/footer.php'; ?>
