<?php /* reports/daily_attendance.php */
$sym  = setting('currency_symbol','Rs.');
$stColors = ['present'=>'#16a34a','late'=>'#d97706','absent'=>'#dc2626',
             'half_day'=>'#0891b2','leave'=>'#7c3aed','off'=>'#94a3b8'];
$stBadge  = ['present'=>'bg-success','late'=>'bg-warning text-dark','absent'=>'bg-danger',
             'half_day'=>'bg-info text-dark','leave'=>'bg-primary','off'=>'bg-secondary'];
$stLabel  = ['present'=>'Present','late'=>'Late','absent'=>'Absent',
             'half_day'=>'Half Day','leave'=>'Leave','off'=>'Off'];
$methIcon = ['fingerprint'=>'bi-fingerprint','manual'=>'bi-pencil-square',
             'qr'=>'bi-qr-code','card'=>'bi-credit-card','face'=>'bi-person-bounding-box'];
$methColor= ['fingerprint'=>'#16a34a','manual'=>'#94a3b8',
             'qr'=>'#3b82f6','card'=>'#7c3aed','face'=>'#d97706'];

$totalIn  = $attSummary['present'] + $attSummary['late'] + $attSummary['half_day'];
$attPct   = $attSummary['total_employees'] > 0
          ? round($totalIn / $attSummary['total_employees'] * 100) : 0;
$pctColor = $attPct >= 90 ? '#16a34a' : ($attPct >= 75 ? '#d97706' : '#dc2626');
?>

