<?php /* payroll/attendance.php */
$sym = setting('currency_symbol','Rs.');
$daysInMonth = cal_days_in_month(CAL_GREGORIAN,$month,$year);
$monthLabel  = date('F Y', mktime(0,0,0,$month,1,$year));

$statusCfg = [
  'present'  => ['P', 'bg-success',   'text-white', 'Present'],
  'absent'   => ['A', 'bg-danger',    'text-white', 'Absent'],
  'half_day' => ['H', 'bg-warning',   'text-dark',  'Half Day'],
  'late'     => ['L', 'bg-info',      'text-dark',  'Late'],
  'leave'    => ['LV','bg-primary',   'text-white', 'Leave'],
  'holiday'  => ['HO','bg-secondary', 'text-white', 'Holiday'],
  'off'      => ['—', 'bg-light',     'text-muted', 'Off'],
];
$methodIcon = ['fingerprint'=>'bi-fingerprint','manual'=>'bi-pencil','qr'=>'bi-qr-code','face'=>'bi-person-bounding-box','card'=>'bi-credit-card'];
?>
<style>
.att-cell{
  width:32px;height:32px;font-size:.62rem;font-weight:700;
  border-radius:4px;cursor:pointer;border:none;
  display:flex;align-items:center;justify-content:center;
}
.att-cell:hover{opacity:.8;transform:scale(1.1)}
.att-table th,.att-table td{padding:4px 6px;white-space:nowrap;vertical-align:middle}
.fp-card{border-radius:10px;border:2px solid #e2e8f0;padding:16px;background:#fff}
.fp-scanner{
  width:120px;height:120px;border-radius:50%;
  background:linear-gradient(135deg,#eff6ff,#dbeafe);
  border:3px solid #3b82f6;
  display:flex;align-items:center;justify-content:center;
  margin:0 auto;cursor:pointer;
  transition:all .2s;
}
.fp-scanner:hover{transform:scale(1.05);box-shadow:0 0 20px rgba(59,130,246,.3)}
.fp-scanner.scanning{animation:fpPulse 1s infinite}
@keyframes fpPulse{0%,100%{box-shadow:0 0 0 0 rgba(59,130,246,.4)}70%{box-shadow:0 0 0 15px rgba(59,130,246,0)}}
.fp-log-row{padding:6px 12px;border-bottom:1px solid #f1f5f9;font-size:.78rem}
.fp-log-row:last-child{border:none}
</style>

<!-- Header -->
<div class="d-flex justify-content-between align-items-start mb-3 flex-wrap gap-2">
  <div>
    <h5 class="fw-bold mb-1 d-flex align-items-center gap-2">
      <i class="bi bi-calendar-check text-primary fs-4"></i>
      Attendance Sheet
      <span class="badge bg-primary"><?= $monthLabel ?></span>
    </h5>
    <small class="text-muted">
      <?= count($employees) ?> employees &nbsp;·&nbsp;
      <?= $daysInMonth ?> days &nbsp;·&nbsp;
      <i class="bi bi-fingerprint text-success me-1"></i>Fingerprint integrated
    </small>
  </div>
  <div class="d-flex gap-2 flex-wrap">
    <a href="<?= APP_URL ?>/payroll" class="btn btn-sm btn-outline-secondary">
      <i class="bi bi-arrow-left me-1"></i>Payroll
    </a>
    <!-- Process fingerprint -->
    <form method="POST" action="<?= APP_URL ?>/attendance/fingerprint/process">
      <?= Auth::csrfField() ?>
      <button class="btn btn-sm btn-success fw-semibold">
        <i class="bi bi-fingerprint me-1"></i>Sync Fingerprint
        <?php
        try {
          $pending = (int)Database::fetchColumn("SELECT COUNT(*) FROM fingerprint_logs WHERE status='pending'");
        } catch(Exception $e) { $pending=0; }
        ?>
        <?php if($pending > 0):?>
        <span class="badge bg-warning text-dark ms-1"><?= $pending ?></span>
        <?php endif;?>
      </button>
    </form>
    <button class="btn btn-sm btn-outline-primary" onclick="window.print()">
      <i class="bi bi-printer me-1"></i>Print
    </button>
  </div>
</div>

<?= flashMessages() ?>

<!-- Month navigation + legend -->
<div class="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2">
  <!-- Month/Year selector -->
  <form method="GET" action="<?= APP_URL ?>/payroll/attendance" class="d-flex gap-2 align-items-end">
    <select name="month" class="form-select form-select-sm" style="width:130px">
      <?php for($m=1;$m<=12;$m++):?>
      <option value="<?=$m?>" <?=$m===$month?'selected':''?>>
        <?= date('F',mktime(0,0,0,$m,1)) ?>
      </option>
      <?php endfor;?>
    </select>
    <select name="year" class="form-select form-select-sm" style="width:90px">
      <?php for($y=date('Y')+1;$y>=date('Y')-2;$y--):?>
      <option value="<?=$y?>" <?=$y===$year?'selected':''?>><?=$y?></option>
      <?php endfor;?>
    </select>
    <button class="btn btn-secondary btn-sm">Go</button>
  </form>

  <!-- Legend -->
  <div class="d-flex gap-1 flex-wrap">
    <?php foreach($statusCfg as $key=>[$lbl,$bg,$txt,$full]):?>
    <span class="badge <?=$bg?> <?=$txt?>" style="font-size:.65rem">
      <?=$lbl?> = <?=$full?>
    </span>
    <?php endforeach;?>
  </div>
</div>

<div class="row g-3">
  <!-- Attendance Sheet Table -->
  <div class="col-lg-9">
    <div class="card">
      <div class="card-header bg-dark text-white fw-semibold small d-flex justify-content-between">
        <span><i class="bi bi-table me-1"></i>Attendance Register — <?= $monthLabel ?></span>
        <span class="badge bg-secondary"><?= count($employees) ?> employees</span>
      </div>
      <div style="overflow-x:auto">
        <table class="table table-sm att-table mb-0" style="min-width:900px">
          <thead>
            <tr class="table-dark">
              <th class="ps-2" style="min-width:160px">Employee</th>
              <?php for($d=1;$d<=$daysInMonth;$d++):
                $dow   = date('w', mktime(0,0,0,$month,$d,$year));
                $isWkd = ($dow === '0'); // Sunday
              ?>
              <th class="text-center <?=$isWkd?'table-danger opacity-50':''?>"
                  style="width:32px;font-size:.62rem">
                <div><?=$d?></div>
                <div style="font-size:.55rem;opacity:.7"><?=date('D',mktime(0,0,0,$month,$d,$year))[0]?></div>
              </th>
              <?php endfor;?>
              <th class="text-center" style="min-width:50px">P</th>
              <th class="text-center" style="min-width:50px">A</th>
              <th class="text-center" style="min-width:50px">L</th>
              <th class="text-center" style="min-width:50px">OT h</th>
              <th class="text-end" style="min-width:80px">FP</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach($employees as $emp):
              $empAtt    = $attMap[$emp['id']] ?? [];
              $pCount    = 0; $aCount = 0; $lCount = 0; $otHrs = 0; $fpCount = 0;
              for($d=1;$d<=$daysInMonth;$d++) {
                $rec = $empAtt[$d] ?? null;
                if($rec) {
                  if($rec['status']==='present'||$rec['status']==='late') $pCount++;
                  if($rec['status']==='absent') $aCount++;
                  if($rec['status']==='leave'||$rec['status']==='half_day') $lCount++;
                  $otHrs += (float)($rec['ot_hours']??0);
                  if($rec['method']==='fingerprint') $fpCount++;
                }
              }
            ?>
            <tr>
              <td class="ps-2">
                <div class="fw-semibold" style="font-size:.78rem"><?= e($emp['full_name']) ?></div>
                <div class="d-flex align-items-center gap-1">
                  <code style="font-size:.6rem;color:#94a3b8"><?= e($emp['emp_code']) ?></code>
                  <?php if($emp['fingerprint_id']):?>
                  <span class="badge bg-success" style="font-size:.5rem">
                    <i class="bi bi-fingerprint"></i> <?= e($emp['fingerprint_id']) ?>
                  </span>
                  <?php endif;?>
                </div>
              </td>
              <?php for($d=1;$d<=$daysInMonth;$d++):
                $rec    = $empAtt[$d] ?? null;
                $dow    = date('w', mktime(0,0,0,$month,$d,$year));
                $isWkd  = ($dow === '0');
                $st     = $rec ? $rec['status'] : ($isWkd ? 'off' : null);
                $cfg    = $st ? ($statusCfg[$st] ?? $statusCfg['absent']) : ['?','bg-light','text-muted',''];
                $mIcon  = $rec ? ($methodIcon[$rec['method']]??'bi-dot') : '';
                $tip    = $rec
                  ? "{$cfg[3]}" . ($rec['check_in']?" | In:{$rec['check_in']}":'') . ($rec['check_out']?" | Out:{$rec['check_out']}":'') . ($rec['ot_hours']>0?" | OT:{$rec['ot_hours']}h":'')
                  : 'No record';
              ?>
              <td class="text-center p-0 <?=$isWkd?'bg-danger bg-opacity-10':''?>"
                  style="width:32px">
                <?php if($rec||$st):?>
                <button class="att-cell <?=$cfg[1]?> <?=$cfg[2]?>"
                        title="<?=$tip?>"
                        onclick="openAttModal(<?=$emp['id']?>,<?=$d?>,<?=$month?>,<?=$year?>,'<?=$st?>')">
                  <?php if($mIcon && $st==='present'):?>
                  <i class="bi <?=$mIcon?>" style="font-size:.6rem"></i>
                  <?php else:?>
                  <?=$cfg[0]?>
                  <?php endif;?>
                </button>
                <?php else:?>
                <button class="att-cell bg-light text-muted"
                        title="Click to add"
                        onclick="openAttModal(<?=$emp['id']?>,<?=$d?>,<?=$month?>,<?=$year?>,'present')">
                  <i class="bi bi-plus" style="font-size:.6rem"></i>
                </button>
                <?php endif;?>
              </td>
              <?php endfor;?>
              <!-- Summary -->
              <td class="text-center fw-bold text-success"><?=$pCount?></td>
              <td class="text-center fw-bold text-danger"><?=$aCount?></td>
              <td class="text-center fw-bold text-primary"><?=$lCount?></td>
              <td class="text-center <?=$otHrs>0?'text-warning fw-bold':''?>"><?=$otHrs>0?number_format($otHrs,1):'—'?></td>
              <td class="text-end">
                <?php if($emp['fingerprint_id']):?>
                <span class="badge bg-success" style="font-size:.6rem">
                  <i class="bi bi-fingerprint me-1"></i><?=$fpCount?>
                </span>
                <?php else:?>
                <span class="badge bg-secondary" style="font-size:.6rem">Manual</span>
                <?php endif;?>
              </td>
            </tr>
            <?php endforeach;?>
          </tbody>
          <!-- Footer totals -->
          <tfoot class="table-secondary fw-bold" style="font-size:.75rem">
            <tr>
              <td class="ps-2">TOTAL</td>
              <?php for($d=1;$d<=$daysInMonth;$d++):
                $cnt=0;
                foreach($employees as $emp) {
                  $rec=$attMap[$emp['id']][$d]??null;
                  if($rec && in_array($rec['status'],['present','late'])) $cnt++;
                }
                $dow=date('w',mktime(0,0,0,$month,$d,$year));
              ?>
              <td class="text-center <?=$dow==='0'?'bg-danger bg-opacity-10':''?>"
                  style="font-size:.6rem;color:<?=$cnt===count($employees)?'#16a34a':($cnt===0?'#dc2626':'#d97706')?>">
                <?=$cnt?>
              </td>
              <?php endfor;?>
              <td colspan="5"></td>
            </tr>
          </tfoot>
        </table>
      </div>
    </div>
  </div>

  <!-- Right panel: Fingerprint Scanner -->
  <div class="col-lg-3">

    <!-- Fingerprint Live Scanner -->
    <div class="fp-card mb-3">
      <div class="fw-bold small mb-3 text-center">
        <i class="bi bi-fingerprint text-success me-1 fs-5"></i>Fingerprint Terminal
      </div>

      <div class="fp-scanner mb-3" id="fpScanner" onclick="startFpScan()">
        <div class="text-center">
          <i class="bi bi-fingerprint" style="font-size:2.5rem;color:#3b82f6" id="fpIcon"></i>
          <div style="font-size:.65rem;color:#64748b;margin-top:4px" id="fpPrompt">Touch to Scan</div>
        </div>
      </div>

      <!-- Manual FP ID entry -->
      <div class="mb-2">
        <label class="form-label small fw-semibold">Fingerprint ID</label>
        <div class="input-group input-group-sm">
          <span class="input-group-text"><i class="bi bi-fingerprint"></i></span>
          <input type="text" id="fpIdInput" class="form-control"
                 placeholder="FP001" autocomplete="off">
        </div>
      </div>
      <div class="d-flex gap-2 mb-3">
        <button class="btn btn-success btn-sm flex-fill fw-semibold"
                onclick="recordPunch('in')">
          <i class="bi bi-box-arrow-in-right me-1"></i>Check In
        </button>
        <button class="btn btn-danger btn-sm flex-fill fw-semibold"
                onclick="recordPunch('out')">
          <i class="bi bi-box-arrow-right me-1"></i>Check Out
        </button>
      </div>

      <!-- Result display -->
      <div id="fpResult" class="rounded p-2 text-center small" style="display:none;min-height:50px"></div>
    </div>

    <!-- Recent FP Logs -->
    <div class="card">
      <div class="card-header fw-semibold small bg-transparent d-flex justify-content-between">
        <span><i class="bi bi-clock-history me-1"></i>Recent Punches</span>
        <span class="badge <?=$pending>0?'bg-warning text-dark':'bg-success'?>">
          <?=$pending?> pending
        </span>
      </div>
      <div style="max-height:300px;overflow-y:auto">
        <?php foreach($fpLogs as $log):
          $stCls=['processed'=>'text-success','pending'=>'text-warning','error'=>'text-danger'][$log['status']]??'';
          $typeIcon=$log['punch_type']==='in'?'bi-box-arrow-in-right text-success':'bi-box-arrow-right text-danger';
        ?>
        <div class="fp-log-row">
          <div class="d-flex justify-content-between align-items-center">
            <div>
              <i class="bi <?=$typeIcon?> me-1"></i>
              <span class="fw-semibold"><?= $log['full_name'] ? e($log['full_name']) : '<span class="text-danger">Unknown</span>' ?></span>
            </div>
            <span class="<?=$stCls?>" style="font-size:.65rem"><?=ucfirst($log['status'])?></span>
          </div>
          <div class="text-muted" style="font-size:.65rem">
            <i class="bi bi-fingerprint me-1"></i><?=e($log['device_user_id'])?>
            &nbsp;·&nbsp; <?=date('d M H:i',strtotime($log['punch_time']))?>
          </div>
          <?php if($log['error_msg']):?>
          <div class="text-danger" style="font-size:.62rem"><?=e($log['error_msg'])?></div>
          <?php endif;?>
        </div>
        <?php endforeach;?>
        <?php if(empty($fpLogs)):?>
        <div class="text-center text-muted py-3 small">No recent fingerprint logs</div>
        <?php endif;?>
      </div>
    </div>
  </div>
</div>

<!-- ── Attendance Edit Modal ───────────────────────────────── -->
<div class="modal fade" id="attModal" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered" style="max-width:420px">
    <div class="modal-content">
      <div class="modal-header bg-dark text-white">
        <h6 class="modal-title fw-bold" id="attModalTitle">Edit Attendance</h6>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <form method="POST" action="<?= APP_URL ?>/attendance/save">
        <?= Auth::csrfField() ?>
        <input type="hidden" name="employee_id" id="att_emp_id">
        <input type="hidden" name="att_date" id="att_date">
        <div class="modal-body">
          <div class="mb-3">
            <label class="form-label small fw-semibold">Status</label>
            <div class="d-flex gap-2 flex-wrap">
              <?php foreach($statusCfg as $key=>[$lbl,$bg,$txt,$full]):
                if($key==='off') continue;
              ?>
              <div class="form-check">
                <input type="radio" name="status" value="<?=$key?>"
                       id="st_<?=$key?>" class="form-check-input">
                <label class="form-check-label" for="st_<?=$key?>">
                  <span class="badge <?=$bg?> <?=$txt?>"><?=$full?></span>
                </label>
              </div>
              <?php endforeach;?>
            </div>
          </div>
          <div class="row g-2 mb-3">
            <div class="col-6">
              <label class="form-label small fw-semibold">Check In</label>
              <input type="time" name="check_in" id="att_check_in"
                     class="form-control form-control-sm">
            </div>
            <div class="col-6">
              <label class="form-label small fw-semibold">Check Out</label>
              <input type="time" name="check_out" id="att_check_out"
                     class="form-control form-control-sm">
            </div>
          </div>
          <div class="mb-3">
            <label class="form-label small fw-semibold">Method</label>
            <select name="method" class="form-select form-select-sm">
              <option value="manual">Manual Entry</option>
              <option value="fingerprint">Fingerprint</option>
              <option value="qr">QR Code</option>
              <option value="card">Card</option>
            </select>
          </div>
          <div>
            <label class="form-label small fw-semibold">Note</label>
            <input type="text" name="note" class="form-control form-control-sm"
                   placeholder="Optional note…">
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Cancel</button>
          <button type="submit" class="btn btn-primary btn-sm fw-semibold">
            <i class="bi bi-check-circle me-1"></i>Save
          </button>
        </div>
      </form>
    </div>
  </div>
</div>

<script>
const APP_URL = '<?= APP_URL ?>';
const CSRF    = '<?= Auth::csrfToken() ?>';

// Open attendance modal
function openAttModal(empId, day, month, year, currentStatus) {
  const d    = String(day).padStart(2,'0');
  const m    = String(month).padStart(2,'0');
  const date = `${year}-${m}-${d}`;

  document.getElementById('att_emp_id').value = empId;
  document.getElementById('att_date').value   = date;

  // Set radio
  const radio = document.querySelector(`input[name="status"][value="${currentStatus}"]`);
  if (radio) radio.checked = true;

  document.getElementById('attModalTitle').textContent =
    `Attendance — ${date}`;
  new bootstrap.Modal(document.getElementById('attModal')).show();
}

// Fingerprint scanner simulation
let fpTimer = null;
function startFpScan() {
  const fpId = document.getElementById('fpIdInput').value.trim();
  if (fpId) { recordPunch('in'); return; }

  const scanner  = document.getElementById('fpScanner');
  const icon     = document.getElementById('fpIcon');
  const prompt   = document.getElementById('fpPrompt');
  scanner.classList.add('scanning');
  icon.style.color  = '#16a34a';
  prompt.textContent = 'Scanning…';

  clearTimeout(fpTimer);
  fpTimer = setTimeout(() => {
    scanner.classList.remove('scanning');
    icon.style.color  = '#3b82f6';
    prompt.textContent = 'Touch to Scan';
    showFpResult('warning','No fingerprint detected. Enter ID manually.');
  }, 3000);
}

async function recordPunch(type) {
  const fpId = document.getElementById('fpIdInput').value.trim();
  if (!fpId) {
    showFpResult('danger','Please enter a Fingerprint ID.');
    return;
  }

  const now = new Date();
  const punchTime = now.getFullYear()+'-'+
    String(now.getMonth()+1).padStart(2,'0')+'-'+
    String(now.getDate()).padStart(2,'0')+' '+
    String(now.getHours()).padStart(2,'0')+':'+
    String(now.getMinutes()).padStart(2,'0')+':'+
    String(now.getSeconds()).padStart(2,'0');

  const body = new URLSearchParams({
    csrf_token: CSRF,
    fingerprint_id: fpId,
    punch_type: type,
    punch_time: punchTime
  });

  try {
    const res  = await fetch(APP_URL+'/attendance/fingerprint/punch', {method:'POST',body});
    const data = await res.json();
    if (data.success) {
      showFpResult('success',
        `<i class="bi bi-check-circle me-1"></i>
         <strong>${data.employee}</strong><br>
         ${type==='in'?'✅ Checked In':'🔴 Checked Out'}<br>
         <small class="text-muted">${punchTime}</small>`);
      document.getElementById('fpIdInput').value = '';
      // Add to log list
      setTimeout(() => location.reload(), 2000);
    } else {
      showFpResult('danger', data.message);
    }
  } catch(e) {
    showFpResult('danger', 'Connection error.');
  }
}

function showFpResult(type, msg) {
  const el = document.getElementById('fpResult');
  const bg = {success:'#f0fdf4',danger:'#fef2f2',warning:'#fffbeb'}[type]||'#f8fafc';
  const tc = {success:'#16a34a',danger:'#dc2626',warning:'#d97706'}[type]||'#374151';
  el.style.display   = 'block';
  el.style.background = bg;
  el.style.color      = tc;
  el.style.border     = `1px solid ${tc}40`;
  el.innerHTML        = msg;
}

// Auto-set check_in to 08:00 for present status
document.querySelectorAll('input[name="status"]').forEach(r => {
  r.addEventListener('change', function() {
    const ci = document.getElementById('att_check_in');
    const co = document.getElementById('att_check_out');
    if (this.value === 'present' && !ci.value) {
      ci.value = '08:00'; co.value = '17:00';
    } else if (this.value === 'absent' || this.value === 'off') {
      ci.value = ''; co.value = '';
    } else if (this.value === 'half_day' && !ci.value) {
      ci.value = '08:00'; co.value = '13:00';
    } else if (this.value === 'late' && !ci.value) {
      ci.value = '09:15'; co.value = '17:00';
    }
  });
});
</script>