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

$dept = isset($_GET['dept']) ? strtolower($_GET['dept']) : 'sales';
$attendance_table = $dept . '_employee_attendance';
$employee_table   = $dept . '_employees';
$late_table       = $dept . '_employee_late_log';
$today = date('Y-m-d');

/* ===============================
   HR HOLIDAY FORM SUBMISSION
================================ */
if(isset($_POST['set_holiday'])){
    $holidays = $_POST['holidays'] ?? [];
    if(!empty($holidays)){
        $employees = $pdo->query("SELECT id FROM $employee_table")->fetchAll(PDO::FETCH_COLUMN);
        foreach($holidays as $h){
            foreach($employees as $emp){
                // Insert or update holiday
                $chk = $pdo->prepare("SELECT id FROM $attendance_table WHERE employee_id=? AND att_date=?");
                $chk->execute([$emp, $h]);
                if($chk->rowCount()==0){
                    $pdo->prepare("INSERT INTO $attendance_table (employee_id, att_date, status) VALUES (?,?,?)")
                        ->execute([$emp, $h, 'Holiday']);
                } else {
                    $pdo->prepare("UPDATE $attendance_table SET status='Holiday' WHERE employee_id=? AND att_date=?")
                        ->execute([$emp, $h]);
                }

                // Holiday bridge logic for late (previous/next day)
                $prev = date('Y-m-d', strtotime('-1 day', strtotime($h)));
                $next = date('Y-m-d', strtotime('+1 day', strtotime($h)));

                $prevLate = $pdo->prepare("SELECT status FROM $late_table WHERE employee_id=? AND log_date=?");
                $prevLate->execute([$emp,$prev]);
                $prevStatus = $prevLate->fetchColumn();

                $nextLate = $pdo->prepare("SELECT status FROM $late_table WHERE employee_id=? AND log_date=?");
                $nextLate->execute([$emp,$next]);
                $nextStatus = $nextLate->fetchColumn();

                if($prevStatus==='Late' || $nextStatus==='Late'){
                    $chkLate = $pdo->prepare("SELECT id FROM $late_table WHERE employee_id=? AND log_date=?");
                    $chkLate->execute([$emp,$h]);
                    if($chkLate->rowCount()==0){
                        $pdo->prepare("INSERT INTO $late_table (employee_id, log_date, status, login_time) VALUES (?,?,?,?)")
                            ->execute([$emp,$h,'Late','00:00:00']);
                    }
                }
            }
        }
        $message = "Holiday(s) set successfully!";
    }
}

/* ===============================
   DEPARTMENT ATTENDANCE FETCH
================================ */
$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);

$employees = $pdo->query("SELECT id, full_name FROM $employee_table ORDER BY full_name ASC")->fetchAll(PDO::FETCH_ASSOC);
$allAttendance = [];

foreach($employees as $emp){
    $emp_id = $emp['id'];

    // 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'];
    }

    // Auto-fill past days
    for($d=1;$d<=$daysInMonth;$d++){
        $date = sprintf("%04d-%02d-%02d",$year,$month,$d);
        if(strtotime($date) >= strtotime($today)) continue; // skip today/future

        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]);
        }
    }

    // Bridge logic: Adjust Holiday based on neighbors
    $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;

        // Leave takes priority
        if ($prevStatus === 'Leave' && $nextStatus === 'Leave') {

    // Dono side Leave → Holiday ko Leave banao
    $attendance[$date] = 'Leave';

    $pdo->prepare("
        UPDATE $attendance_table 
        SET status=? 
        WHERE employee_id=? AND att_date=?
    ")->execute(['Leave', $emp_id, $date]);

}

        // Else Absent
        elseif ($prevStatus === 'Absent' && $nextStatus === 'Absent') {

    // Dono side Absent → Holiday ko Absent banao
    $attendance[$date] = 'Absent';

    $pdo->prepare("
        UPDATE $attendance_table 
        SET status=? 
        WHERE employee_id=? AND att_date=?
    ")->execute(['Absent', $emp_id, $date]);

}

    }

    // Apply Late logs
    $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'; // Display Late but counts separately
    }

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

/* ===============================
   SUMMARY FUNCTION
================================ */
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;
}
?>
<!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{
  
  --glass:rgba(255,255,255,.08);
}

/* RESET */
*{box-sizing:border-box;font-family:Inter,Segoe UI,Arial,sans-serif}
body{margin:0;}

/* ===== Animated Background ===== */

@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:-4;
}
@keyframes grid{to{transform:translateY(70px)}}

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

/* ===== GLASS PANEL ===== */
.glass-panel{
  margin:100px 28px 40px;
  padding:28px;
  color:white;
  background:var(--glass);
  backdrop-filter:blur(22px);
  border:1px solid rgba(255,255,255,.15);
  border-radius:20px;
  box-shadow:0 0 60px rgba(31,140,255,.25);
}

/* ===== FORM & BUTTONS ===== */
select.form-select,input.form-control{background:rgba(0,0,0,.3);border:1px solid rgba(255,255,255,.15);color:#fff;border-radius:10px;}
select.form-select:focus,input.form-control:focus{outline:none;border-color:var(--blue);box-shadow:0 0 8px var(--blue);}
button.btn{background:linear-gradient(135deg,var(--blue),var(--orange));color:#fff;font-weight:600;transition:.3s;}
button.btn:hover{box-shadow:0 0 20px var(--blue);transform:translateY(-2px);}

/* ===== TABLE ===== */
.table td,.table th{text-align:center;vertical-align:middle}
.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}
.badge{font-weight:600;box-shadow:0 0 10px rgba(31,140,255,.3);}
</style>
</head>
<body>
<div class="mesh"></div>
<div class="grid"></div>
<canvas id="particles"></canvas>

<?php include '../assets/header.php'; ?>

<div class="glass-panel">

<h3 class="mb-4 text-center">HR Attendance Management (<?= ucfirst($dept) ?> Dept)</h3>

<!-- DEPARTMENT & DATE FILTER -->
<form method="GET" class="mb-4 text-center">
<select name="dept" class="form-select d-inline w-auto">
<?php
$depts = ['sales','design','development','marketing'];
foreach($depts as $d):
?>
<option value="<?= $d ?>" <?= $d==$dept?'selected':'' ?>><?= ucfirst($d) ?></option>
<?php endforeach; ?>
</select>
<select name="month" class="form-select d-inline 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 d-inline 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">Go</button>
</form>

<!-- HOLIDAY SET FORM -->
<?php if(isset($message)) echo "<div class='alert alert-success'>$message</div>"; ?>
<form method="POST" class="mb-4 text-center">
<label>Set Holidays (multiple)</label><br>
<input type="date" name="holidays[]" multiple required class="form-control d-inline w-auto">
<input type="hidden" name="dept" value="<?= $dept ?>">
<button name="set_holiday" class="btn mt-2">Set Holiday</button>
</form>

<!-- EMPLOYEE ATTENDANCE -->
<?php foreach($allAttendance as $emp_id => $empData): 
$attendance = $empData['attendance'];
$summary = summary($attendance);
?>
<h5><?= htmlspecialchars($empData['name']) ?></h5>
<div class="mb-2">
<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>

<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 || $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>
<?php endforeach; ?>

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