<?php
include 'config.php';
if(!isset($_SESSION['user_id'])) exit();

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $agency_id = $_SESSION['agency_id'];
    
    // Check if client was selected from DB, otherwise set to NULL
    $client_id = !empty($_POST['client_id']) ? (int)$_POST['client_id'] : NULL;
    $manual_name = $_POST['manual_client_name'];
    
    $voucher_data = [
        'client_display_name' => $manual_name,
        'contact_person' => $_POST['contact_person'],
        'flight_options' => $_POST['options'] ?? []
    ];
    
    $json_data = json_encode($voucher_data);
    
    $stmt = $conn->prepare("INSERT INTO ticket_vouchers (agency_id, client_id, voucher_data) VALUES (?, ?, ?)");
    $stmt->bind_param("iis", $agency_id, $client_id, $json_data);
    $conn->query("UPDATE agencies SET tickets_used = tickets_used + 1 WHERE id = $agency_id");
    if ($stmt->execute()) {
        header("Location: ticket_vouchers.php?status=success");
    } else {
        echo "Error: " . $conn->error;
    }
}
?>