<?php
// api/patient/prescriptions.php
require_once __DIR__ . '/../middleware.php';
require_once __DIR__ . '/../../layouts/dbconn.php';

global $API_USER;
if (!isset($API_USER)) {
    jsonError('Unauthorized', 401);
}

// Get Patient ID
$user_id = $API_USER['sub'];
$stmt = $conn->prepare("SELECT patient_id FROM patients WHERE user_id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$res = $stmt->get_result();

if ($res->num_rows === 0) {
    jsonError('Patient profile not found', 404);
}

$patient = $res->fetch_assoc();
$patient_id = $patient['patient_id'];

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    // Logic from patient_prescriptions.php
    $sql = "SELECT p.prescription_id, p.date_prescribed, p.medication_name, p.dosage, 
                   p.frequency, p.duration, p.indication, p.status, p.instructions,
                   p.route, p.refills_remaining, p.refills_allowed,
                   u.full_name as doctor_name, d.specialization 
            FROM prescriptions p 
            JOIN doctors d ON p.doctor_id = d.doctor_id 
            JOIN users u ON d.user_id = u.user_id 
            WHERE p.patient_id = ? 
            ORDER BY p.date_prescribed DESC";

    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $patient_id);
    $stmt->execute();
    $result = $stmt->get_result();

    $prescriptions = [];
    while ($row = $result->fetch_assoc()) {
        $prescriptions[] = $row;
    }

    jsonResponse($prescriptions);

} else {
    jsonError('Method not allowed', 405);
}
?>