<?php
session_start();
require 'config/db.php';
if(!isset($_SESSION['employee_id'])) die('Unauthorized');

$emp_id = $_SESSION['employee_id'];
$dept = $_SESSION['department'] ?? 'design';
$dept = strtolower($dept);
$dept = preg_replace('/[^a-z0-9_]/','',$dept);


$attendance_table = $dept . '_employee_attendance';
$late_table       = $dept . '_employee_late_log';
$today = date('Y-m-d');

$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);

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

$attendance = [];
foreach($data as $a){
    $attendance[$a['att_date']] = $a['status'];
}

for($d=1;$d<=$daysInMonth;$d++){
    $date = sprintf("%04d-%02d-%02d",$year,$month,$d);
    if(strtotime($date) >= strtotime($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]);
    }
}

$dates = array_keys($attendance);
sort($dates);
foreach($dates as $date){
    if($attendance[$date]!=='Holiday') continue;

    $prev = date('Y-m-d', strtotime('-1 day', strtotime($date)));
    $next = date('Y-m-d', strtotime('+1 day', strtotime($date)));

    $prevStatus = $attendance[$prev] ?? null;
    $nextStatus = $attendance[$next] ?? null;

    if(in_array('Leave', [$prevStatus, $nextStatus])){
        $attendance[$date] = 'Leave';
        $pdo->prepare("UPDATE $attendance_table SET status=? WHERE employee_id=? AND att_date=?")
            ->execute(['Leave',$emp_id,$date]);
    }
    elseif(in_array('Absent', [$prevStatus, $nextStatus])){
        $attendance[$date] = 'Absent';
        $pdo->prepare("UPDATE $attendance_table SET status=? WHERE employee_id=? AND att_date=?")
            ->execute(['Absent',$emp_id,$date]);
    }
}

$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]);
$lateDates = $lateStmt->fetchAll(PDO::FETCH_COLUMN);
foreach($lateDates as $ld){
    $attendance[$ld] = 'Late';
}

function summary($att){
    $summary = ['Present'=>0,'Absent'=>0,'Leave'=>0,'Holiday'=>0,'Late'=>0];
    foreach($att as $s){
        if($s=='Late') $summary['Late']++;
        elseif(isset($summary[$s])) $summary[$s]++;
    }
    return $summary;
}

$summary = summary($attendance);
?>
<!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">

<!-- External CSS -->
<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>
/* ===== Animated Background ===== */
.mesh{
  position:fixed;inset:0;
  background:
    radial-gradient(circle at 15% 20%, rgba(31,140,255,.35), transparent 45%),
    radial-gradient(circle at 80% 25%, rgba(255,138,0,.28), transparent 45%),
    linear-gradient(180deg,#03040a,#070b18);
  animation:mesh 25s ease-in-out infinite alternate;
  z-index:-6;
}
@keyframes mesh{0%{filter:hue-rotate(0)}100%{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:-5;
}
@keyframes grid{to{transform:translateY(70px)}}

/* Glass panel */
.glass-panel{
  max-width:900px;
  margin:80px auto;
  padding:30px;
  background:rgba(255,255,255,.08);
  backdrop-filter:blur(22px);
  border-radius:18px;
  border:1px solid rgba(255,255,255,.14);
  box-shadow:0 12px 35px rgba(0,151,252,.25);
  color:#fff;
    position: relative;
  z-index: 10;
}

.table td,.table th{text-align:center;vertical-align:middle;color:#lack}
.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}

.form-select, .btn-main{
  background:rgba(0,0,0,.35);
  color:#fff;
  border:none;
}
.btn-main{
  background:linear-gradient(135deg,#0097fc,#ff6a00);
  font-weight:600;
  padding:10px;
  box-shadow:0 0 25px rgba(0,151,252,.4);
}
.btn-main:hover{
  transform:translateY(-2px);
  box-shadow:0 0 35px rgba(255,138,0,.6);
}
</style>
</head>
<body>

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

<!-- ===== HEADER ===== -->
<?php include 'assets/header.php'; ?>

<div class="glass-panel">

<h4 class="mb-4 text-center">My Attendance (<?= ucfirst($dept) ?> Department)</h4>

<!-- MONTH/YEAR FILTER -->
<form method="GET" class="mb-4 d-flex justify-content-center gap-2 flex-wrap">
  <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-main">Go</button>
</form>

<!-- SUMMARY -->
<div class="mb-3 text-center d-flex justify-content-center gap-2 flex-wrap">
  <span class="badge bg-success">Present <?= $summary['Present'] ?></span>
  <span class="badge bg-danger">Absent <?= $summary['Absent'] ?></span>
  <span class="badge bg-warning text-dark">Leave <?= $summary['Leave'] ?></span>
  <span class="badge bg-primary">Holiday <?= $summary['Holiday'] ?></span>
  <span class="badge bg-warning text-white">Late <?= $summary['Late'] ?></span>
</div>

<!-- ATTENDANCE TABLE -->
<table class="table table-bordered 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){
            echo "<td></td>";
        }elseif($day>$daysInMonth){
            echo "<td></td>";
        }else{
            $date = sprintf("%04d-%02d-%02d",$year,$month,$day);
            $st = $attendance[$date] ?? '';
            echo "<td class='".strtolower($st)."'>$day<br>$st</td>";
            $day++;
        }
    }
    echo "</tr>";
}
?>
</tbody>
</table>

</div>

<script src="assets/particles.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
