<?php
include 'layouts/session.php';
include 'layouts/dbconn.php';

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

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $conn->begin_transaction();
    try {
        // Validate required fields
        $requiredFields = ['salutation', 'customer_name', 'ticket_ref', 'booking_class', 'airline',
                          'flight_route', 'flight_date', 'ticket_cost', 'agency_fee'];
        
        foreach ($requiredFields as $field) {
            if (!isset($_POST[$field]) || empty($_POST[$field])) {
                throw new Exception("Missing required field: " . $field);
            }
        }

        // Sanitize and validate input data
        $salutation = filter_var($_POST['salutation'], FILTER_SANITIZE_STRING);
        $customerName = filter_var($_POST['customer_name'], FILTER_SANITIZE_STRING);
        $ticketRef = filter_var($_POST['ticket_ref'], FILTER_SANITIZE_STRING);
        $bookingClass = filter_var($_POST['booking_class'], FILTER_SANITIZE_STRING);
        $airline = filter_var($_POST['airline'], FILTER_SANITIZE_STRING);
        $flightRoute = filter_var($_POST['flight_route'], FILTER_SANITIZE_STRING);
        $currency = filter_var($_POST['currency'], FILTER_SANITIZE_STRING);
        $flightDate = $_POST['flight_date'];
        $ticketCost = filter_var($_POST['ticket_cost'], FILTER_VALIDATE_FLOAT);
        $agencyFee = filter_var($_POST['agency_fee'], FILTER_VALIDATE_FLOAT);
        $bookingId = !empty($_POST['booking_id']) ? filter_var($_POST['booking_id'], FILTER_VALIDATE_INT) : null;

        // Validate flight route format (XXX-XXX)
        if (!preg_match('/^[A-Z]{3}-[A-Z]{3}$/', $flightRoute)) {
            throw new Exception("Invalid flight route format. Please use format: XXX-XXX");
        }

        // Check for duplicate ticket reference
        $checkStmt = $conn->prepare("SELECT ticket_id FROM ticket_details WHERE ticket_ref = ?");
        $checkStmt->bind_param("s", $ticketRef);
        $checkStmt->execute();
        if ($checkStmt->get_result()->num_rows > 0) {
            throw new Exception("Ticket reference already exists.");
        }
        $checkStmt->close();

        // If booking ID is provided, verify it exists and is valid
        if ($bookingId) {
            $bookingStmt = $conn->prepare("SELECT booking_id FROM bookings WHERE booking_id = ? AND status = 'Booked'");
            $bookingStmt->bind_param("i", $bookingId);
            $bookingStmt->execute();
            if ($bookingStmt->get_result()->num_rows === 0) {
                throw new Exception("Invalid or non-existent booking reference.");
            }
            $bookingStmt->close();
        }

        // Insert the ticket
        $stmt = $conn->prepare("INSERT INTO ticket_details (
            salutation, customer_name, ticket_ref, booking_class, airline, flight_route,
            flight_date, ticket_cost, agency_fee, booking_id, currency
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

        $stmt->bind_param("sssssssddis",
            $salutation,
            $customerName,
            $ticketRef,
            $bookingClass,
            $airline,
            $flightRoute,
            $flightDate,
            $ticketCost,
            $agencyFee,
            $bookingId,
            $currency
        );

        if (!$stmt->execute()) {
            throw new Exception("Error saving ticket: " . $stmt->error);
        }

        $ticketId = $conn->insert_id;
        $stmt->close();

        $conn->commit();
        
        // Update the success response in save_ticket.php
        echo json_encode([
            'status' => 'success',
            'message' => 'Ticket saved successfully!',
            'ticket_id' => $ticketId,
            'redirect' => 'all_new_tickets.php'  // Changed redirection URL
        ]);

    } catch (Exception $e) {
        $conn->rollback();
        echo json_encode([
            'status' => 'error',
            'message' => $e->getMessage()
        ]);
    }
}

$conn->close();
?>