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

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

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

// Check permissions
$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' => 'Insufficient permissions']);
    exit();
}

// Get patient ID
$patient_id = isset($_POST['patient_id']) ? (int)$_POST['patient_id'] : 0;

if (!$patient_id) {
    echo json_encode(['success' => false, 'message' => 'Patient ID is required']);
    exit();
}

try {
    // Fetch active prescriptions for the patient
    $sql = "SELECT p.prescription_id, p.prescription_number, p.medication_name, 
                   p.medication_type, p.dosage, p.frequency, p.route, p.duration,
                   p.quantity, p.instructions, p.prescribed_date,
                   doc.full_name as doctor_name,
                   pv.visit_number
            FROM prescriptions p
            INNER JOIN users doc ON p.doctor_id = doc.user_id
            LEFT JOIN patient_visits pv ON p.visit_id = pv.visit_id
            WHERE p.patient_id = ? 
            AND p.dispensed = 0 
            AND p.status = 'ACTIVE'
            ORDER BY p.prescribed_date DESC";
    
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('i', $patient_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $prescriptions = [];
    while ($row = $result->fetch_assoc()) {
        // Format date
        $row['prescribed_date'] = date('d M Y', strtotime($row['prescribed_date']));
        $prescriptions[] = $row;
    }
    
    echo json_encode([
        'success' => true,
        'prescriptions' => $prescriptions,
        'count' => count($prescriptions)
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Error loading prescriptions: ' . $e->getMessage()
    ]);
}

$conn->close();
?>