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

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

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method', 'prescriptions' => []]);
    exit();
}

$patient_id = (int)($_POST['patient_id'] ?? 0);

if ($patient_id < 1) {
    echo json_encode(['success' => false, 'message' => 'Invalid patient ID', 'prescriptions' => []]);
    exit();
}

try {
    // Uses prescriptions table directly — doctor_id joins to users
    $stmt = $conn->prepare(
        "SELECT p.prescription_id,
                p.prescription_number,
                COALESCE(NULLIF(p.medication_name, ''), NULLIF(p.medication_name, '0'), p.medication_name) AS medication_name,
                p.medication_type,
                p.dosage,
                p.frequency,
                p.duration,
                p.quantity,
                p.instructions,
                p.prescribed_date,
                p.status,
                u.full_name AS doctor_name
         FROM   prescriptions p
         LEFT   JOIN users u ON p.doctor_id = u.user_id
         WHERE  p.patient_id = ?
           AND  p.dispensed  = 0
           AND  p.status     = 'ACTIVE'
         ORDER  BY p.prescribed_date DESC, p.created_at DESC"
    );

    if (!$stmt) {
        throw new Exception('Prepare failed: ' . $conn->error);
    }

    $stmt->bind_param('i', $patient_id);

    if (!$stmt->execute()) {
        throw new Exception('Execute failed: ' . $stmt->error);
    }

    $result        = $stmt->get_result();
    $prescriptions = [];

    while ($row = $result->fetch_assoc()) {
        $prescriptions[] = [
            'prescription_id'     => (int)$row['prescription_id'],
            'prescription_number' => $row['prescription_number']  ?? '',
            'medication_name'     => $row['medication_name']      ?? '',
            'medication_type'     => $row['medication_type']      ?? '',
            'dosage'              => $row['dosage']               ?? '',
            'frequency'           => $row['frequency']            ?? '',
            'duration'            => $row['duration']             ?? '',
            'quantity'            => $row['quantity']             ?? '',
            'instructions'        => $row['instructions']         ?? '',
            'prescribed_date'     => $row['prescribed_date']      ?? '',
            'doctor_name'         => $row['doctor_name']          ?? 'Unknown',
            'status'              => $row['status']               ?? '',
        ];
    }

    $stmt->close();

    echo json_encode([
        'success'       => true,
        'prescriptions' => $prescriptions,
        'count'         => count($prescriptions),
    ]);

} catch (Exception $e) {
    error_log('get_patient_prescriptions.php error: ' . $e->getMessage());
    echo json_encode([
        'success'       => false,
        'message'       => $e->getMessage(),
        'prescriptions' => [],
    ]);
}