<?php
session_start();
header('Content-Type: application/json');
require_once __DIR__ . '/../config/db.php';

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

$method = $_SERVER['REQUEST_METHOD'];

try {

    if ($method === 'GET') {
        $patient_id = $_GET['patient_id'] ?? null;

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

        $stmt = $pdo->prepare("SELECT * FROM medications WHERE patient_id = ? ORDER BY created_at DESC");
        $stmt->execute([$patient_id]);
        $medications = $stmt->fetchAll(PDO::FETCH_ASSOC);

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

    elseif ($method === 'POST') {
        $patient_id = $_POST['patient_id'] ?? null;
        $name = trim($_POST['name'] ?? '');
        $dosage = trim($_POST['dosage'] ?? '');
        $instructions = trim($_POST['instructions'] ?? '');

        if (!$patient_id || $name === '') {
            echo json_encode(['success' => false, 'message' => 'patient_id and medication name required']);
            exit;
        }

        $stmt = $pdo->prepare("INSERT INTO medications (patient_id, name, dosage, instructions) VALUES (?, ?, ?, ?)");
        $stmt->execute([$patient_id, $name, $dosage, $instructions]);

        echo json_encode(['success' => true]);
    }

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