<?php /* payroll/attendance_chart.php */ ?>

<style>
.att-hero{background:linear-gradient(135deg,#0f172a,#1e3a5f 60%,#1d4ed8);
  border-radius:12px;padding:20px 24px;color:#fff;margin-bottom:18px}
.stat-kpi{border-radius:10px;border:1px solid #e2e8f0;background:#fff;
  padding:16px;text-align:center;height:100%}
.stat-kpi .val{font-size:1.8rem;font-weight:900;line-height:1}
.stat-kpi .lbl{font-size:.72rem;color:#94a3b8;margin-top:4px;text-transform:uppercase;letter-spacing:.04em}
.chart-card{border-radius:12px;border:1px solid #e2e8f0;background:#fff;overflow:hidden;margin-bottom:16px}
.chart-card-header{padding:12px 18px;border-bottom:1px solid #f1f5f9;
  display:flex;justify-content:space-between;align-items:center;
  font-size:.82rem;font-weight:700;color:#1e293b}
.chart-wrap{padding:14px 18px}
.emp-bar{height:22px;border-radius:4px;background:linear-gradient(90deg,#3b82f6,#60a5fa);
  transition:width .6s ease;min-width:4px;display:flex;align-items:center;
  padding-right:6px;justify-content:flex-end}
.emp-bar-row{display:flex;align-items:center;gap:8px;margin-bottom:6px}
.status-dot{width:10px;height:10px;border-radius:50%;flex-shrink:0;display:inline-block}
</style>

<!-- Hero -->
<div class="att-hero">
  <div class="d-flex justify-content-between align-items-center flex-wrap gap-2">
    <div>
      <h5 class="fw-bold mb-1">
        <i class="bi bi-bar-chart-line me-2"></i>Attendance Analytics
        <span class="badge bg-white text-primary ms-2" style="font-size:.72rem">
          <?= $monthLabel ?>
        </span>
      </h5>
      <div style="opacity:.8;font-size:.82rem">
        <?= $totalEmployees ?> employees &nbsp;·&nbsp;
        <?= $workingDays ?> working days &nbsp;·&nbsp;
        <i class="bi bi-fingerprint me-1"></i><?= $fpCount ?> fingerprint records
      </div>
    </div>
    <div class="d-flex gap-2">
      <a href="<?= APP_URL ?>/payroll/fp-upload" class="btn btn-outline-light btn-sm fw-semibold">
        <i class="bi bi-upload me-1"></i>FP Upload
      </a>
      <a href="<?= APP_URL ?>/payroll" class="btn btn-light btn-sm fw-semibold" style="color:#1d4ed8">
        <i class="bi bi-arrow-left me-1"></i>Payroll
      </a>
    </div>
  </div>
</div>

<!-- Month selector -->
<form method="GET" action="<?= APP_URL ?>/payroll/attendance-chart"
      class="d-flex gap-2 mb-3 align-items-end flex-wrap">
  <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');$y>=date('Y')-3;$y--):?>
    <option value="<?=$y?>" <?=$y===$year?'selected':''?>><?=$y?></option>
    <?php endfor;?>
  </select>
  <button class="btn btn-primary btn-sm fw-semibold">
    <i class="bi bi-funnel me-1"></i>Filter
  </button>
</form>

<?= flashMessages() ?>

<!-- KPI Row -->
<div class="row g-2 mb-3">
  <div class="col-6 col-md-2">
    <div class="stat-kpi" style="border-top:3px solid #3b82f6">
      <div class="val text-primary"><?= $totalEmployees ?></div>
      <div class="lbl">Employees</div>
    </div>
  </div>
  <div class="col-6 col-md-2">
    <div class="stat-kpi" style="border-top:3px solid #16a34a">
      <div class="val text-success"><?= $totalPresent ?></div>
      <div class="lbl">Total Present</div>
    </div>
  </div>
  <div class="col-6 col-md-2">
    <div class="stat-kpi" style="border-top:3px solid #dc2626">
      <div class="val text-danger"><?= $totalAbsent ?></div>
      <div class="lbl">Total Absent</div>
    </div>
  </div>
  <div class="col-6 col-md-2">
    <div class="stat-kpi" style="border-top:3px solid #d97706">
      <div class="val text-warning"><?= $totalLate ?></div>
      <div class="lbl">Late Arrivals</div>
    </div>
  </div>
  <div class="col-6 col-md-2">
    <div class="stat-kpi" style="border-top:3px solid #7c3aed">
      <div class="val" style="color:#7c3aed"><?= $totalLeave ?></div>
      <div class="lbl">Leave Days</div>
    </div>
  </div>
  <div class="col-6 col-md-2">
    <div class="stat-kpi" style="border-top:3px solid #0891b2">
      <div class="val" style="color:#0891b2"><?= number_format($totalOT,1) ?>h</div>
      <div class="lbl">Total OT</div>
    </div>
  </div>
</div>

<div class="row g-3">

  <!-- Daily Attendance Trend -->
  <div class="col-lg-8">
    <div class="chart-card">
      <div class="chart-card-header">
        <span><i class="bi bi-graph-up me-1 text-primary"></i>Daily Attendance Trend</span>
        <div class="d-flex gap-3" style="font-size:.72rem">
          <span><span class="status-dot" style="background:#3b82f6"></span> Present</span>
          <span><span class="status-dot" style="background:#dc2626"></span> Absent</span>
          <span><span class="status-dot" style="background:#d97706"></span> Late</span>
        </div>
      </div>
      <div class="chart-wrap">
        <canvas id="dailyChart" height="180"></canvas>
      </div>
    </div>

    <!-- Attendance by Status Doughnut + Method -->
    <div class="row g-3">
      <div class="col-md-5">
        <div class="chart-card">
          <div class="chart-card-header">
            <span><i class="bi bi-pie-chart me-1 text-info"></i>Status Breakdown</span>
          </div>
          <div class="chart-wrap text-center">
            <canvas id="statusChart" height="200"></canvas>
          </div>
        </div>
      </div>
      <div class="col-md-7">
        <div class="chart-card">
          <div class="chart-card-header">
            <span><i class="bi bi-fingerprint me-1 text-success"></i>Check-in Method</span>
          </div>
          <div class="chart-wrap">
            <canvas id="methodChart" height="200"></canvas>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- Right column -->
  <div class="col-lg-4">

    <!-- Attendance % by Employee -->
    <div class="chart-card mb-3">
      <div class="chart-card-header">
        <span><i class="bi bi-people me-1 text-primary"></i>Attendance % by Employee</span>
      </div>
      <div class="chart-wrap" style="max-height:340px;overflow-y:auto">
        <?php foreach($empStats as $es):
          $pct = $workingDays > 0 ? round($es['present']/$workingDays*100) : 0;
          $barColor = $pct>=95?'linear-gradient(90deg,#16a34a,#22c55e)':
                     ($pct>=80?'linear-gradient(90deg,#3b82f6,#60a5fa)':
                     ($pct>=60?'linear-gradient(90deg,#d97706,#f59e0b)':
                               'linear-gradient(90deg,#dc2626,#ef4444)'));
        ?>
        <div class="emp-bar-row">
          <div style="width:120px;font-size:.72rem;font-weight:600;flex-shrink:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap"
               title="<?=e($es['full_name'])?>">
            <?=e(explode(' ',$es['full_name'])[0])?>
          </div>
          <div style="flex:1;background:#f1f5f9;border-radius:4px;height:22px;position:relative">
            <div style="width:<?=$pct?>%;height:100%;border-radius:4px;background:<?=$barColor?>;
                        display:flex;align-items:center;justify-content:flex-end;padding-right:5px;
                        min-width:<?=$pct>0?'28':'0'?>px;transition:width .6s ease">
              <?php if($pct>15):?>
              <span style="font-size:.62rem;color:#fff;font-weight:700"><?=$pct?>%</span>
              <?php endif;?>
            </div>
            <?php if($pct<=15):?>
            <span style="font-size:.62rem;color:#64748b;font-weight:700;position:absolute;left:5px;top:3px"><?=$pct?>%</span>
            <?php endif;?>
          </div>
          <div style="width:30px;text-align:right;font-size:.7rem;color:#64748b;font-weight:700;flex-shrink:0">
            <?=$es['present']?>d
          </div>
        </div>
        <?php endforeach;?>
      </div>
    </div>

    <!-- OT Hours chart -->
    <div class="chart-card">
      <div class="chart-card-header">
        <span><i class="bi bi-clock-history me-1 text-warning"></i>Overtime Hours</span>
        <span class="badge bg-warning text-dark"><?=number_format($totalOT,1)?>h total</span>
      </div>
      <div class="chart-wrap">
        <canvas id="otChart" height="160"></canvas>
      </div>
    </div>
  </div>
</div>

<!-- Employee Detail Table -->
<div class="chart-card mt-3">
  <div class="chart-card-header">
    <span><i class="bi bi-table me-1 text-primary"></i>Employee Attendance Summary — <?= $monthLabel ?></span>
    <button onclick="window.print()" class="btn btn-sm btn-outline-secondary py-0 px-2">
      <i class="bi bi-printer me-1"></i>Print
    </button>
  </div>
  <div class="table-responsive">
    <table class="table table-sm table-hover mb-0 align-middle">
      <thead class="table-dark" style="font-size:.72rem">
        <tr>
          <th class="ps-3">#</th>
          <th>Employee</th>
          <th class="text-center text-success">Present</th>
          <th class="text-center text-danger">Absent</th>
          <th class="text-center text-warning">Late</th>
          <th class="text-center" style="color:#a78bfa">Leave</th>
          <th class="text-center">Half Day</th>
          <th class="text-center text-info">OT Hours</th>
          <th class="text-center">Worked Hrs</th>
          <th class="text-center">Method</th>
          <th class="text-center">Att %</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach($empStats as $i=>$es):
          $pct = $workingDays>0 ? round($es['present']/$workingDays*100) : 0;
          $pctCls = $pct>=95?'text-success fw-bold':($pct>=80?'text-primary':($pct>=60?'text-warning':'text-danger fw-bold'));
        ?>
        <tr>
          <td class="ps-3 text-muted small"><?=$i+1?></td>
          <td>
            <div class="fw-semibold small"><?=e($es['full_name'])?></div>
            <code style="font-size:.62rem;color:#94a3b8"><?=e($es['emp_code'])?></code>
            <?php if($es['fingerprint_id']):?>
            <span class="badge bg-success ms-1" style="font-size:.5rem">
              <i class="bi bi-fingerprint"></i>
            </span>
            <?php endif;?>
          </td>
          <td class="text-center fw-bold text-success"><?=$es['present']?></td>
          <td class="text-center fw-bold text-danger"><?=$es['absent']?></td>
          <td class="text-center fw-bold text-warning"><?=$es['late']?></td>
          <td class="text-center" style="color:#7c3aed;font-weight:700"><?=$es['leave']?></td>
          <td class="text-center text-muted"><?=$es['half_day']?></td>
          <td class="text-center <?=$es['ot_hours']>0?'text-warning fw-bold':''?>">
            <?=$es['ot_hours']>0?number_format($es['ot_hours'],1).'h':'—'?>
          </td>
          <td class="text-center text-muted small"><?=number_format($es['worked_hours'],1)?>h</td>
          <td class="text-center">
            <?php if($es['fingerprint_id']):?>
            <span class="badge bg-success" style="font-size:.6rem"><i class="bi bi-fingerprint me-1"></i>FP</span>
            <?php else:?>
            <span class="badge bg-secondary" style="font-size:.6rem">Manual</span>
            <?php endif;?>
          </td>
          <td class="text-center">
            <span class="fw-bold <?=$pctCls?>"><?=$pct?>%</span>
          </td>
        </tr>
        <?php endforeach;?>
      </tbody>
      <tfoot class="table-secondary fw-bold" style="font-size:.78rem">
        <tr>
          <td colspan="2" class="ps-3">TOTAL (<?=$totalEmployees?> employees)</td>
          <td class="text-center text-success"><?=$totalPresent?></td>
          <td class="text-center text-danger"><?=$totalAbsent?></td>
          <td class="text-center text-warning"><?=$totalLate?></td>
          <td class="text-center" style="color:#7c3aed"><?=$totalLeave?></td>
          <td class="text-center"><?=$totalHalfDay?></td>
          <td class="text-center text-warning"><?=number_format($totalOT,1)?>h</td>
          <td class="text-center"><?=number_format($totalWorkedHrs,1)?>h</td>
          <td colspan="2"></td>
        </tr>
      </tfoot>
    </table>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<script>
// ── Data from PHP ──────────────────────────────────────────
const dailyData  = <?= json_encode($dailyData) ?>;
const statusData = <?= json_encode($statusData) ?>;
const methodData = <?= json_encode($methodData) ?>;
const otData     = <?= json_encode($otData) ?>;

const chartDefaults = {
  responsive: true,
  plugins: { legend: { labels: { font: { size: 11 }, boxWidth: 12 } } }
};

// ── Daily Trend (Bar + Line) ───────────────────────────────
new Chart(document.getElementById('dailyChart'), {
  type: 'bar',
  data: {
    labels: dailyData.map(d=>d.day),
    datasets: [
      { label:'Present', data:dailyData.map(d=>d.present),
        backgroundColor:'rgba(59,130,246,.75)', borderRadius:3 },
      { label:'Absent',  data:dailyData.map(d=>d.absent),
        backgroundColor:'rgba(220,38,38,.65)', borderRadius:3 },
      { label:'Late',    data:dailyData.map(d=>d.late),
        backgroundColor:'rgba(217,119,6,.7)', borderRadius:3 },
      { label:'Leave',   data:dailyData.map(d=>d.leave),
        backgroundColor:'rgba(124,58,237,.6)', borderRadius:3 },
    ]
  },
  options: {
    ...chartDefaults,
    scales: {
      x: { stacked:true, grid:{ display:false }, ticks:{ font:{size:10} } },
      y: { stacked:true, beginAtZero:true, ticks:{ stepSize:1, font:{size:10} } }
    },
    plugins: { ...chartDefaults.plugins, legend:{ position:'top', labels:{ font:{size:11}, boxWidth:12 } } }
  }
});

// ── Status Doughnut ────────────────────────────────────────
new Chart(document.getElementById('statusChart'), {
  type: 'doughnut',
  data: {
    labels: statusData.map(d=>d.label),
    datasets: [{
      data: statusData.map(d=>d.value),
      backgroundColor: ['#3b82f6','#dc2626','#d97706','#7c3aed','#6b7280','#0891b2'],
      borderWidth: 2, borderColor:'#fff'
    }]
  },
  options: {
    ...chartDefaults,
    cutout:'65%',
    plugins: { legend:{ position:'bottom', labels:{ font:{size:10}, boxWidth:10 } } }
  }
});

// ── Method Bar ─────────────────────────────────────────────
new Chart(document.getElementById('methodChart'), {
  type: 'bar',
  data: {
    labels: methodData.map(d=>d.label),
    datasets: [{
      label: 'Records',
      data: methodData.map(d=>d.value),
      backgroundColor: ['#16a34a','#3b82f6','#7c3aed','#d97706','#dc2626'],
      borderRadius: 6
    }]
  },
  options: {
    ...chartDefaults, indexAxis:'y',
    scales: { x:{ beginAtZero:true, ticks:{font:{size:10}} }, y:{ticks:{font:{size:10}}} },
    plugins: { legend:{ display:false } }
  }
});

// ── OT Hours Bar ───────────────────────────────────────────
new Chart(document.getElementById('otChart'), {
  type: 'bar',
  data: {
    labels: otData.map(d=>d.name),
    datasets: [{
      label:'OT Hours',
      data: otData.map(d=>d.hours),
      backgroundColor:'rgba(245,158,11,.8)',
      borderRadius:4
    }]
  },
  options: {
    ...chartDefaults,
    scales: { x:{grid:{display:false},ticks:{font:{size:9}}}, y:{beginAtZero:true,ticks:{font:{size:9}}} },
    plugins: { legend:{display:false} }
  }
});
</script>