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

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $agency_id = $_SESSION['agency_id'];
    
    // Logic: Use client_id if selected, otherwise set to NULL
    $client_id = !empty($_POST['client_id']) ? (int)$_POST['client_id'] : NULL;
    $manual_name = $_POST['manual_client_name'];
    $contact = $_POST['contact_person'];
    
    $voucher_data = [
        'client_display_name' => $manual_name, // Store name directly in JSON
        'options' => $_POST['options'],
        'contact_person' => $contact
    ];
    
    $json_data = json_encode($voucher_data);
    
    // We bind i (int) or NULL for client_id
    $stmt = $conn->prepare("INSERT INTO umrah_vouchers (agency_id, client_id, voucher_data) VALUES (?, ?, ?)");
    $stmt->bind_param("iis", $agency_id, $client_id, $json_data);
    $conn->query("UPDATE agencies SET umrah_used = umrah_used + 1 WHERE id = $agency_id");
    if ($stmt->execute()) {
        header("Location: umrah_vouchers.php?msg=success");
    } else {
        echo "Error: " . $conn->error;
    }
}
?>