<?php
/**
 * AJAX: Get Remedy Details
 * Fetch remedy information including Materia Medica
 * Method: GET/POST
 */

require_once '../config/config.php';
require_once '../includes/functions.php';

session_start();
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    http_response_code(200);
    exit;
}

$remedyId = (int)($_GET['id'] ?? $_POST['id'] ?? 0);
$remedyName = $_GET['name'] ?? $_POST['name'] ?? '';

if ($remedyId <= 0 && empty($remedyName)) {
    echo json_encode(['success' => false, 'error' => 'Remedy ID or name required']);
    exit;
}

$pdo = getDB();

if ($remedyId > 0) {
    $stmt = $pdo->prepare("SELECT * FROM remedies WHERE id = ?");
    $stmt->execute([$remedyId]);
} else {
    $stmt = $pdo->prepare("SELECT * FROM remedies WHERE name = ?");
    $stmt->execute([$remedyName]);
}

$remedy = $stmt->fetch();

if (!$remedy) {
    echo json_encode(['success' => false, 'error' => 'Remedy not found']);
    exit;
}

// Get rubric count
$stmt = $pdo->prepare("SELECT COUNT(*) as count FROM rubric_remedy WHERE remedy_id = ?");
$stmt->execute([$remedy['id']]);
$rubricCount = $stmt->fetch()['count'];

// Get prescription count
$stmt = $pdo->prepare("SELECT COUNT(*) as count FROM cases WHERE prescribed_remedy_id = ?");
$stmt->execute([$remedy['id']]);
$prescriptionCount = $stmt->fetch()['count'];

// Parse modalities
$modalities = json_decode($remedy['modalities'], true);

echo json_encode([
    'success' => true,
    'data' => [
        'id' => $remedy['id'],
        'name' => $remedy['name'],
        'abbreviation' => $remedy['abbreviation'],
        'materia_medica' => $remedy['materia_medica_text'],
        'clinical_indications' => $remedy['clinical_indications'],
        'modalities' => $modalities,
        'rubric_count' => $rubricCount,
        'prescription_count' => $prescriptionCount
    ]
]);
?>