<?php
require_once 'config/config.php';
$success = '';
$error = '';
session_start();



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

$generated_booking_number = generateBookingNumber();

function generateBookingNumber() {
    $letters = strtoupper(substr(str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ'), 0, 2));
    $numbers = str_pad(rand(0, 9999), 4, '0', STR_PAD_LEFT);
    return $letters . $numbers;
}

// جلب الشروط من قاعدة البيانات لاستخدامها في العرض
$termsContent = '';
$termsResult = $conn->query("SELECT content FROM terms_conditions LIMIT 1");
if ($termsResult && $termsResult->num_rows > 0) {
    $termsContent = $termsResult->fetch_assoc()['content'];
}




// Customer Names (دمج كل الأسماء)
$customer_names = isset($_POST['customer_name']) ? implode(' | ', $_POST['customer_name']) : '';

// Remarks
$remarks = $_POST['remarks'] ?? null;

// Company Logo
$company_logo = null;
if (!empty($_FILES['company_logo']['name'])) {
    $uploadDir = "uploads/logos/";
    if (!is_dir($uploadDir)) mkdir($uploadDir, 0777, true);
    $targetFile = $uploadDir . time() . "_logo.jpg";

    // تصغير الصورة 200x200
    $source = imagecreatefromstring(file_get_contents($_FILES['company_logo']['tmp_name']));
    $resized = imagescale($source, 200, 200);
    imagejpeg($resized, $targetFile);
    imagedestroy($source);
    imagedestroy($resized);

    $company_logo = $targetFile;
}


if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $hotel_name       = $_POST['hotel_name'];
    $check_in_date    = $_POST['check_in_date'];
    $check_out_date   = $_POST['check_out_date'];
    $city             = $_POST['city'];
$booking_number = $_POST['booking_number'];
    $room_type        = $_POST['room_type'];
    $rooms_count      = $_POST['rooms_count'];
    $guests_per_room  = $_POST['guests_per_room'];
    $status = $_POST['status'];
    $hotel_confirmation_number = $_POST['hotel_confirmation_number'] ?? null;
    $view = $_POST['view'] ?? '';
    $meal_plan = $_POST['meal_plan'] ?? '';

$room_level = $_POST['room_level'] ?? '';

    $customer_name    = $_POST['customer_name'];
    $entered_by       = $_SESSION['user_id'];
    $terms            = $termsContent; // استخدم الشروط من قاعدة البيانات

    $date1 = new DateTime($check_in_date);
    $date2 = new DateTime($check_out_date);
    $nights = $date1->diff($date2)->days;

$stmt = $conn->prepare("INSERT INTO vouchers (
    hotel_name, check_in_date, check_out_date, nights, city, booking_number, hotel_confirmation_number,
    room_type, rooms_count, guests_per_room, customer_name, voucher_date, entered_by, terms, status, view, room_level, meal_plan,
    remarks, company_logo
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CURDATE(), ?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param("sssissssiisisssssss",
    $hotel_name, $check_in_date, $check_out_date, $nights, $city, $booking_number, $hotel_confirmation_number,
    $room_type, $rooms_count, $guests_per_room, $customer_names,
    $entered_by, $terms, $status, $view, $room_level, $meal_plan,
    $remarks, $company_logo
);

    if ($stmt->execute()) {
        $_SESSION['success_id'] = $conn->insert_id;
        header("Location: index.php");
        exit;
    } else {
        $error = $lang['voucher_failed'];
    }
}

// عرض الرسالة بعد إعادة التوجيه
if (isset($_SESSION['success_id'])) {
    $success = $lang['voucher_saved'];
    $download_id = $_SESSION['success_id'];
    unset($_SESSION['success_id']);
}
?>

<?php include 'header.php'; ?>
<div class="main-content p-4" style="flex: 1;">

<h2 class="mb-4"><?= $lang['add_voucher'] ?></h2>

<?php if ($error): ?>
    <div class="alert alert-danger"><?= $error ?></div>
<?php elseif ($success): ?>
    <div class="alert alert-success">
        <?= $success ?><br>
        <a href="generate_pdf.php?id=<?= $download_id ?>" class="btn btn-primary mt-2"><?= $lang['download'] ?> PDF</a>
    </div>
<?php endif; ?>

<form method="POST" enctype="multipart/form-data">

    <!-- ========================== قسم الفندق والمدخلات الأساسية ========================== -->
    <div class="row mb-3">
        <div class="col-md-3">
            <label class="form-label"><?= $lang['hotel_name'] ?></label>
            <input type="text" name="hotel_name" class="form-control" required>
        </div>
        <div class="col-md-3">
            <label class="form-label"><?= $lang['city'] ?></label>
            <input type="text" name="city" class="form-control" required>
        </div>
        <div class="col-md-3">
            <label class="form-label"><?= $lang['check_in'] ?></label>
            <input type="date" name="check_in_date" class="form-control" required>
        </div>
        <div class="col-md-3">
            <label class="form-label"><?= $lang['check_out'] ?></label>
            <input type="date" name="check_out_date" class="form-control" required>
        </div>
    </div>

    <!-- ========================== قسم الغرف والضيوف + أسماء العملاء ========================== -->
    <div class="row mb-3">
        <div class="col-md-3">
            <label class="form-label"><?= $lang['rooms_count'] ?></label>
            <input type="number" name="rooms_count" class="form-control" required>
        </div>
        <div class="col-md-3">
            <label class="form-label"><?= $lang['guests_per_room'] ?></label>
            <input type="number" name="guests_per_room" class="form-control" required>
        </div>
        <!-- Customer Name مع إضافة وحذف -->
        <div class="col-md-3" id="customerNameContainer">
            <label class="form-label"><?= $lang['customer_name'] ?></label>
            <div class="input-group mb-2">
                <input type="text" name="customer_name[]" class="form-control" required>
                <button type="button" class="btn btn-success" onclick="addCustomerName()">+</button>
            </div>
        </div>
        <script>
        function addCustomerName() {
            let container = document.getElementById('customerNameContainer');
            let div = document.createElement('div');
            div.className = 'input-group mb-2';
            div.innerHTML = `
                <input type="text" name="customer_name[]" class="form-control" required>
                <button type="button" class="btn btn-danger" onclick="this.parentNode.remove()">-</button>
            `;
            container.appendChild(div);
        }
        </script>

        <!-- حالة الفاوتشر -->
        <div class="col-md-3">
            <label class="form-label"><?= $lang['status'] ?></label>
            <select name="status" class="form-select" required>
                <option value="Confirmed"><?= $lang['confirmed'] ?></option>
                <option value="Hold"><?= $lang['hold'] ?></option>
                <option value="Cancelled"><?= $lang['cancelled'] ?></option>
            </select>
        </div>
    </div>

    <!-- ========================== قسم تفاصيل الغرفة (نوع، إطلالة، مستوى، خطة وجبات) ========================== -->
    <div class="row mb-3">
        <div class="col-md-3">
            <label class="form-label"><?= $lang['room_type'] ?></label>
            <select name="room_type" class="form-select" required>
                <option value="<?= $lang['room_single'] ?>"><?= $lang['room_single'] ?></option>
                <option value="<?= $lang['room_double'] ?>"><?= $lang['room_double'] ?></option>
                <option value="<?= $lang['room_triple'] ?>"><?= $lang['room_triple'] ?></option>
                <option value="<?= $lang['room_quad'] ?>"><?= $lang['room_quad'] ?></option>
                <option value="<?= $lang['room_quintuple'] ?>"><?= $lang['room_quintuple'] ?></option>
                <option value="<?= $lang['room_suite'] ?>"><?= $lang['room_suite'] ?></option>
                <option value="<?= $lang['room_two_living'] ?>"><?= $lang['room_two_living'] ?></option>
            </select>
        </div>
        <div class="col-md-3">
            <label class="form-label"><?= $lang['view'] ?></label>
            <select name="view" class="form-select" required>
                <option value="<?= $lang['city_view'] ?>"><?= $lang['city_view'] ?></option>
                <option value="<?= $lang['haram_view'] ?>"><?= $lang['haram_view'] ?></option>
                <option value="<?= $lang['kaaba_view'] ?>"><?= $lang['kaaba_view'] ?></option>
                <option value="<?= $lang['sea_view'] ?>"><?= $lang['sea_view'] ?></option>
                <option value="<?= $lang['garden_view'] ?>"><?= $lang['garden_view'] ?></option>
                <option value="<?= $lang['pool_view'] ?>"><?= $lang['pool_view'] ?></option>
            </select>
        </div>
        <div class="col-md-3">
            <label class="form-label"><?= $lang['room_level'] ?></label>
            <select name="room_level" class="form-select" required>
                <option value="<?= $lang['standard_room'] ?>"><?= $lang['standard_room'] ?></option>
                <option value="<?= $lang['deluxe_room'] ?>"><?= $lang['deluxe_room'] ?></option>
                <option value="<?= $lang['superior_room'] ?>"><?= $lang['superior_room'] ?></option>
            </select>
        </div>
        <div class="col-md-3">
            <label for="meal_plan" class="form-label"><?= $lang['meal_plan'] ?></label>
            <select name="meal_plan" id="meal_plan" class="form-select" required>
                <option value="B.B"><?= $lang['b_b'] ?></option>
                <option value="R.O"><?= $lang['r_o'] ?></option>
                <option value="H.B"><?= $lang['h_b'] ?></option>
                <option value="F.B"><?= $lang['f_b'] ?></option>
                <option value="AI"><?= $lang['ai'] ?></option>
                <option value="AI-S"><?= $lang['ai_s'] ?></option>
                <option value="AI-H"><?= $lang['ai_h'] ?></option>
            </select>
        </div>
    </div>

    <!-- ========================== قسم أرقام الحجز والفندق ========================== -->
<div class="row mb-3">
    <div class="col-md-3">
        <label class="form-label"><?= $lang['booking_number'] ?></label>
        <input type="text" class="form-control bg-light" value="<?= $generated_booking_number ?>" readonly>
        <input type="hidden" name="booking_number" value="<?= $generated_booking_number ?>">
    </div>

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

    <!-- Remarks -->
    <div class="col-md-3">
        <div class="form-check mb-2">
            <input class="form-check-input" type="checkbox" id="remarksCheck" onclick="toggleRemarks()">
            <label class="form-check-label" for="remarksCheck"><?= $lang['remarks'] ?></label>
        </div>
        <textarea name="remarks" id="remarksField" class="form-control" style="display:none;"></textarea>
    </div>
    <script>
    function toggleRemarks() {
        document.getElementById('remarksField').style.display = 
            document.getElementById('remarksCheck').checked ? 'block' : 'none';
    }
    </script>

    <!-- Company Logo -->
    <div class="col-md-3">
        <label class="form-label"><?= $lang['company_logo'] ?></label>
        <input type="file" name="company_logo" class="form-control" accept="image/*">
    </div>
</div>

<!-- ========================== المستخدم المدخل ========================== -->
<div class="row mb-3">
    <div class="col-md-3">
        <label class="form-label"><?= $lang['entered_by'] ?></label>
        <input type="text" class="form-control" value="<?= htmlspecialchars($_SESSION['user_name']) ?>" disabled>
    </div>
</div>

    <!-- ========================== قسم الشروط ========================== -->
    <div class="mb-3">
        <label class="form-label"><?= $lang['terms_conditions'] ?></label>
        <div class="border p-3 bg-light" style="white-space: pre-wrap;"><?= htmlspecialchars($termsContent) ?></div>
    </div>

    <!-- ========================== زر الحفظ ========================== -->
    <button type="submit" class="btn btn-success"><?= $lang['save'] ?></button>
</form>

</div> <!-- Close main-content -->

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