<?php
session_start();
require '../config/db.php';

if (!isset($_SESSION['hr_id'])) die('Unauthorized');

/* ===============================
   DEPARTMENTS & TABLES
================================ */
$departments = [
    'Sales' => 'manager1_attendance',
    'Design' => 'manager2_attendance',
    'Development' => 'manager3_attendance',
    'Marketing' => 'manager4_attendance'
];

$selected_department = $_GET['department'] ?? 'Sales';
$attendance_table = $departments[$selected_department] ?? 'manager1_attendance';

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

/* ===============================
   FILTERS
================================ */
$month = isset($_GET['month']) ? (int)$_GET['month'] : date('n');
$year  = isset($_GET['year']) ? (int)$_GET['year'] : date('Y');
$daysInMonth = cal_days_in_month(CAL_GREGORIAN, $month, $year);

/* ===============================
   ATTENDANCE DATA
================================ */
$stmt = $pdo->prepare("
    SELECT att_date, status 
    FROM $attendance_table
    WHERE MONTH(att_date)=? AND YEAR(att_date)=?
    ORDER BY att_date ASC
");
$stmt->execute([$month, $year]);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

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

// Fill missing days
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;

        // Optional: auto-insert into DB
        $pdo->prepare("INSERT INTO $attendance_table (att_date, status) VALUES (?,?)")
            ->execute([$date, $status]);
    }
}

/* ===============================
   SUMMARY FUNCTION
================================ */
function summary($att) {
    $sum = ['Present'=>0,'Absent'=>0,'Leave'=>0,'Holiday'=>0];
    foreach ($att as $s) {
        if (isset($sum[$s])) $sum[$s]++;
    }
    return $sum;
}
$sum = summary($attendance);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title><?= $selected_department ?> Attendance Calendar</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>
body{background:#050814;color:#fff;font-family:Inter,Segoe UI,Arial,sans-serif;}
.glass-box{background:rgba(255,255,255,.08);backdrop-filter:blur(20px);border-radius:15px;padding:20px;margin-bottom:30px;}
.present{background:#28a745;color:#fff;}
.absent{background:#dc3545;color:#fff;}
.leave{background:#ffc107;color:#000;}
.holiday{background:#0d6efd;color:#fff;}
table td{height:70px;width:14%;vertical-align:middle;}
:root{
  --blue:#0097fc;
  --orange:#ff6a00;
  --dark:#050814;
  --glass:rgba(255,255,255,.08);
}


/* 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)}}
.altern{
    z-index: 2 !important;
}
</style>
</head>
<body>
    <div class="mesh"></div>
<div class="grid"></div>
<canvas id="particles"></canvas>
<?php include '../assets/header.php'; ?>
<br><br><br>
<div class="container mt-4">
<h3 class="mb-4"><?= $selected_department ?> Department – Attendance Calendar <?= date('F', mktime(0,0,0,$month,1)) ?> <?= $year ?></h3>

<!-- FILTERS -->
<form method="GET" class="mb-4 altern d-flex gap-2 flex-wrap">
<select name="department" class="form-select w-auto">
<?php foreach ($departments as $name=>$table): ?>
<option value="<?= $name ?>" <?= $name==$selected_department?'selected':'' ?>><?= $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-primary">Apply</button>
</form>

<!-- ATTENDANCE CALENDAR -->
<div class="glass-box">
<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>
</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 = $attendance[$date] ?? '';
     $class = strtolower($st);
     echo "<td class='$class'>$day<br>$st</td>";
     $day++;
   }
 }
 echo "</tr>";
}
?>
</tbody>
</table>
</div>

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