<?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 = ['ticket_id', 'salutation', 'customer_name', 'booking_class', 
                          '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
        $ticketId = filter_var($_POST['ticket_id'], FILTER_VALIDATE_INT);
        $salutation = filter_var($_POST['salutation'], FILTER_SANITIZE_STRING);
        $customerName = filter_var($_POST['customer_name'], FILTER_SANITIZE_STRING);
        $bookingClass = filter_var($_POST['booking_class'], FILTER_SANITIZE_STRING);
        $flightRoute = filter_var($_POST['flight_route'], 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
        if (!preg_match('/^[A-Z]{3}-[A-Z]{3}$/', $flightRoute)) {
            throw new Exception("Invalid flight route format. Please use format: XXX-XXX");
        }

        // Check if ticket exists and is active
        $checkStmt = $conn->prepare("SELECT status FROM ticket_details WHERE ticket_id = ?");
        $checkStmt->bind_param("i", $ticketId);
        $checkStmt->execute();
        $result = $checkStmt->get_result();
        
        if ($result->num_rows === 0) {
            throw new Exception("Ticket not found.");
        }
        
        $ticket = $result->fetch_assoc();
        if ($ticket['status'] !== 'Active') {
            throw new Exception("Only active tickets can be updated.");
        }
        
        $checkStmt->close();

        // Update the ticket
        $stmt = $conn->prepare("UPDATE ticket_details SET 
            salutation = ?,
            customer_name = ?,
            booking_class = ?,
            flight_route = ?,
            flight_date = ?,
            ticket_cost = ?,
            agency_fee = ?,
            booking_id = ?,
            updated_date = CURRENT_TIMESTAMP
            WHERE ticket_id = ?");

        $stmt->bind_param("sssssddii",
            $salutation,
            $customerName,
            $bookingClass,
            $flightRoute,
            $flightDate,
            $ticketCost,
            $agencyFee,
            $bookingId,
            $ticketId
        );

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

        $stmt->close();
        $conn->commit();

        echo json_encode([
            'status' => 'success',
            'message' => 'Ticket updated successfully!',
            'ticket_id' => $ticketId
        ]);

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

$conn->close();
?>