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

if(isset($_POST['submit'])) {    
    $name = $_POST['patient_name'];
    $age = $_POST['patient_age'];
    $mobile = $_POST['patient_mobile'];
    $address = $_POST['patient_address'];
    $gender = $_POST['patient_gender'];

    // Optional: check for duplicate patient (same name + mobile)
   $check = $conn->query("SELECT patient_id FROM patient WHERE patient_name='$name' AND patient_mobile='$mobile'");
    if($check->num_rows > 0){
        echo "<div class='alert alert-warning mt-2'>This patient already exists.</div>";
    } else {
        $insert = "INSERT INTO patient (patient_name, patient_age, patient_mobile, patient_address, patient_gender) 
                   VALUES ('$name', '$age', '$mobile', '$address', '$gender')";
        if($conn->query($insert)){
            echo "<script>window.location.href='appointment_add.php';</script>";
            exit;
        } else {
            echo "<div class='alert alert-danger mt-2'>Error: " . $conn->error . "</div>";
        }
    }
}

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

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

        <div class="mb-3">
            <label class="form-label">Name</label>
            <input type="text" name="patient_name" class="form-control" required>
        </div>

        <div class="mb-3">
            <label class="form-label">Age</label>
            <input type="number" name="patient_age" class="form-control" required>
        </div>

        <div class="mb-3">
            <label class="form-label">Mobile</label>
            <input type="text" name="patient_mobile" class="form-control" required>
        </div>

        <div class="mb-3">
            <label class="form-label">Address</label>
            <input type="text" name="patient_address" class="form-control" required>
        </div>

        <p>Gender</p>
        <div class="mb-2 form-check">
            <input type="radio" class="form-check-input" name="patient_gender" value="Male" id="male" required>
            <label class="form-check-label" for="male">Male</label>
        </div>
        <div class="mb-2 form-check">
            <input type="radio" class="form-check-input" name="patient_gender" value="Female" id="female" required>
            <label class="form-check-label" for="female">Female</label>
        </div>

        <button type="submit" name="submit" class="btn btn-success" id="submitBtn">Save</button>
        <a href="patient_list.php" class="btn btn-secondary">Cancel</a>
    </form>
</div>

<script>
const form = document.getElementById('patientForm');
const submitBtn = document.getElementById('submitBtn');

form.addEventListener('submit', function(e){
    // Disable button AFTER a tiny delay to allow submission
    setTimeout(function(){
        submitBtn.disabled = true;
    }, 1);
});
</script>

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