<?php
session_start();
include '../layouts/dbconn.php';

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

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

$allowed_roles = ['SUPER_ADMIN', 'HOSPITAL_ADMIN', 'CHIEF_PHARMACIST', 'PHARMACIST', 'PHARMACY_TECH'];
if (!in_array($_SESSION['role_code'] ?? '', $allowed_roles)) {
    echo json_encode(['success' => false, 'message' => 'Forbidden']);
    exit();
}

try {
    $count_sql = "SELECT COUNT(*) as count FROM prescriptions WHERE dispensed = 0 AND status = 'ACTIVE'";
    $result = $conn->query($count_sql);
    $count = $result ? (int) $result->fetch_assoc()['count'] : 0;
    echo json_encode(['success' => true, 'count' => $count]);
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage(), 'count' => 0]);
}