<style>
.att-hero{background:linear-gradient(135deg,#0f2557,#1e40af 60%,#0891b2);
  border-radius:14px;padding:22px 28px;color:#fff;margin-bottom:20px}
.kpi-pill{border-radius:12px;padding:14px 16px;text-align:center;border:none;height:100%}
.kpi-pill .val{font-size:1.6rem;font-weight:900;line-height:1}
.kpi-pill .lbl{font-size:.65rem;text-transform:uppercase;letter-spacing:.06em;opacity:.8;margin-top:3px}
.att-row td{padding:6px 10px;border-bottom:1px solid #f1f5f9;vertical-align:middle}
.att-row:hover td{background:#f8fafc}
.emp-init{width:32px;height:32px;border-radius:50%;display:flex;align-items:center;
  justify-content:center;font-size:.65rem;font-weight:700;flex-shrink:0}
.dept-tag{display:inline-block;padding:1px 7px;border-radius:12px;font-size:.62rem;font-weight:700}
.timeline-dot{width:10px;height:10px;border-radius:50%;flex-shrink:0}
.section-title{font-size:.8rem;font-weight:800;text-transform:uppercase;
  letter-spacing:.06em;color:#64748b;margin-bottom:10px;
  padding-bottom:6px;border-bottom:2px solid #f1f5f9}
@media print{
  .no-print{display:none!important}
  .att-hero{background:#1e40af!important;-webkit-print-color-adjust:exact;print-color-adjust:exact}
  .kpi-pill{-webkit-print-color-adjust:exact;print-color-adjust:exact}
  body{font-size:11px}
  .table{font-size:11px}
}
</style>

<!-- ── Hero ────────────────────────────────────────────────── -->
<div class="att-hero">
  <div class="d-flex justify-content-between align-items-start flex-wrap gap-2">
    <div>
      <h4 class="fw-bold mb-1">
        <i class="bi bi-calendar-check me-2"></i>Daily Attendance Report
      </h4>
      <div style="opacity:.8;font-size:.85rem">
        <?= date('l, d F Y', strtotime($date)) ?>
        &nbsp;·&nbsp; <?= $attSummary['total_employees'] ?> Active Employees
        &nbsp;·&nbsp; <i class="bi bi-fingerprint me-1"></i><?= $attSummary['fp_count'] ?> FP Records
      </div>
    </div>
    <div class="d-flex gap-2 flex-wrap no-print">
      <!-- Date nav -->
      <a href="?date=<?= date('Y-m-d',strtotime($date.' -1 day')) ?>"
         class="btn btn-outline-light btn-sm"><i class="bi bi-chevron-left"></i></a>
      <form method="GET" class="d-flex gap-1 align-items-center">
        <input type="date" name="date" value="<?= $date ?>"
               class="form-control form-control-sm" style="width:145px"
               onchange="this.form.submit()">
      </form>
      <a href="?date=<?= date('Y-m-d',strtotime($date.' +1 day')) ?>"
         class="btn btn-outline-light btn-sm"><i class="bi bi-chevron-right"></i></a>
      <a href="?date=<?= date('Y-m-d') ?>" class="btn btn-outline-light btn-sm">Today</a>
      <button onclick="window.print()" class="btn btn-light btn-sm fw-semibold" style="color:#1d4ed8">
        <i class="bi bi-printer me-1"></i>Print
      </button>
    </div>
  </div>
</div>

<!-- ── KPI Pills ────────────────────────────────────────────── -->
<div class="row g-2 mb-4">
  <?php foreach([
    [$attSummary['present'],  'Present',   '#dcfce7','#16a34a'],
    [$attSummary['absent'],   'Absent',    '#fee2e2','#dc2626'],
    [$attSummary['late'],     'Late',      '#fef9c3','#d97706'],
    [$attSummary['half_day'],'Half Day',  '#dbeafe','#0891b2'],
    [$attSummary['leave_days'],'Leave',   '#ede9fe','#7c3aed'],
    [$attSummary['total_employees']-$attSummary['total_marked'],'Not Marked','#f1f5f9','#64748b'],
  ] as[$val,$lbl,$bg,$clr]):?>
  <div class="col-6 col-md-2">
    <div class="kpi-pill" style="background:<?=$bg?>;border:2px solid <?=$clr?>33">
      <div class="val" style="color:<?=$clr?>"><?=$val?></div>
      <div class="lbl" style="color:<?=$clr?>"><?=$lbl?></div>
    </div>
  </div>
  <?php endforeach;?>
</div>

<div class="row g-3 mb-4">

  <!-- Attendance Rate Gauge -->
  <div class="col-md-3">
    <div class="card h-100">
      <div class="card-body text-center d-flex flex-column justify-content-center">
        <div style="font-size:3rem;font-weight:900;color:<?=$pctColor?>;line-height:1">
          <?= $attPct ?>%
        </div>
        <div class="text-muted small mb-2">Attendance Rate</div>
        <div style="height:12px;background:#f1f5f9;border-radius:6px">
          <div style="height:12px;border-radius:6px;width:<?=$attPct?>%;background:<?=$pctColor?>;transition:width .5s"></div>
        </div>
        <div class="mt-2 small">
          <span class="fw-bold"><?=$totalIn?></span>
          <span class="text-muted"> of <?=$attSummary['total_employees']?> in</span>
        </div>
        <div class="d-flex justify-content-center gap-3 mt-2 small">
          <span style="color:#d97706"><i class="bi bi-clock me-1"></i><?=number_format($attSummary['total_ot'],1)?>h OT</span>
          <span class="text-muted"><i class="bi bi-hourglass me-1"></i><?=number_format($attSummary['total_worked'],1)?>h</span>
        </div>
      </div>
    </div>
  </div>

  <!-- Status doughnut chart -->
  <div class="col-md-3">
    <div class="card h-100">
      <div class="card-body">
        <div class="section-title">Status Breakdown</div>
        <canvas id="statusChart" height="180"></canvas>
      </div>
    </div>
  </div>

  <!-- Method breakdown -->
  <div class="col-md-3">
    <div class="card h-100">
      <div class="card-body">
        <div class="section-title">Check-in Method</div>
        <canvas id="methodChart" height="180"></canvas>
      </div>
    </div>
  </div>

  <!-- Department summary -->
  <div class="col-md-3">
    <div class="card h-100">
      <div class="card-body">
        <div class="section-title">By Department</div>
        <?php foreach($deptSummary as $dept):
          $dp = $dept['total']>0?round($dept['present']/$dept['total']*100):0;
          $dc = $dp>=90?'#16a34a':($dp>=70?'#d97706':'#dc2626');
        ?>
        <div class="mb-2">
          <div class="d-flex justify-content-between align-items-center mb-1">
            <span style="font-size:.72rem;font-weight:600"><?=e($dept['department']??'—')?></span>
            <span style="font-size:.68rem;color:<?=$dc?>;font-weight:700"><?=$dept['present']?>/<?=$dept['total']?></span>
          </div>
          <div style="height:6px;background:#f1f5f9;border-radius:3px">
            <div style="height:6px;border-radius:3px;width:<?=$dp?>%;background:<?=$dc?>"></div>
          </div>
        </div>
        <?php endforeach;?>
      </div>
    </div>
  </div>

</div>

<!-- ── Employee Detail Table ────────────────────────────────── -->
<div class="card">
  <div class="card-header bg-dark text-white d-flex justify-content-between align-items-center">
    <span class="fw-semibold small">
      <i class="bi bi-people me-1"></i>Employee Attendance Detail
    </span>
    <div class="d-flex gap-2 no-print">
      <input type="text" id="empSearch" class="form-control form-control-sm"
             placeholder="Search employee…" style="width:180px"
             onkeyup="filterTable()">
      <select id="deptFilter" class="form-select form-select-sm" style="width:140px"
              onchange="filterTable()">
        <option value="">All Departments</option>
        <?php foreach($deptSummary as $d):?>
        <option value="<?=e($d['department'])?>">
          <?=e($d['department'])?>
        </option>
        <?php endforeach;?>
      </select>
      <select id="statusFilter" class="form-select form-select-sm" style="width:130px"
              onchange="filterTable()">
        <option value="">All Status</option>
        <?php foreach(['present','absent','late','half_day','leave'] as $s):?>
        <option value="<?=$s?>"><?=$stLabel[$s]?></option>
        <?php endforeach;?>
      </select>
    </div>
  </div>
  <div class="table-responsive">
    <table class="table table-sm mb-0" id="attTable">
      <thead class="table-secondary" style="font-size:.72rem">
        <tr>
          <th class="ps-3" style="width:32px">#</th>
          <th>Employee</th>
          <th>Department</th>
          <th class="text-center">Status</th>
          <th class="text-center">Check In</th>
          <th class="text-center">Check Out</th>
          <th class="text-center">Worked</th>
          <th class="text-center">OT Hrs</th>
          <th class="text-center">Method</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach($attDetail as $i=>$a):
          $clr   = $stColors[$a['status']] ?? '#64748b';
          $init  = strtoupper(substr($a['full_name'],0,1)
                 .(strpos($a['full_name'],' ')!==false?substr(strrchr($a['full_name'],' '),1,1):''));
        ?>
        <tr class="att-row"
            data-status="<?=e($a['status'])?>"
            data-dept="<?=e($a['department']??'')?>">
          <td class="ps-3 text-muted"><?=$i+1?></td>
          <td>
            <div class="d-flex align-items-center gap-2">
              <div class="emp-init" style="background:<?=$clr?>18;color:<?=$clr?>">
                <?=e($init)?>
              </div>
              <div>
                <div class="fw-semibold small"><?=e($a['full_name'])?></div>
                <div style="font-size:.62rem;color:#94a3b8">
                  <code><?=e($a['emp_code'])?></code>
                  &nbsp;<?=e($a['designation']??'')?>
                  <?php if($a['fingerprint_id']):?>
                  &nbsp;<i class="bi bi-fingerprint text-success" title="<?=e($a['fingerprint_id'])?>"></i>
                  <?php endif;?>
                </div>
              </div>
            </div>
          </td>
          <td>
            <span class="dept-tag" style="background:<?=$clr?>12;color:<?=$clr?>">
              <?=e($a['department']??'—')?>
            </span>
          </td>
          <td class="text-center">
            <span class="badge <?=$stBadge[$a['status']]??'bg-secondary'?>" style="font-size:.65rem">
              <?=$stLabel[$a['status']]??ucfirst($a['status'])?>
            </span>
          </td>
          <td class="text-center">
            <?php if($a['check_in']): ?>
            <span class="fw-semibold small"><?=substr($a['check_in'],0,5)?></span>
            <?php if($a['status']==='late'):?>
            <span class="text-danger ms-1" style="font-size:.6rem">Late</span>
            <?php endif;?>
            <?php else:?>
            <span class="text-muted">—</span>
            <?php endif;?>
          </td>
          <td class="text-center">
            <?php if($a['check_out']): ?>
            <span class="small"><?=substr($a['check_out'],0,5)?></span>
            <?php else:?>
            <span class="text-warning small">—</span>
            <?php endif;?>
          </td>
          <td class="text-center small">
            <?=$a['worked_hours']>0?'<span class="fw-semibold">'.number_format($a['worked_hours'],1).'h</span>':'—'?>
          </td>
          <td class="text-center">
            <?php if($a['ot_hours']>0):?>
            <span class="fw-bold" style="color:#d97706;font-size:.78rem"><?=number_format($a['ot_hours'],1)?>h</span>
            <?php else:?>
            <span class="text-muted">—</span>
            <?php endif;?>
          </td>
          <td class="text-center">
            <i class="bi <?=$methIcon[$a['method']]??'bi-dot'?>"
               style="color:<?=$methColor[$a['method']]??'#94a3b8'?>;font-size:1rem"
               title="<?=ucfirst($a['method'])?>"></i>
          </td>
        </tr>
        <?php endforeach;?>
        <?php if(empty($attDetail)):?>
        <tr>
          <td colspan="9" class="text-center text-muted py-5">
            <i class="bi bi-calendar-x d-block fs-2 mb-2 opacity-25"></i>
            No attendance records for <?=date('d F Y',strtotime($date))?>
          </td>
        </tr>
        <?php endif;?>
      </tbody>
      <tfoot class="table-secondary fw-bold" style="font-size:.72rem">
        <tr>
          <td colspan="3" class="ps-3">TOTAL</td>
          <td class="text-center"><?=count($attDetail)?> records</td>
          <td colspan="2"></td>
          <td class="text-center"><?=number_format($attSummary['total_worked'],1)?>h</td>
          <td class="text-center" style="color:#d97706"><?=number_format($attSummary['total_ot'],1)?>h</td>
          <td></td>
        </tr>
      </tfoot>
    </table>
  </div>
</div>

<!-- Absent / Not Marked Employees -->
<?php if(!empty($absentList)): ?>
<div class="card mt-3">
  <div class="card-header bg-danger text-white fw-semibold small">
    <i class="bi bi-person-x me-1"></i>Absent / Not Marked (<?=count($absentList)?>)
  </div>
  <div class="table-responsive">
    <table class="table table-sm mb-0">
      <thead class="table-secondary" style="font-size:.72rem">
        <tr><th class="ps-3">#</th><th>Employee</th><th>Dept</th><th>Designation</th><th>Phone</th></tr>
      </thead>
      <tbody>
        <?php foreach($absentList as $i=>$e):?>
        <tr>
          <td class="ps-3 text-muted"><?=$i+1?></td>
          <td>
            <div class="fw-semibold small"><?=e($e['full_name'])?></div>
            <code style="font-size:.6rem;color:#94a3b8"><?=e($e['emp_code'])?></code>
          </td>
          <td class="text-muted small"><?=e($e['department']??'—')?></td>
          <td class="text-muted small"><?=e($e['designation']??'—')?></td>
          <td class="small"><?=e($e['phone']??'—')?></td>
        </tr>
        <?php endforeach;?>
      </tbody>
    </table>
  </div>
</div>
<?php endif;?>

<!-- Charts -->
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<script>
// Status doughnut
new Chart(document.getElementById('statusChart'),{
  type:'doughnut',
  data:{
    labels:['Present','Absent','Late','Half Day','Leave'],
    datasets:[{
      data:[<?=$attSummary['present']?>,<?=$attSummary['absent']?>,
            <?=$attSummary['late']?>,<?=$attSummary['half_day']?>,<?=$attSummary['leave_days']?>],
      backgroundColor:['#16a34a','#dc2626','#d97706','#0891b2','#7c3aed'],
      borderWidth:2,borderColor:'#fff'
    }]
  },
  options:{responsive:true,cutout:'65%',
    plugins:{legend:{position:'bottom',labels:{font:{size:10},boxWidth:10}}}}
});

// Method bar
const methodData = <?= json_encode(array_values($methodBreakdown)) ?>;
new Chart(document.getElementById('methodChart'),{
  type:'bar',
  data:{
    labels:methodData.map(d=>d.method),
    datasets:[{
      label:'Records',
      data:methodData.map(d=>d.cnt),
      backgroundColor:['#16a34a','#3b82f6','#7c3aed','#d97706','#dc2626'],
      borderRadius:5
    }]
  },
  options:{responsive:true,indexAxis:'y',
    plugins:{legend:{display:false}},
    scales:{x:{beginAtZero:true,ticks:{font:{size:10}}},y:{ticks:{font:{size:10}}}}}
});

// Table filter
function filterTable(){
  const s=document.getElementById('empSearch').value.toLowerCase();
  const st=document.getElementById('statusFilter').value;
  const dp=document.getElementById('deptFilter').value;
  document.querySelectorAll('#attTable tbody tr.att-row').forEach(row=>{
    const text=row.textContent.toLowerCase();
    const status=row.dataset.status;
    const dept=row.dataset.dept;
    const ok=(!s||text.includes(s))&&(!st||status===st)&&(!dp||dept===dp);
    row.style.display=ok?'':'none';
  });
}
</script>