<?php
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/db.php';

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

// Allow caregiver OR admin
if (!isset($_SESSION['caregiver_logged_in']) && !isset($_SESSION['admin_logged_in'])) {
    echo json_encode(['success' => false, 'message' => 'Not authorized']);
    exit;
}

try {
    $stmt = $pdo->query("
        SELECT id, generic_name, rxcui, brand_names
        FROM medication_library
        ORDER BY generic_name ASC
    ");

    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode([
        'success' => true,
        'medications' => $rows
    ]);

} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}