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

header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['count' => 0]);
    exit;
}

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

$count = 0;

/* ONLY TECHNICIAN */
if ($role === "technician" && $department_id) {

    $stmt = mysqli_prepare($conn, "
        SELECT COUNT(*) as total
        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);
    $res = mysqli_stmt_get_result($stmt);

    $row = mysqli_fetch_assoc($res);
    $count = $row['total'] ?? 0;
}

echo json_encode(['count' => $count]);