<?php
// Prevent any output before JSON
ob_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);

require_once '../layouts/session.php';
require_once '../layouts/dbconn.php';

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

try {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        throw new Exception('Invalid request method');
    }

    // Get input data
    $visit_id = isset($_POST['visit_id']) ? intval($_POST['visit_id']) : 0;
    $patient_id = isset($_POST['patient_id']) ? intval($_POST['patient_id']) : 0;
    $doctor_id = isset($_POST['doctor_id']) ? intval($_POST['doctor_id']) : 0;

    if (!$visit_id || !$patient_id) {
        throw new Exception('Missing required IDs');
    }

    // Generate Consultation Number
    $consultation_number = 'CONS-' . date('Ymd-His') . '-' . rand(1000, 9999);

    // Prepare JSON fields
    $json_fields = [
        'ear_examination',
        'nose_examination',
        'throat_examination',
        'neck_examination',
        'cranial_nerves',
        'medications_prescribed',
        'procedures_recommended',
        'investigations_ordered',
        'referrals'
    ];

    $json_data = [];
    foreach ($json_fields as $field) {
        $data = isset($_POST[$field]) ? $_POST[$field] : null;
        if (is_string($data)) {
            json_decode($data);
            if (json_last_error() === JSON_ERROR_NONE) {
                $json_data[$field] = $data;
            } else {
                $json_data[$field] = null;
            }
        } else {
            $json_data[$field] = null;
        }
    }

    // Prepare text fields
    $consultation_type = $_POST['consultation_type'] ?? 'INITIAL';
    $chief_complaint = $_POST['chief_complaint'] ?? '';
    $history_present_illness = $_POST['history_present_illness'] ?? '';
    $past_medical_history = $_POST['past_medical_history'] ?? '';
    $family_history = $_POST['family_history'] ?? '';
    $social_history = $_POST['social_history'] ?? '';
    $general_examination = $_POST['general_examination'] ?? '';
    $diagnosis_primary = $_POST['diagnosis_primary'] ?? '';
    $diagnosis_secondary = $_POST['diagnosis_secondary'] ?? '';
    $differential_diagnosis = $_POST['differential_diagnosis'] ?? '';
    $treatment_plan = $_POST['treatment_plan'] ?? '';
    $follow_up_instructions = $_POST['follow_up_instructions'] ?? '';
    $next_appointment = !empty($_POST['next_appointment']) ? $_POST['next_appointment'] : null;
    $doctor_notes = $_POST['doctor_notes'] ?? '';
    $status = $_POST['status'] ?? 'COMPLETED';

    $consultation_fee = isset($_POST['consultation_fee']) ? floatval($_POST['consultation_fee']) : 0.00;
    $doctor_commission = isset($_POST['doctor_commission']) ? floatval($_POST['doctor_commission']) : 0.00;

    // Start Transaction
    $conn->begin_transaction();

    // Insert into consultations
    $sql = "INSERT INTO consultations (
        consultation_number, visit_id, patient_id, doctor_id, consultation_type,
        chief_complaint, history_present_illness, past_medical_history, family_history, social_history,
        ear_examination, nose_examination, throat_examination, neck_examination, cranial_nerves,
        general_examination, diagnosis_primary, diagnosis_secondary, differential_diagnosis,
        treatment_plan, medications_prescribed, procedures_recommended, investigations_ordered, referrals,
        follow_up_instructions, next_appointment, doctor_notes, consultation_fee, doctor_commission,
        status, completed_at
    ) VALUES (
        ?, ?, ?, ?, ?,
        ?, ?, ?, ?, ?,
        ?, ?, ?, ?, ?,
        ?, ?, ?, ?,
        ?, ?, ?, ?, ?,
        ?, ?, ?, ?, ?,
        ?, NOW()
    )";

    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        throw new Exception("Prepare failed: " . $conn->error);
    }

    // Bind parameters once
    $stmt->bind_param(
        "siiisssssssssssssssssssssssdds", // 30 characters for 30 variables
        $consultation_number,
        $visit_id,
        $patient_id,
        $doctor_id,
        $consultation_type,
        $chief_complaint,
        $history_present_illness,
        $past_medical_history,
        $family_history,
        $social_history,
        $json_data['ear_examination'],
        $json_data['nose_examination'],
        $json_data['throat_examination'],
        $json_data['neck_examination'],
        $json_data['cranial_nerves'],
        $general_examination,
        $diagnosis_primary,
        $diagnosis_secondary,
        $differential_diagnosis,
        $treatment_plan,
        $json_data['medications_prescribed'],
        $json_data['procedures_recommended'],
        $json_data['investigations_ordered'],
        $json_data['referrals'],
        $follow_up_instructions,
        $next_appointment,
        $doctor_notes,
        $consultation_fee,
        $doctor_commission,
        $status
    );

    if (!$stmt->execute()) {
        throw new Exception("Execute failed: " . $stmt->error);
    }

    $consultation_id = $conn->insert_id;

    // Update patient_visits status
    // Use 'status' column instead of 'visit_status'
    $update_visit = "UPDATE patient_visits SET
                     status = ?,
                     notes = ?
                     WHERE visit_id = ?";

    $visit_status = ($status === 'COMPLETED') ? 'DISCHARGED' : 'IN_PROGRESS';
    $visit_stmt = $conn->prepare($update_visit);
    $visit_stmt->bind_param("ssi", $visit_status, $doctor_notes, $visit_id);
    $visit_stmt->execute();

    $conn->commit();

    // Clean output buffer to ensure valid JSON
    ob_clean();

    echo json_encode([
        'success' => true,
        'message' => 'Consultation saved successfully',
        'consultation_id' => $consultation_id,
        'consultation_number' => $consultation_number
    ]);

} catch (Exception $e) {
    if (isset($conn) && $conn->in_transaction) {
        $conn->rollback();
    }

    ob_clean();
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>