<?php
session_start();
include 'layouts/dbconn.php';

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

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

// Get form data
$patient_id = isset($_POST['patient_id']) ? (int)$_POST['patient_id'] : 0;
$doctor_id = isset($_POST['doctor_id']) ? (int)$_POST['doctor_id'] : 0;
$slot_id = isset($_POST['slot_id']) ? (int)$_POST['slot_id'] : 0;
$appointment_date = isset($_POST['appointment_date']) ? $_POST['appointment_date'] : '';
$appointment_time = isset($_POST['appointment_time']) ? $_POST['appointment_time'] : '';
$appointment_type = isset($_POST['appointment_type']) ? $_POST['appointment_type'] : 'CONSULTATION';
$booking_source = isset($_POST['booking_source']) ? $_POST['booking_source'] : 'STAFF';
$chief_complaint = isset($_POST['chief_complaint']) ? trim($_POST['chief_complaint']) : '';
$special_requirements = isset($_POST['special_requirements']) ? trim($_POST['special_requirements']) : '';
$estimated_duration = isset($_POST['estimated_duration']) ? (int)$_POST['estimated_duration'] : 30;
$room_number = isset($_POST['room_number']) ? trim($_POST['room_number']) : null;
$status = isset($_POST['status']) ? $_POST['status'] : 'SCHEDULED';
$notes = isset($_POST['notes']) ? trim($_POST['notes']) : null;

// Validate required fields
if (!$patient_id || !$doctor_id || !$appointment_date || !$appointment_time || !$chief_complaint) {
    echo json_encode(['success' => false, 'message' => 'Please fill all required fields']);
    exit();
}

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

try {
    // Generate appointment number
    $year = date('Y');
    $month = date('m');
    $day = date('d');
    
    $number_sql = "SELECT appointment_number FROM appointments 
                   WHERE appointment_number LIKE 'APP-$year$month$day-%' 
                   ORDER BY appointment_id DESC LIMIT 1";
    $number_result = $conn->query($number_sql);
    
    if ($number_result->num_rows > 0) {
        $last_number = $number_result->fetch_assoc()['appointment_number'];
        $last_sequence = (int)substr($last_number, -4);
        $new_sequence = str_pad($last_sequence + 1, 4, '0', STR_PAD_LEFT);
    } else {
        $new_sequence = '0001';
    }
    
    $appointment_number = "APP-$year$month$day-$new_sequence";

    // Insert appointment
    $insert_sql = "INSERT INTO appointments (
                    appointment_number, patient_id, doctor_id, slot_id,
                    appointment_date, appointment_time, appointment_type, booking_source,
                    chief_complaint, special_requirements, estimated_duration, room_number,
                    status, notes
                   ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
    
    $stmt = $conn->prepare($insert_sql);
    $stmt->bind_param('siiissssssisss',
        $appointment_number, $patient_id, $doctor_id, $slot_id,
        $appointment_date, $appointment_time, $appointment_type, $booking_source,
        $chief_complaint, $special_requirements, $estimated_duration, $room_number,
        $status, $notes
    );
    
    if (!$stmt->execute()) {
        throw new Exception('Failed to create appointment');
    }
    
    $appointment_id = $conn->insert_id;

    // Update slot availability
    if ($slot_id > 0) {
        $update_slot_sql = "UPDATE appointment_slots 
                           SET booked_patients = booked_patients + 1,
                               is_available = CASE 
                                   WHEN booked_patients + 1 >= max_patients THEN 0 
                                   ELSE 1 
                               END
                           WHERE slot_id = ?";
        $stmt = $conn->prepare($update_slot_sql);
        $stmt->bind_param('i', $slot_id);
        $stmt->execute();
    }

    // Commit transaction
    $conn->commit();

    echo json_encode([
        'success' => true,
        'message' => "Appointment booked successfully! Appointment number: $appointment_number",
        'appointment_id' => $appointment_id,
        'appointment_number' => $appointment_number
    ]);

} catch (Exception $e) {
    $conn->rollback();
    echo json_encode([
        'success' => false,
        'message' => 'Error: ' . $e->getMessage()
    ]);
}
?>