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

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

$manager_id = $_SESSION['manager_id'];
$dept = strtolower($_SESSION['department']);
$manager_table = "manager1_attendance"; // e.g., sales_manager_attendance

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

// Check if today's attendance is marked
$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 selection
$month = isset($_GET['month']) ? (int)$_GET['month'] : date('n');
$year  = isset($_GET['year']) ? (int)$_GET['year'] : date('Y');

// Fetch all attendance for selected 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 unmarked past 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);

/* ===== PAGE TITLE ===== */
$page_title = ucfirst($dept) . " Manager • My Attendance";

/* ===== LAYOUT START ===== */
include 'assets/layout_top.php';
?>
<br><br>
<div class="glass-panel p-4">

<h3 class="mb-4 text-center">
    <i class="fa-solid fa-calendar-check me-2"></i>My Attendance
</h3>

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

<!-- Month/Year Selector -->
<form method="GET" class="mb-3 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 class="btn-main"><i class="fa-solid fa-arrow-right me-1"></i> Go</button>
</form>

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

<!-- Attendance Calendar -->
<div class="glass-card p-3 overflow-auto">
<table class="table table-bordered text-center mb-0">
    <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'><b>$day</b><br>$status</td>";
                $day++;
            }
        }
        echo "</tr>";
    }
    ?>
    </tbody>
</table>
</div>

</div>

<?php
/* ===== LAYOUT END ===== */
include 'assets/layout_bottom.php';
?>
