<?php
require_once 'config/config.php';
session_start();

// التحقق من تسجيل الدخول
if (!isset($_SESSION['user_id'])) {
    header("Location: auth/login.php");
    exit;
}

$success = "";
$error = "";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $issued = isset($_POST['issued']) ? 1 : 0;
    $issue_date = $issued ? ($_POST['issue_date'] ?? null) : null;
    $travel_date = $_POST['travel_date'] ?? null;
    $booking_nas_go = $_POST['booking_nas_go'] ?? null;
    $booking_nas_return = $_POST['booking_nas_return'] ?? null;
    $passenger_name = $_POST['passenger_name'] ?? null;

    $stmt = $conn->prepare("INSERT INTO transit_visas (issued, issue_date, travel_date, booking_nas_go, booking_nas_return, passenger_name) VALUES (?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("isssss", $issued, $issue_date, $travel_date, $booking_nas_go, $booking_nas_return, $passenger_name);

    if ($stmt->execute()) {
        $success = $lang['visa_saved'];
    } else {
        $error = $lang['visa_failed'];
    }
}
?>

<?php include 'header.php'; ?>
<div class="main-content p-4" style="flex:1;">
    <h2><?= $lang['add_transit_visa'] ?></h2>

    <?php if ($success): ?><div class="alert alert-success"><?= $success ?></div><?php endif; ?>
    <?php if ($error): ?><div class="alert alert-danger"><?= $error ?></div><?php endif; ?>

    <form method="POST">
                <div class="mb-3">
            <label class="form-label"><?= $lang['passenger_name'] ?></label>
            <input type="text" name="passenger_name" class="form-control" required>
        </div>
        
        <div class="form-check mb-3">
            <input class="form-check-input" type="checkbox" name="issued" id="issued" onclick="toggleIssueDate()">
            <label class="form-check-label" for="issued"><?= $lang['visa_issued'] ?></label>
        </div>

        <div class="mb-3" id="issueDateField" style="display:none;">
            <label class="form-label"><?= $lang['issue_date'] ?></label>
            <input type="date" name="issue_date" class="form-control">
        </div>

        <div class="mb-3">
            <label class="form-label"><?= $lang['travel_date'] ?></label>
            <input type="date" name="travel_date" class="form-control">
        </div>

        <div class="mb-3">
            <label class="form-label"><?= $lang['booking_nas_go'] ?></label>
            <input type="text" name="booking_nas_go" class="form-control">
        </div>

        <div class="mb-3">
            <label class="form-label"><?= $lang['booking_nas_return'] ?></label>
            <input type="text" name="booking_nas_return" class="form-control">
        </div>



        <button type="submit" class="btn btn-success"><?= $lang['save'] ?></button>
    </form>
</div>

<script>
function toggleIssueDate() {
    document.getElementById('issueDateField').style.display =
        document.getElementById('issued').checked ? 'block' : 'none';
}
</script>

<?php include 'includes/footer.php'; ?>
