<?php
session_start();
require_once __DIR__ . "/../config/db.php";

if (!isset($_SESSION['user_id'])) {
    header("Location: ../login.php");
    exit();
}

$role = $_SESSION['role'];

/* ======================================================
   ONLY TECHNICIAN & HOD CAN EDIT
====================================================== */
$canEdit = ($role == 'technician' || $role == 'hod');

/* ======================================================
   MONTH & YEAR
====================================================== */
$month = $_GET['month'] ?? date('m');
$year  = $_GET['year'] ?? date('Y');

$month = intval($month);
$year  = intval($year);

$firstDay = date("$year-$month-01");
$totalDays = date('t', strtotime($firstDay));

/* ======================================================
   GET EQUIPMENT DUE DATE
====================================================== */
$equipmentQuery = "
SELECT 
    id,
    equipment_name,
    next_due_date,
    status
FROM equipment
WHERE next_due_date IS NOT NULL
";

$equipmentResult = mysqli_query($conn, $equipmentQuery);

$calendarData = [];

while($row = mysqli_fetch_assoc($equipmentResult)) {

    $dateKey = date('Y-m-d', strtotime($row['next_due_date']));

    $calendarData[$dateKey][] = [
        'type' => 'Due',
        'equipment_name' => $row['equipment_name'],
        'status' => $row['status']
    ];
}

/* ======================================================
   GET MAINTENANCE RECORD
====================================================== */
$maintenanceQuery = "
SELECT 
    mr.id,
    mr.status,
    mr.maintenance_date,
    e.equipment_name
FROM maintenance_record mr
JOIN equipment e ON mr.equipment_id = e.id
WHERE mr.maintenance_date IS NOT NULL
";

$maintenanceResult = mysqli_query($conn, $maintenanceQuery);

while($row = mysqli_fetch_assoc($maintenanceResult)) {

    $dateKey = date('Y-m-d', strtotime($row['maintenance_date']));

    $calendarData[$dateKey][] = [
        'type' => 'Maintenance',
        'equipment_name' => $row['equipment_name'],
        'status' => $row['status']
    ];
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Schedule Calendar - QRCareTrack</title>

    <link rel="stylesheet" href="../assets/style.css">

    <style>

        body{
            background:#f5f7fb;
        }

        .main{
            margin-left:250px;
            padding:20px;
        }

        .calendar-header{
            display:flex;
            justify-content:space-between;
            align-items:center;
            margin-bottom:20px;
            flex-wrap:wrap;
            gap:10px;
        }

        .calendar-header h1{
            margin:0;
        }

        .calendar{
            display:grid;
            grid-template-columns: repeat(7, 1fr);
            gap:10px;
        }

        .day-name{
            background:#2c3e50;
            color:#fff;
            padding:10px;
            text-align:center;
            border-radius:8px;
            font-weight:bold;
        }

        .day-box{
            background:#fff;
            min-height:140px;
            border-radius:10px;
            padding:10px;
            box-shadow:0 2px 5px rgba(0,0,0,0.08);
            overflow:auto;
        }

        .day-number{
            font-weight:bold;
            margin-bottom:10px;
            color:#2c3e50;
        }

        .event{
            padding:6px;
            border-radius:6px;
            margin-bottom:6px;
            font-size:12px;
            color:#fff;
        }

        .due{
            background:#f39c12;
        }

        .maintenance{
            background:#2980b9;
        }

        .completed{
            background:#27ae60;
        }

        .in-progress{
            background:#c0392b;
        }

        .empty{
            background:transparent;
            box-shadow:none;
        }

        .legend{
            display:flex;
            gap:15px;
            margin-bottom:20px;
            flex-wrap:wrap;
        }

        .legend span{
            display:flex;
            align-items:center;
            gap:5px;
            font-size:13px;
        }

        .legend-box{
            width:15px;
            height:15px;
            border-radius:4px;
        }

        .btn{
            background:#3498db;
            color:#fff;
            padding:8px 14px;
            border-radius:6px;
            text-decoration:none;
            font-size:14px;
        }

        .edit-btn{
            margin-top:6px;
            display:inline-block;
            background:#2ecc71;
            color:#fff;
            padding:4px 8px;
            border-radius:5px;
            text-decoration:none;
            font-size:11px;
        }

    </style>
</head>

<body>

<?php include "../includes/sidebar.php"; ?>

<div class="main">

    <div class="calendar-header">

        <div>
            <h1>Maintenance Schedule</h1>
            <p>Equipment due dates & maintenance activities</p>
        </div>

        <div>
            <?php
                $prevMonth = $month - 1;
                $prevYear = $year;

                if($prevMonth <= 0){
                    $prevMonth = 12;
                    $prevYear--;
                }

                $nextMonth = $month + 1;
                $nextYear = $year;

                if($nextMonth > 12){
                    $nextMonth = 1;
                    $nextYear++;
                }
            ?>

            <a class="btn" href="?month=<?= $prevMonth ?>&year=<?= $prevYear ?>">
                ← Previous
            </a>

            <a class="btn" href="?month=<?= $nextMonth ?>&year=<?= $nextYear ?>">
                Next →
            </a>
        </div>

    </div>

    <div class="legend">

        <span>
            <div class="legend-box due"></div>
            Due Date
        </span>

        <span>
            <div class="legend-box maintenance"></div>
            Maintenance
        </span>

    </div>

    <div class="calendar">

        <?php
        $days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];

        foreach($days as $day){
            echo "<div class='day-name'>$day</div>";
        }

        $firstDayWeek = date('w', strtotime($firstDay));

        for($i=0; $i<$firstDayWeek; $i++){
            echo "<div class='day-box empty'></div>";
        }

        for($day=1; $day <= $totalDays; $day++):

            $currentDate = date('Y-m-d', strtotime("$year-$month-$day"));
        ?>

        <div class="day-box">

            <div class="day-number">
                <?= $day ?>
            </div>

            <?php if(isset($calendarData[$currentDate])): ?>

                <?php foreach($calendarData[$currentDate] as $event): ?>

                    <div class="event <?= strtolower($event['type']) == 'due' ? 'due' : 'maintenance' ?>">

                        <b><?= htmlspecialchars($event['equipment_name']) ?></b><br>

                        <?= $event['type'] ?><br>

                        Status:
                        <?= htmlspecialchars($event['status']) ?>

                        <?php if($canEdit): ?>

                            <br>

                            <a class="edit-btn"
                               href="../equipment/edit_equipment.php?id=<?= $event['type']=='Due' ? $row['id'] : '' ?>">
                               Edit
                            </a>

                        <?php endif; ?>

                    </div>

                <?php endforeach; ?>

            <?php endif; ?>

        </div>

        <?php endfor; ?>

    </div>

</div>

</body>
</html>