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

date_default_timezone_set("Asia/Kuala_Lumpur");

$role = $_SESSION['role'];
$department_id = $_SESSION['department_id'];

$now = time();

$output = [];

if ($role === "technician") {

    $stmt = mysqli_prepare($conn, "
        SELECT id, equipment_name, next_due_date
        FROM equipment
        WHERE department_id = ?
        AND status = 'Active'
        AND next_due_date IS NOT NULL
    ");

    mysqli_stmt_bind_param($stmt, "i", $department_id);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);

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

        $due = strtotime($row['next_due_date']);
        $diff = $due - $now;

        if ($diff <= 0) {
            $time_text = "⚠️ Overdue";
            $class = "overdue";
        } else {
            $hours = floor($diff / 3600);
            $days = floor($hours / 24);

            if ($days > 0) {
                $time_text = "$days day(s) left";
                $class = "normal";
            } else {
                $time_text = "$hours hour(s) left";
                $class = "warning";
            }
        }

        $output[] = [
            "id" => $row['id'],
            "equipment_name" => $row['equipment_name'],
            "due_date" => date("d M Y", $due),
            "time_text" => $time_text,
            "class" => $class,
            "link" => "equipment/equipment_details.php?id=" . $row['id']
        ];
    }
}

header('Content-Type: application/json');
echo json_encode($output);