<?php
require_once $_SERVER['DOCUMENT_ROOT'] . '/config.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $conn = get_db_connection();

    $fname = $conn->real_escape_string($_POST['fname']);
    $lname = $conn->real_escape_string($_POST['lname']);
    $phone = $conn->real_escape_string($_POST['phone']);
    $email = $conn->real_escape_string($_POST['email']);
    $service = $conn->real_escape_string($_POST['service']);
    $date = $conn->real_escape_string($_POST['date']);
    $time = $conn->real_escape_string($_POST['time']);
    $address = $conn->real_escape_string($_POST['address']);

    // Check if table exists, if not create it (failsafe)
    $conn->query("CREATE TABLE IF NOT EXISTS `appointments` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `first_name` varchar(100) NOT NULL,
        `last_name` varchar(100) NOT NULL,
        `phone` varchar(20) NOT NULL,
        `email` varchar(100) NOT NULL,
        `service` varchar(255) NOT NULL,
        `appointment_date` date NOT NULL,
        `appointment_time` time NOT NULL,
        `address` text NOT NULL,
        `status` enum('pending', 'confirmed', 'completed', 'cancelled') DEFAULT 'pending',
        `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;");

    $sql = "INSERT INTO appointments (first_name, last_name, phone, email, service, appointment_date, appointment_time, address) 
            VALUES ('$fname', '$lname', '$phone', '$email', '$service', '$date', '$time', '$address')";

    if ($conn->query($sql)) {
        // Redirect to success page
        header("Location: /appointment-success.php");
        exit();
    } else {
        die("Error: " . $conn->error);
    }
} else {
    header("Location: /");
    exit();
}
?>