<?php
require '../connection/conn.php';

if(isset($_POST['add'])) {    
    $p_id = $_POST['patient_id'];
    $date = $_POST['appointment_date'];
    $price = $_POST['appointment_price'];
    $selected_ops = isset($_POST['appointment_operation']) ? $_POST['appointment_operation'] : [];
    $operations_string = implode(', ', $selected_ops);

    if($p_id == '') {
        echo "<div class='alert alert-danger mt-2'>Please select a valid patient from the list.</div>";
    } else {
        // Optional: prevent duplicate appointments
        $check = $conn->query("
            SELECT appointment_id FROM appointment
            WHERE appointment_patient = '$p_id'
            AND appointment_date = '$date'
            AND appointment_operation = '$operations_string'
        ");

        if($check->num_rows > 0){
            echo "<div class='alert alert-warning mt-2'>This appointment already exists.</div>";
        } else {
            $insert = "INSERT INTO appointment (`appointment_patient`, `appointment_operation`, `appointment_date`, `appointment_price`) 
                       VALUES ('$p_id', '$operations_string', '$date', '$price')";
            if($conn->query($insert)){
                echo "<script>window.location.href='index.php';</script>";
                exit;
            } else {
                echo "<div class='alert alert-danger mt-2'>Error: " . $conn->error . "</div>";
            }
        }
    }
}

$patients_res = $conn->query("SELECT * FROM patient ORDER BY patient_name ASC");
$operations_res = $conn->query("SELECT * FROM operation");

$patients = [];
while($p = mysqli_fetch_array($patients_res)){
    $patients[] = $p;
}

require "../includes/header.php";
?>

<div class="container mt-4">
    <h2 class="mb-4">Add Appointment</h2>
    <form method="POST" id="appointmentForm">

        <div class="mb-3 position-relative">
            <label class="form-label">Patient Name</label>
            <input type="text" autocomplete="off" id="patient_search" class="form-control" placeholder="Type patient name..." autofocus required>
            <input type="hidden" name="patient_id" id="patient_id">
            <div id="suggestions" class="border bg-white position-absolute w-100" style="max-height:150px; overflow-y:auto; z-index:1000; display:none;"></div>
        </div>

        <div class="mb-3">
            <label class="form-label">Operations</label>
            <select name="appointment_operation[]" class="form-select" multiple required>
                <?php while($op = mysqli_fetch_array($operations_res)) { ?>
                    <option value="<?php echo $op['operation_name']; ?>"><?php echo $op['operation_name']; ?></option>
                <?php } ?>
            </select>
            <small class="form-text text-muted">Hold Ctrl (or Cmd) to select multiple operations</small>
        </div>

        <div class="mb-3">
            <label class="form-label">Date</label>
            <input type="date" name="appointment_date" class="form-control" required>
        </div>

        <div class="mb-3">
            <label class="form-label">Price (IQD)</label>
            <input type="number" name="appointment_price" class="form-control" placeholder="Enter price in IQD" required>
        </div>

        <button type="submit" name="add" class="btn btn-primary" id="submitBtn">Add Appointment</button>
        <a href="index.php" class="btn btn-secondary">Cancel</a>
    </form>
</div>

<script>
const patients = <?php echo json_encode($patients); ?>;
const input = document.getElementById('patient_search');
const hiddenId = document.getElementById('patient_id');
const suggestions = document.getElementById('suggestions');
const form = document.getElementById('appointmentForm');
const submitBtn = document.getElementById('submitBtn');

// Patient search autocomplete
input.addEventListener('input', function(){
    const val = input.value.toLowerCase();
    suggestions.innerHTML = '';
    if(val.length === 0){
        suggestions.style.display = 'none';
        hiddenId.value = '';
        return;
    }
    const matches = patients.filter(p => p.patient_name.toLowerCase().includes(val));
    if(matches.length > 0){
        matches.forEach(p => {
            const div = document.createElement('div');
            div.textContent = p.patient_name;
            div.classList.add('p-2');
            div.style.cursor = 'pointer';
            div.addEventListener('click', () => {
                input.value = p.patient_name;
                hiddenId.value = p.patient_id;
                suggestions.style.display = 'none';
            });
            suggestions.appendChild(div);
        });
        suggestions.style.display = 'block';
    } else {
        suggestions.style.display = 'none';
        hiddenId.value = '';
    }
});

// Hide suggestions when clicking outside
document.addEventListener('click', function(e){
    if(!suggestions.contains(e.target) && e.target !== input){
        suggestions.style.display = 'none';
    }
});

// Form submit: validate patient & prevent double click
form.addEventListener('submit', function(e){
    if(hiddenId.value === ''){
        alert('Please select a valid patient from the list.');
        e.preventDefault();
        return;
    }
    
    // Disable button AFTER a tiny delay to allow submission
    setTimeout(function(){
        submitBtn.disabled = true;
    }, 1);
});
</script>

<?php require "../includes/footer.php"; ?>
