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

$manager_id = $_SESSION['manager_id'];
$dept = $_SESSION['department'];
$manager_table = "manager2_attendance";

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

// Check today's attendance
$att_stmt = $pdo->prepare("SELECT * FROM $manager_table WHERE manager_id=? AND att_date=?");
$att_stmt->execute([$manager_id, $today]);
$today_att = $att_stmt->fetch();

// Month & Year
$month = isset($_GET['month']) ? (int)$_GET['month'] : date('n');
$year  = isset($_GET['year']) ? (int)$_GET['year'] : date('Y');

// Fetch attendance for month
$stmt = $pdo->prepare("SELECT * FROM $manager_table WHERE manager_id=? AND MONTH(att_date)=? AND YEAR(att_date)=?");
$stmt->execute([$manager_id, $month, $year]);
$attendance_data = $stmt->fetchAll(PDO::FETCH_ASSOC);

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

// Auto mark Absent for past unmarked days
for($d=1;$d<=cal_days_in_month(CAL_GREGORIAN,$month,$year);$d++){
    $dateStr = sprintf("%04d-%02d-%02d",$year,$month,$d);
    if(!isset($attendance[$dateStr]) && strtotime($dateStr)<strtotime($today)){
        $attendance[$dateStr] = 'Absent';
        $pdo->prepare("INSERT INTO $manager_table (manager_id, att_date, status) VALUES (?,?,?)")
            ->execute([$manager_id, $dateStr, 'Absent']);
    }
}

// Summary
$summary = ['Present'=>0,'Absent'=>0,'Leave'=>0];
foreach($attendance as $status){
    if(isset($summary[$status])) $summary[$status]++;
}

// Days in month
$daysInMonth = cal_days_in_month(CAL_GREGORIAN,$month,$year);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My Attendance</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
body { 
    background:#f1f5f9; 
    font-family:Arial,sans-serif; 
}
.glass-container{
    max-width:1200px;
    margin:40px auto;
    padding:25px;
    background:var(--glass);
    backdrop-filter:blur(22px);
}
.glass-card{
    background: rgba(255,255,255,.65);
    backdrop-filter: blur(14px);
    -webkit-backdrop-filter: blur(14px);
    border-radius:16px;
    padding:20px;
    box-shadow:0 10px 25px rgba(0,0,0,.08);
    border:1px solid rgba(255,255,255,.35);
    background:var(--glass);
    backdrop-filter:blur(22px);
}
.table td, .table th { 
    text-align:center; 
    vertical-align:middle; 
    font-weight:500;
}
.present { background:#28a745; color:#fff; font-weight:bold; }
.absent  { background:#dc3545; color:#fff; font-weight:bold; }
.leave   { background:#ffc107; color:#000; font-weight:bold; }

select, button{
    border-radius:10px;
}
button{
    background:#2563eb;
    color:#fff;
    border:none;
    font-weight:600;
    padding:6px 14px;
}
button:hover{
    background:#1d4ed8;
}
</style>
</head>
<body>

<?php include 'assets/layout_top.php'; ?>
<br><br><br>
<div class="glass-container glass-card">

<h3 class="text-center mb-4">📅 My Attendance</h3>

<!-- Mark Today Attendance -->
<?php if(!$today_att): ?>
<div class="mb-4 text-center">
    <form method="POST" action="mark_manager_attendance.php">
        <button class="btn btn-success btn-lg">Mark Today's Attendance</button>
    </form>
</div>
<?php endif; ?>

<!-- Month/Year Selector -->
<form method="GET" class="mb-4 text-center d-flex justify-content-center gap-2 flex-wrap">
    <select name="month" class="form-select d-inline-block 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-block 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>Go</button>
</form>

<!-- Summary -->
<div class="mb-4 text-center">
    <span class="badge bg-success me-2">Present: <?= $summary['Present'] ?></span>
    <span class="badge bg-danger me-2">Absent: <?= $summary['Absent'] ?></span>
    <span class="badge bg-warning text-dark">Leave: <?= $summary['Leave'] ?></span>
</div>

<!-- Calendar Table -->
<table class="table table-bordered table-hover">
    <thead>
        <tr>
            <?php
            $weekDays = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
            foreach($weekDays as $d) echo "<th>$d</th>";
            ?>
        </tr>
    </thead>
    <tbody>
    <?php
    $firstDay = date('w', strtotime("$year-$month-01"));
    $day=1;
    $finished=false;
    while(!$finished){
        echo "<tr>";
        for($i=0;$i<7;$i++){
            if($day==1 && $i<$firstDay){
                echo "<td></td>";
            }elseif($day>$daysInMonth){
                echo "<td></td>";
                $finished=true;
            }else{
                $dateStr = sprintf("%04d-%02d-%02d",$year,$month,$day);
                $status = $attendance[$dateStr] ?? '';
                $class = strtolower($status);
                echo "<td class='$class'>$day<br>$status</td>";
                $day++;
            }
        }
        echo "</tr>";
    }
    ?>
    </tbody>
</table>

</div>

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

</body>
</html>
