<?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'],
        'link' => '../equipment/equipment_details.php?id=' . $row['id']
    ];
}

/* ======================================================
   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'],
        'link' => '../equipment/equipment_details.php?id=' . $row['id']
    ];
}
?>

<!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:95px;
            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:5px;
            color:#2c3e50;
        }

        .event{
            padding:4px;
            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;
        }
        
        select{
    padding:8px 10px;
    border:1px solid #ddd;
    border-radius:6px;
    background:#fff;
    font-size:14px;
}

.calendar-header h1{
    font-size:28px;
    margin-bottom:5px;
}

    </style>
</head>

<body>

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

<div class="main">
            <?php
        $prevMonth = $month - 1;
        $prevYear = $year;
        
        if ($prevMonth < 1) {
            $prevMonth = 12;
            $prevYear--;
        }
        
        $nextMonth = $month + 1;
        $nextYear = $year;
        
        if ($nextMonth > 12) {
            $nextMonth = 1;
            $nextYear++;
        }
        ?>
    <div class="calendar-header">

        <div>
            <h1>
                <?= date('F Y', strtotime("$year-$month-01")) ?>
            </h1>
        
            <p>Equipment Due Dates & Maintenance Activities</p>
        </div>

        <div style="display:flex;align-items:center;gap:10px;flex-wrap:wrap;">

    <!-- Back -->
    <a class="btn btn-back"
       href="../maintenance.php">
        ← Back
    </a>

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

    <!-- Month Year Selector -->
    <form method="GET" style="display:flex;gap:8px;">

        <select name="month">
            <?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">
            <?php for($y=date('Y')-3;$y<=date('Y')+3;$y++): ?>
                <option value="<?= $y ?>"
                    <?= ($y == $year) ? 'selected' : '' ?>>
                    <?= $y ?>
                </option>
            <?php endfor; ?>
        </select>

        <button type="submit" class="btn">
            Go
        </button>

    </form>

    <!-- Next -->
    <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
                        <?=
                        ($event['status'] == 'Completed') ? 'completed' :
                        (($event['status'] == 'HOD Rejected') ? 'in-progress' :
                        (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="<?= $event['link'] ?>">
                               View
                            </a>

                        <?php endif; ?>

                    </div>

                <?php endforeach; ?>

            <?php endif; ?>

        </div>

        <?php endfor; ?>

    </div>

</div>

</body>
</html>