<?php
session_start();
require 'config/db.php';
if (!isset($_SESSION['admin_id'])) {
    header("Location: login.php");
    exit;
}

/* ===============================
   TABLE CONFIG
================================ */
$attendance_table = 'sales_employee_attendance';
$employee_table   = 'sales_employees';
$late_table       = 'sales_employee_late_log';

$today = date('Y-m-d');

/* ===============================
   FILTERS
================================ */
$month = isset($_GET['month']) ? (int)$_GET['month'] : date('n');
$year  = isset($_GET['year']) ? (int)$_GET['year'] : date('Y');
$selected_employee = isset($_GET['employee_id']) ? (int)$_GET['employee_id'] : 0;

$daysInMonth = cal_days_in_month(CAL_GREGORIAN, $month, $year);

/* ===============================
   EMPLOYEES
================================ */
$empSql = "SELECT id, full_name FROM $employee_table";
if ($selected_employee > 0) $empSql .= " WHERE id = $selected_employee";
$empSql .= " ORDER BY full_name ASC";

$employees = $pdo->query($empSql)->fetchAll(PDO::FETCH_ASSOC);
$allAttendance = [];

/* ===============================
   ATTENDANCE PROCESS
================================ */
foreach ($employees as $emp) {

    $emp_id = $emp['id'];

    $stmt = $pdo->prepare("
        SELECT att_date, status 
        FROM $attendance_table 
        WHERE employee_id=? 
        AND MONTH(att_date)=? 
        AND YEAR(att_date)=?
    ");
    $stmt->execute([$emp_id, $month, $year]);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $attendance = [];
    foreach ($rows as $r) {
        $attendance[$r['att_date']] = $r['status'];
    }

    for ($d = 1; $d <= $daysInMonth; $d++) {
        $date = sprintf("%04d-%02d-%02d", $year, $month, $d);
        if ($date >= $today) continue;

        if (!isset($attendance[$date])) {
            $weekday = date('w', strtotime($date));
            $status = ($weekday == 0) ? 'Holiday' : 'Absent';
            $attendance[$date] = $status;

            $pdo->prepare("
                INSERT INTO $attendance_table (employee_id, att_date, status)
                VALUES (?,?,?)
            ")->execute([$emp_id, $date, $status]);
        }
    }

    $lateStmt = $pdo->prepare("
        SELECT log_date 
        FROM $late_table 
        WHERE employee_id=? 
        AND MONTH(log_date)=? 
        AND YEAR(log_date)=?
    ");
    $lateStmt->execute([$emp_id, $month, $year]);
    foreach ($lateStmt->fetchAll(PDO::FETCH_COLUMN) as $ld) {
        $attendance[$ld] = 'Late';
    }

    $allAttendance[$emp_id] = [
        'name' => $emp['full_name'],
        'attendance' => $attendance
    ];
}

/* ===============================
   SUMMARY
================================ */
function summary($att) {
    $sum = ['Present'=>0,'Absent'=>0,'Leave'=>0,'Holiday'=>0,'Late'=>0];
    foreach ($att as $s) {
        if ($s === 'Late') { $sum['Late']++; $sum['Present']++; }
        elseif (isset($sum[$s])) $sum[$s]++;
    }
    return $sum;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="icon" type="image/png" href="images/jg.webp">
<title>JG - Suite</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="../assets/style.css">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">

<style>
:root{
  --blue:#0097fc;
  --orange:#ff6a00;
  --dark:#050814;
  --glass:rgba(255,255,255,.08);
}
*{font-family:Inter,Segoe UI,Arial,sans-serif}
body{background:var(--dark);color:#fff;overflow-x:hidden}

/* BACKGROUND */
.mesh{
  position:fixed;inset:0;
  background:
    radial-gradient(circle at 20% 20%, rgba(0,151,252,.35), transparent 45%),
    radial-gradient(circle at 80% 30%, rgba(255,106,0,.3), transparent 45%),
    linear-gradient(180deg,#03040a,#070b18);
  animation:mesh 25s infinite alternate;
  z-index:-2;
}
@keyframes mesh{to{filter:hue-rotate(25deg)}}

.grid{
  position:fixed;inset:0;
  background:
    linear-gradient(rgba(255,255,255,.04) 1px, transparent 1px),
    linear-gradient(90deg, rgba(255,255,255,.04) 1px, transparent 1px);
  background-size:70px 70px;
  animation:grid 50s linear infinite;
  z-index:-1;
}
@keyframes grid{to{transform:translateY(70px)}}

/* HEADER */
.topbar{
  position:fixed;top:0;left:0;right:0;height:64px;
  display:flex;align-items:center;justify-content:space-between;
  padding:0 36px;background:rgba(8,12,25,.6);
  backdrop-filter:blur(14px);
  border-bottom:1px solid rgba(255,255,255,.08);
  z-index:10;
}
.logo{display:flex;align-items:center;gap:10px;font-weight:600}
.logo img{height:42px}
.status::before{
  content:"";width:9px;height:9px;background:#1cff7a;
  border-radius:50%;margin-right:6px;display:inline-block;
  box-shadow:0 0 12px #1cff7a;
}

/* GLASS */
.glass-box{
  background:var(--glass);
  backdrop-filter:blur(22px);
  border:1px solid rgba(255,255,255,.14);
  border-radius:18px;
  padding:24px;
  box-shadow:0 0 50px rgba(0,151,252,.3);
}

/* ATT COLORS */
.present{background:#28a745;color:#fff}
.absent{background:#dc3545;color:#fff}
.leave{background:#ffc107;color:#000}
.holiday{background:#0d6efd;color:#fff}
.late{background:#fd7e14;color:#fff}
</style>
</head>

<body>

<div class="mesh"></div>
<div class="grid"></div>
<canvas id="particles"></canvas>

<?php include '../assets/header.php'; ?>
<div class="container-fluid" style="padding-top:90px">

<div class="glass-box mb-4">
<h4 class="mb-3">Sales Attendance</h4>

<form method="GET" class="mb-3 d-flex gap-2 flex-wrap">
<select name="employee_id" class="form-select w-auto">
<option value="0">All Employees</option>
<?php foreach ($employees as $e): ?>
<option value="<?= $e['id'] ?>" <?= $selected_employee==$e['id']?'selected':'' ?>>
<?= htmlspecialchars($e['full_name']) ?>
</option>
<?php endforeach; ?>
</select>

<select name="month" class="form-select w-auto">
<?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 w-auto">
<?php for ($y=date('Y')-5;$y<=date('Y')+5;$y++): ?>
<option value="<?= $y ?>" <?= $y==$year?'selected':'' ?>><?= $y ?></option>
<?php endfor; ?>
</select>

<button class="btn btn-glow">Apply</button>
</form>

<?php foreach ($allAttendance as $emp):
$att=$emp['attendance']; $sum=summary($att); ?>

<h5><?= htmlspecialchars($emp['name']) ?></h5>

<div class="mb-2">
<span class="badge bg-success">Present <?= $sum['Present'] ?></span>
<span class="badge bg-danger">Absent <?= $sum['Absent'] ?></span>
<span class="badge bg-warning text-dark">Leave <?= $sum['Leave'] ?></span>
<span class="badge bg-primary">Holiday <?= $sum['Holiday'] ?></span>
<span class="badge bg-warning text-dark">Late <?= $sum['Late'] ?></span>
</div>

<table class="table table-bordered table-sm text-center mb-4">
<thead><tr><?php foreach(['Sun','Mon','Tue','Wed','Thu','Fri','Sat'] as $d) echo "<th>$d</th>"; ?></tr></thead>
<tbody>
<?php
$firstDay = date('w', strtotime("$year-$month-01"));
$day=1;
while ($day <= $daysInMonth) {
 echo "<tr>";
 for ($i=0;$i<7;$i++) {
   if ($day==1 && $i<$firstDay || $day>$daysInMonth) echo "<td></td>";
   else {
     $date=sprintf("%04d-%02d-%02d",$year,$month,$day);
     $st=$att[$date]??'';
     echo "<td class='".strtolower($st)."'>$day<br>$st</td>";
     $day++;
   }
 }
 echo "</tr>";
}
?>
</tbody>
</table>

<?php endforeach; ?>

</div>
</div>
<script src="../assets/particles.js"></script>
</body>
</html>
