<?php
/**
 * File 3: ajax/save_prescription.php
 * Save prescription for patient
 */
session_start();
include '../layouts/dbconn.php';

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

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

$user_id = $_SESSION['user_id'];
$patient_id = $_POST['patient_id'] ?? 0;
$visit_id = $_POST['visit_id'] ?? null;
$doctor_id = $_POST['doctor_id'] ?? $user_id;

// Validate visit_id exists if provided
if ($visit_id) {
    $check_visit = "SELECT visit_id FROM patient_visits WHERE visit_id = ?";
    $stmt = $conn->prepare($check_visit);
    $stmt->bind_param("i", $visit_id);
    $stmt->execute();
    $visit_result = $stmt->get_result();
    
    if ($visit_result->num_rows === 0) {
        $visit_id = null; // Set to null if visit doesn't exist
    }
}

// If no valid visit_id, try to get or create active visit
if (!$visit_id) {
    // Try to find active visit for today
    $active_visit_sql = "SELECT visit_id FROM patient_visits 
                        WHERE patient_id = ? 
                        AND status = 'ACTIVE' 
                        AND DATE(registration_date) = CURDATE()
                        ORDER BY registration_date DESC LIMIT 1";
    $stmt = $conn->prepare($active_visit_sql);
    $stmt->bind_param("i", $patient_id);
    $stmt->execute();
    $active_result = $stmt->get_result();
    
    if ($active_result->num_rows > 0) {
        $visit_id = $active_result->fetch_assoc()['visit_id'];
    } else {
        // Create new visit with unique number
        try {
            $conn->begin_transaction();
            
            // Generate unique visit number
            $count_sql = "SELECT COUNT(*) as count FROM patient_visits WHERE DATE(registration_date) = CURDATE()";
            $count_result = $conn->query($count_sql);
            $count = $count_result->fetch_assoc()['count'];
            
            $visit_number = 'VST-' . date('Ymd') . '-' . str_pad($count + 1, 4, '0', STR_PAD_LEFT);
            
            // Check if visit number exists (in case of race condition)
            $check_number_sql = "SELECT visit_id FROM patient_visits WHERE visit_number = ?";
            $stmt = $conn->prepare($check_number_sql);
            $stmt->bind_param("s", $visit_number);
            $stmt->execute();
            
            if ($stmt->get_result()->num_rows > 0) {
                // Generate a unique number with timestamp
                $visit_number = 'VST-' . date('Ymd') . '-' . time() . '-' . $patient_id;
            }
            
            $create_visit = "INSERT INTO patient_visits (visit_number, patient_id, visit_type, registration_date, status, created_at)
                            VALUES (?, ?, 'OUT_PATIENT', NOW(), 'ACTIVE', NOW())";
            $stmt = $conn->prepare($create_visit);
            $stmt->bind_param("si", $visit_number, $patient_id);
            
            if (!$stmt->execute()) {
                throw new Exception("Failed to create visit");
            }
            
            $visit_id = $conn->insert_id;
            $conn->commit();
            
        } catch (Exception $e) {
            $conn->rollback();
            echo json_encode([
                'success' => false,
                'message' => 'Failed to create visit: ' . $e->getMessage()
            ]);
            exit();
        }
    }
}

// Prescription details
$medication_name = trim($_POST['medication_name'] ?? '');
$dosage = trim($_POST['dosage'] ?? '');
$frequency = trim($_POST['frequency'] ?? '');
$route = $_POST['route'] ?? 'ORAL';
$duration = trim($_POST['duration'] ?? '');
$quantity = trim($_POST['quantity'] ?? '');
$instructions = trim($_POST['instructions'] ?? '');
$indication = trim($_POST['indication'] ?? '');

// Validation
if (empty($medication_name) || empty($dosage) || empty($frequency) || empty($duration)) {
    echo json_encode([
        'success' => false,
        'message' => 'Please fill all required fields'
    ]);
    exit();
}

try {
    $conn->begin_transaction();
    
    // Generate prescription number using function if available
    $rx_number_sql = "SELECT CONCAT('RX-', DATE_FORMAT(NOW(), '%Y%m%d'), '-', LPAD((SELECT COUNT(*) + 1 FROM prescriptions WHERE DATE(prescribed_date) = CURDATE()), 4, '0')) as rx_number";
    $rx_number_result = $conn->query($rx_number_sql);
    $prescription_number = $rx_number_result->fetch_assoc()['rx_number'];
    
    $insert_sql = "INSERT INTO prescriptions (
        prescription_number, patient_id, doctor_id, visit_id,
        medication_name, dosage, frequency, route, duration,
        quantity, instructions, indication,
        prescribed_date, status
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CURDATE(), 'ACTIVE')";
    
    $stmt = $conn->prepare($insert_sql);
    $stmt->bind_param("siiissssssss",
        $prescription_number, $patient_id, $doctor_id, $visit_id,
        $medication_name, $dosage, $frequency, $route, $duration,
        $quantity, $instructions, $indication
    );
    
    if (!$stmt->execute()) {
        throw new Exception("Failed to save prescription: " . $stmt->error);
    }
    
    $prescription_id = $conn->insert_id;
    
    // Update patient visit with prescription info if needed
    $update_visit_sql = "UPDATE patient_visits 
                        SET updated_at = NOW()
                        WHERE visit_id = ?";
    $stmt = $conn->prepare($update_visit_sql);
    $stmt->bind_param("i", $visit_id);
    $stmt->execute();
    
    // Log activity
    $activity_sql = "INSERT INTO activity_log (user_id, action, module, record_id, record_type, ip_address, logged_at)
                    VALUES (?, 'CREATE', 'PRESCRIPTION', ?, 'PRESCRIPTION', ?, NOW())";
    $ip_address = $_SERVER['REMOTE_ADDR'];
    $stmt = $conn->prepare($activity_sql);
    $stmt->bind_param("iis", $user_id, $prescription_id, $ip_address);
    $stmt->execute();
    
    $conn->commit();
    
    echo json_encode([
        'success' => true,
        'message' => 'Prescription created successfully',
        'prescription_id' => $prescription_id,
        'prescription_number' => $prescription_number,
        'visit_id' => $visit_id
    ]);
    
} catch (Exception $e) {
    $conn->rollback();
    echo json_encode([
        'success' => false,
        'message' => 'Failed to save prescription: ' . $e->getMessage()
    ]);
}
?>