<?php
/**
 * save_appointment.php
 * Save a new appointment with autonomous price calculation.
 */

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once __DIR__ . '/../../dripend/includes/db.php';

// ----------------------------
// Helper function to sanitize inputs
// ----------------------------
function clean($data) {
    return htmlspecialchars(trim($data));
}

// ----------------------------
// Fetch POST inputs
// ----------------------------
$appointment_id   = clean($_POST['appointment_id'] ?? '');
$appointment_date = clean($_POST['appointment_date'] ?? '');
$appointment_time = clean($_POST['appointment_time'] ?? '');
$appointment_type = clean($_POST['appointment_type'] ?? null); // integer ID
$doctor_id        = clean($_POST['doctor_id'] ?? null);
$department_id    = clean($_POST['department_id'] ?? null);
$service_code     = clean($_POST['service_request'] ?? null); // GDRG CODE
$ccc              = clean($_POST['ccc_code'] ?? null);
$notes            = clean($_POST['notes'] ?? '');
$patient_no       = clean($_POST['patient_no'] ?? null);
















// ----------------------------
// Validate required fields
// ----------------------------
$errors = [];
if (!$appointment_id)   $errors[] = 'Appointment ID is missing.';
if (!$appointment_date) $errors[] = 'Appointment date is required.';
if (!$appointment_time) $errors[] = 'Appointment time is required.';
if (!$department_id)    $errors[] = 'Department selection is required.';
if (!$service_code)     $errors[] = 'Service request is required.';
if (!$patient_no)       $errors[] = 'Patient is not selected.';

if ($errors) {
    echo json_encode(['status' => 'error', 'message' => implode(' ', $errors)]);
    exit;
}

// ----------------------------
// Fetch patient insurance info
// ----------------------------
$stmt = $conn->prepare("
    SELECT nhis_no, other_insurance_no
    FROM patient
    WHERE patient_no = ?
    LIMIT 1
");
$stmt->bind_param("s", $patient_no);
$stmt->execute();
$patient = $stmt->get_result()->fetch_assoc();
$stmt->close();

$other_insurance_no = $patient['other_insurance_no'] ?? null;

// ----------------------------
// Appointment type validation
// ----------------------------
$appointmentTypeMap = [
    1 => 'Initial Consultation',
    2 => 'Follow Up',
    3 => 'Emergency'
];

if (!isset($appointmentTypeMap[$appointment_type])) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid appointment type']);
    exit;
}

$appointment_type_id = (int)$appointment_type;

// ----------------------------
// Fetch GDRG details (THIS IS THE FIX)
// ----------------------------
$stmt = $conn->prepare("
    SELECT gdrg_name, base_price, co_payment
    FROM gdrg
    WHERE gdrg_code = ?
    LIMIT 1
");
$stmt->bind_param("s", $service_code);
$stmt->execute();
$gdrg = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$gdrg) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid service selected']);
    exit;
}

$service_request = $gdrg['gdrg_name']; // HUMAN READABLE NAME
$base_price      = (float)$gdrg['base_price'];
$copay           = (float)$gdrg['co_payment'];

// ----------------------------
// Price calculation (UNCHANGED)
// ----------------------------
$total_app_amount = $base_price;

if ($other_insurance_no) {
    $stmt = $conn->prepare("
        SELECT co_payment
        FROM private_insurance_gdrg_pricing
        WHERE insurance_no = ? AND gdrg_code = ?
        LIMIT 1
    ");
    $stmt->bind_param("ss", $other_insurance_no, $service_code);
    $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    if ($row) {
        $total_app_amount = (float)$row['co_payment'];
    }
} elseif ($ccc && preg_match('/^\d{5}$/', $ccc)) {
    $total_app_amount = $copay;
}







// ----------------------------
// Resolve default appointment status (PENDING)
// ----------------------------
$stmt = $conn->prepare("
    SELECT status_id
    FROM appointment_status
    WHERE status_code = 'PENDING'
    LIMIT 1
");
$stmt->execute();
$statusRow = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$statusRow) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Default appointment status not configured'
    ]);
    exit;
}

$default_status_id = (int)$statusRow['status_id'];









// ----------------------------
// Insert appointment (FIXED)
// ----------------------------
$stmt = $conn->prepare("
    INSERT INTO appointment
    (
        appointment_id,
        appointment_date,
        appointment_time,
        appointment_type,
        doctor_id,
        clinic_department_id,
        service_request,
        ccc,
        notes,
        patient_no,
        total_app_amount,
        status,
        created_at
    )
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())
");

$stmt->bind_param(
    "sssiiissssdi",
    $appointment_id,
    $appointment_date,
    $appointment_time,
    $appointment_type_id,
    $doctor_id,
    $department_id,
    $service_request,
    $ccc,
    $notes,
    $patient_no,
    $total_app_amount,
    $default_status_id
);

if ($stmt->execute()) {

    // Store minimal success context in session
    session_start();
    $_SESSION['appointment_success'] = [
        'appointment_id'  => $appointment_id,
        'service_request' => $service_request,
        'total_amount'    => number_format($total_app_amount, 2)
    ];

    header("Location: success_appointment.php");
    exit;
}
 else {
    echo json_encode([
        'status' => 'error',
        'message' => $stmt->error
    ]);
}

$stmt->close();
$conn->close();



?>
