<?php
session_start();
header('Content-Type: application/json');
include '../layouts/dbconn.php';

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

$drug_a = isset($_POST['drug_a']) ? trim($_POST['drug_a']) : '';
$drug_b = isset($_POST['drug_b']) ? trim($_POST['drug_b']) : '';

if (empty($drug_a) || empty($drug_b)) {
    echo json_encode(['success' => false, 'message' => 'Both drug names required']);
    exit();
}

// Check database for known interactions
$sql = "SELECT * FROM drug_interactions 
        WHERE (
            (LOWER(drug_a) = LOWER(?) AND LOWER(drug_b) = LOWER(?)) OR
            (LOWER(drug_a) = LOWER(?) AND LOWER(drug_b) = LOWER(?))
        )
        AND is_active = 1";

$stmt = $conn->prepare($sql);
$stmt->bind_param("ssss", $drug_a, $drug_b, $drug_b, $drug_a);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows > 0) {
    $interactions = [];
    while ($row = $result->fetch_assoc()) {
        $interactions[] = [
            'interaction_type' => $row['interaction_type'],
            'severity_level' => $row['severity_level'],
            'description' => $row['interaction_description'],
            'clinical_effects' => $row['clinical_effects'],
            'management_strategy' => $row['management_strategy'],
            'alternative_medications' => json_decode($row['alternative_medications'], true)
        ];
    }
    
    echo json_encode([
        'success' => true,
        'has_interaction' => true,
        'interactions' => $interactions
    ]);
} else {
    // No interaction found in database
    echo json_encode([
        'success' => true,
        'has_interaction' => false,
        'message' => 'No known interactions found in database'
    ]);
}

$conn->close();
?>