<?php
ob_start();
$pageTitle = 'إدارة الرحلات';
ini_set('serialize_precision', '-1');
include 'init.php';
use classs\ReservationsManager;
use classs\FileManager;
use classs\YomyaTransaction;
use NumberToWords\NumberToWords;
$numberToWords = new NumberToWords();
$numberTransformer = $numberToWords->getNumberTransformer('en');
$do = isset($_GET['do']) ? $_GET['do'] : '';
if (checkadmin($_SESSION['admin'], 4, 2) == 1) {
}
$countmanagement = 0;
$tourism_management = "SELECT * FROM tourism_management";
$managementsResult = $con->query($tourism_management);
while ($management = $managementsResult->fetch(PDO::FETCH_ASSOC)) {
    $id_user = $_SESSION['admin'];
    if (checkadmin($id_user, $management['department_id'], 2) == 1 || checkadmin($id_user, $management['department_id'], 3) == 1 || checkadmin($id_user, $management['department_id'], 4) == 1 || checkadmin($id_user, $management['department_id'], 5) == 1) {
        $countmanagement += 1;
        // echo "<option value='{$management['ID']}'>{$management['name_management']}</option>";
    } else {
        
    }
}
$department_id = 4;
if ($countmanagement > 0) {
    if ($do === 'add') {
        // عرض نموذج إضافة حجز جديد
        // include 'add_reservation_form.php';
        $countmanagement = 0;
        $tourism_management = "SELECT * FROM tourism_management";
        $managementsResult = $con->query($tourism_management);
        while ($management = $managementsResult->fetch(PDO::FETCH_ASSOC)) {
            $id_user = $_SESSION['admin'];
            if (checkadmin($id_user, $management['department_id'], 3) == 1) {
                $countmanagement += 1;
                // echo "<option value='{$management['ID']}'>{$management['name_management']}</option>";
            } else {
                
            }
        }
        if ($countmanagement > 0) {
            ?>
            <div class="container mt-5">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">إضافة ملف جديد <i class="fa-solid fa-folder-plus fa-sm"></i></h3>
                    </div>
                    <div class="card-body">
                        <form action="?do=insert" method="post">
                            <div class="row">
                                <div class="col-md-4 mb-3">
                                    <div class="form-floating">
                                        <select name="tourism_management" id="tourism_management" class="form-select" required>
                                            <?php
                                            // Query to retrieve agents from the agents table
                                            $agentsQuery = "SELECT * FROM tourism_management";
                                            $agentsResult = $con->query($agentsQuery);
                                            echo "<option value=''>اختر الإدارة</option>";
                                            while ($agent = $agentsResult->fetch(PDO::FETCH_ASSOC)) {
                                                $id_user = $_SESSION['admin'];
                                                if (checkadmin($id_user, $agent['department_id'], 3) == 1) {
                                                    echo "<option value='{$agent['ID']}'>{$agent['name_management']}</option>";
                                                }
                                            }
                                            ?>
                                        </select>
                                        <label for="tourism_management" class="form-label">إدارة:</label>
                                    </div>
                                </div>
                                <div class="col-md-4 mb-3">
                                    <div class="form-floating">
                                        <select name="cost_centers_id" id="cost_centers_id" class="form-select" required>
                                            <?php
                                            // Query to retrieve agents from the agents table
                                            $agentsQuery = "SELECT * FROM cost_centers WHERE cc_lv = 1";
                                            $agentsResult = $con->query($agentsQuery);
                                            echo "<option value=''>اختر مركز التكلفة الرئيسي</option>";
                                            while ($agent = $agentsResult->fetch(PDO::FETCH_ASSOC)) {
                                                echo "<option value='{$agent['ID']}'>{$agent['cost_center_name']}</option>";
                                            }
                                            ?>
                                        </select>
                                        <label for="cost_centers_id" class="form-label">مركز التكلفة:</label>
                                    </div>
                                </div>
                                <div class="col-md-4 mb-3">
                                    <div class="form-group">
                                    <label for="agent_id" class="form-label">الوكيل:</label>
                                        <select name="agent_id" id="agent_id" class="form-select getsearch" required>
                                            <?php
                                            // Query to retrieve agents from the agents table
                                            $agentsQuery = "SELECT * FROM agents";
                                            $agentsResult = $con->query($agentsQuery);
                                            echo "<option value=''>اختر الوكيل</option>";
                                            while ($agent = $agentsResult->fetch(PDO::FETCH_ASSOC)) {
                                                echo "<option value='{$agent['ID']}'>{$agent['agent_name']}</option>";
                                            }
                                            ?>
                                        </select>
                                        
                                    </div>
                                </div>
                                <div class="col-md-2 mb-3">
                                    <div class="form-check">
                                        <input class="form-check-input" type="radio" name="client_selection" id="existing_client_radio" value="existing" >
                                        <label class="form-check-label" style=" font-size: 12px;" for="existing_client_radio">اختيار عميل موجود</label>
                                    </div>
                                </div>
                                <div class="col-md-2 mb-3">
                                    <div class="form-check">
                                        <input class="form-check-input" type="radio" name="client_selection" id="new_client_radio" value="new">
                                        <label class="form-check-label" style=" font-size: 12px;" for="new_client_radio">إضافة عميل جديد</label>
                                    </div>
                                </div>
                                <div class="col-md-6 mb-3"  id="existingClientSelect" style="display: none;">
                                    <div class="form-group">
                                    <label for="client_id" class="form-label">العميل:</label>
                                        <select name="client_id" id="clientSelect" class="form-select getsearch">
                                            <?php
                                            $clientsQuery = "SELECT clients.ID as client_id, clients.client_name, nationality.nationality_name
                                            FROM clients
                                            LEFT JOIN nationality ON clients.id_nationality = nationality.ID";
                                            $clientsResult = $con->query($clientsQuery);
                                            // إضافة خيار لإضافة عميل جديد
                                            echo "<option value=''>إختر العميل</option>";
                                            if ($clientsResult->rowCount() > 0) {
                                                // عرض العملاء المسترجعين من الاستعلام
                                                while ($client = $clientsResult->fetch(PDO::FETCH_ASSOC)) {
                                                    echo "<option value='{$client['client_id']}'>{$client['client_name']} ({$client['nationality_name']})</option>";
                                                }
                                            }
                                            ?>
                                        </select>
                                        
                                    </div>
                                </div>
                                <div class="col-md-8 mb-3" id="newClientFields" style="display: none">
                                    <!-- حقول إضافة العميل الجديد -->
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="form-floating mb-3">
                                                <input type="text" class="form-control" name="client_name" id="client_name" placeholder="name client">
                                                <label for="client_name" class="form-label">اسم العميل</label>
                                            </div>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <div class="form-group">
                                            <label for="nationality_id" class="form-label">الجنسية:</label>
                                            <select name="nationality_id" id="nationality_id" class="form-select getsearch">
                                                <?php
                                                $nationalitysQuery = "SELECT *
                                                                    FROM nationality ";
                                                $nationalitysResult = $con->query($nationalitysQuery);

                                                // إضافة خيار لإضافة عميل جديد
                                                echo "<option value=''>اختر الجنسية</option>";

                                                if ($nationalitysResult->rowCount() > 0) {
                                                    // عرض الجنسيات المسترجعين من الاستعلام
                                                    while ($nationality = $nationalitysResult->fetch(PDO::FETCH_ASSOC)) {
                                                        echo "<option value='{$nationality['ID']}'>({$nationality['nationality_name']} - {$nationality['nationality_code']})</option>";
                                                    }
                                                }
                                                ?>
                                            </select>
                                            
                                        </div>
                                        </div>
                                    </div>
                                </div>
                                <script>
                                        // كود جافا سكريبت لإظهار أو إخفاء حقول إضافة العميل الجديد
                                        document.querySelectorAll('input[name="client_selection"]').forEach(function(radio) {
                                            radio.addEventListener('change', function () {
                                                var existingClientSelect = document.getElementById('existingClientSelect');
                                                var newClientFields = document.getElementById('newClientFields');
                                                
                                                if (this.value === 'existing') {
                                                    existingClientSelect.style.display = 'block';
                                                    newClientFields.style.display = 'none';
                                                } else if (this.value === 'new') {
                                                    existingClientSelect.style.display = 'none';
                                                    newClientFields.style.display = 'block';
                                                }
                                            });
                                        });
                                    </script>
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                    <div class="form-floating mb-3">
                                        <input type="date" name="arrival_date" class="form-control" placeholder="Arrival Date" required>
                                        <label for="arrival_date" class="form-label">Arrival Date:</label>
                                    </div>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                    <div class="form-floating mb-3">
                                        <input type="date" name="departure_date" class="form-control" placeholder="Departure Date" required>
                                        <label for="departure_date" class="form-label">Departure Date:</label>
                                    </div>
                                    </div>
                                </div>

                                <div class="mb-3">
                                <div class="form-floating">
                                    <textarea name="remarks" class="form-control"></textarea>
                                    <label for="remarks" class="form-label">ملحوظة:</label>
                                </div>
                                </div>

                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <button type="submit" class="btn btn-primary" name="add_file">add file</button>
                                    </div>
                                </div>
                        </form>
                    </div>
                </div>
            </div>
            <?php
        } else {
            echo '<div class="alert alert-danger">ليس لديك صلاحية الدخول الى هذا القسم</div>';
        }
    } elseif ($do === 'insert') {
        // معالجة إضافة الحجز الجديد
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_file'])) {
            $reservationsManager = new ReservationsManager($con);
            // استلام البيانات من الفورم  client_selection
            $tourism_management = $_POST['tourism_management'];
            $cost_centers_id = $_POST['cost_centers_id'];
            $agent_id = $_POST['agent_id'];
            $client_id = ($_POST['client_selection'] === 'new') ? null : $_POST['client_id'];
            $new_client_name = ($_POST['client_selection'] === 'new') ? $_POST['client_name'] : null;
            $nationality_id = ($_POST['client_selection'] === 'new') ? $_POST['nationality_id'] : null;
            $arrival_date = $_POST['arrival_date'];
            $departure_date = $_POST['departure_date'];
            $remarks = $_POST['remarks'];
            // يمكنك إجراء عمليات التحقق هنا
            $formErrors = array();
            if (empty($tourism_management)) {
                $formErrors[] = 'برجاء إختر إدارة السياحة<strong>فارغ</strong>';
            }
            if (empty($cost_centers_id)) {
                $formErrors[] = 'لا يجب أن يكون مركز التكلفة  <strong>فارغ</strong>';
            }
            if (empty($agent_id)) {
                $formErrors[] = 'لا يجب أن يكون إسم الوكيل  <strong>فارغ</strong>';
            }
            if (empty($arrival_date)) {
                $formErrors[] = 'لا يجب أن يكون تاريخ الوصول <strong>فارغ</strong>';
            }
            if (empty($departure_date)) {
                $formErrors[] = 'لا يجب أن يكون تاريخ المغادرة <strong>فارغ</strong>';
            }
            if ($_POST['client_selection'] === 'new') {
                if (empty($new_client_name)) {
                    $formErrors[] = 'لا يجب أن يكون اسم العميل <strong>فارغ</strong>';
                }
                if (empty($nationality_id)) {
                    $formErrors[] = 'برجاء إختر جنسية العميل <strong></strong>';
                }
            }
            // Loop Into Errors Array And Echo It
            foreach ($formErrors as $error) {
                echo '<div class="alert alert-danger">' . $error . '</div>';
            }
            if (empty($formErrors)) {
                try {
                    $FileNumber = $reservationsManager->generateFileNumber($departure_date);
                    // بدء عملية إضافة العميل إذا كان تم اختيار "اضافة عميل جديد"
                    if ($_POST['client_selection'] === 'new') {
                        $client_id = $reservationsManager->addNewClient($new_client_name, $nationality_id);
                    } else {
                        $nationality_id = getId('clients','ID',$client_id, 'id_nationality');
                    }
                    
                    $lv1 = getName("cost_centers", "ID", $cost_centers_id, "cost_center_code");
                    $new_cost_center_id = getNextCostCenterCode($con, $lv1, $cost_centers_id, $FileNumber);
                    
                    $id_addReservation = $reservationsManager->addReservation($tourism_management, $new_cost_center_id, $FileNumber, $agent_id, $client_id, $arrival_date, $departure_date, $remarks, $sessionUser, $nationality_id);

                    if ($id_addReservation) {
                        
                        $theMsg = "تمت إضافة الحجز بنجاح!";
                        redirectlink($theMsg, $url = "reservations?do=all_data_file&id=".$id_addReservation."", $name = "عرض الملفات", $seconds = 0);
                    } else {
                        echo "حدث خطأ أثناء إضافة الحجز.";
                    }
                } catch (PDOException $e) {
                    echo "حدث خطأ أثناء إضافة الحجز: " . $e->getMessage();
                }
            }
        }
    } elseif ($do === 'edit') {
        $id_file = isset($_GET['id']) && is_numeric($_GET['id']) ? intval($_GET['id']) : 0;
        $countmanagement = 0;
        $id_management = getName("reservations","id",$id_file,"id_tourism_management");
        if ($id_management >= 1) {
            $tourism_management = $con->prepare("SELECT * FROM tourism_management where ID = $id_management");
            $tourism_management->execute();
            $managements = $tourism_management->fetch(PDO::FETCH_ASSOC);
            $count = $tourism_management->rowCount();
            if ($count > 0) {
                $department_id = $managements['department_id'];
                $name_management = $managements['name_management'];
                $id_user = $_SESSION['admin'];
                if (checkadmin($id_user, $department_id, 4) == 1 ) {
                    $countmanagement += 1;
                }
            } else {
                $countmanagement = 0;
            }
        } else {
            $countmanagement = 0;
        }
        if ($countmanagement > 0) {
            if (isset($_GET['id']) && is_numeric($_GET['id'])) {
                $reservation_id = $_GET['id'];

                $reservationsManager = new ReservationsManager($con);
                $reservationDatas = $reservationsManager->getReservationById($reservation_id);

                if ($reservationDatas != null) {
                    // استخدم $reservationData لملء حقول النموذج
                    ?>
                    <div class="container mt-5">
                        <div class="card">
                            <div class="card-header">
                                <h3 class="card-title">تعديل بيانات ملف <i class="fa-solid fa-folder-plus fa-sm"></i></h3>
                            </div>
                            <div class="card-body">
                                <form action="?do=update" method="post">
                                    <input type="hidden" name="reservation_id" value="<?php echo $reservationDatas['id']; ?>">
                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <div class="form-floating">
                                                <select name="tourism_management" id="tourism_management" class="form-select" required>
                                                    <?php
                                                    // Query to retrieve agents from the agents table
                                                    $agentsQuery = "SELECT * FROM tourism_management WHERE ID = :id_management";
                                                    $stmt = $con->prepare($agentsQuery);
                                                    $stmt->bindParam(':id_management', $reservationDatas['id_tourism_management']);
                                                    $stmt->execute();
                                                    while ($agent = $stmt->fetch(PDO::FETCH_ASSOC)) {
                                                        if (checkadmin($id_user, $agent['department_id'], 4) == 1) {
                                                            echo "<option value='{$agent['ID']}'>{$agent['name_management']}</option>";
                                                        }
                                                    }
                                                    $agentsQuery = "SELECT * FROM tourism_management WHERE ID != :id_management";
                                                    $stmt = $con->prepare($agentsQuery);
                                                    $stmt->bindParam(':id_management', $reservationDatas['id_tourism_management']);
                                                    $stmt->execute();
                                                    while ($agent = $stmt->fetch(PDO::FETCH_ASSOC)) {
                                                        if (checkadmin($id_user, $agent['department_id'], 3) == 1) {
                                                            echo "<option value='{$agent['ID']}'>{$agent['name_management']}</option>";
                                                        }
                                                    }
                                                    ?>
                                                </select>
                                                <label for="tourism_management" class="form-label">إدارة:</label>
                                            </div>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <div class="form-floating">
                                                <select name="agent_id" class="form-select" required>
                                                    <?php
                                                    // Query to retrieve agents from the agents table
                                                    $agentsQuery = "SELECT * FROM agents WHERE ID = :id_agents";
                                                    $stmt = $con->prepare($agentsQuery);
                                                    $stmt->bindParam(':id_agents', $reservationDatas['agent_id']);
                                                    $stmt->execute();
                                                    while ($agent = $stmt->fetch(PDO::FETCH_ASSOC)) {
                                                        echo "<option value='{$agent['ID']}'>{$agent['agent_name']}</option>";
                                                    }
                                                    $agentsQuery = "SELECT * FROM agents WHERE ID != :id_agents";
                                                    $stmt = $con->prepare($agentsQuery);
                                                    $stmt->bindParam(':id_agents', $reservationDatas['agent_id']);
                                                    $stmt->execute();
                                                    while ($agent = $stmt->fetch(PDO::FETCH_ASSOC)) {
                                                        echo "<option value='{$agent['ID']}'>{$agent['agent_name']}</option>";
                                                    }
                                                    ?>
                                                </select>
                                                <label for="agent_id" class="form-label">الوكيل:</label>
                                            </div>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label for="client_id" class="form-label">اختر العميل:</label>
                                            <select name="client_id" id="clientSelect" class="form-select" required>
                                                <?php
                                                $clientsQuery = "SELECT clients.ID as client_id, clients.client_name, nationality.nationality_name
                                                            FROM clients
                                                            LEFT JOIN nationality ON clients.id_nationality = nationality.ID
                                                            WHERE clients.ID = :ID";
                                                $stmt = $con->prepare($clientsQuery);
                                                $stmt->bindParam(':ID', $reservationDatas['client_id']);
                                                $stmt->execute();
                                                // $clientsResult = $con->query($clientsQuery);
                                                if ($stmt->rowCount() > 0) {
                                                    // عرض العملاء المسترجعين من الاستعلام
                                                    while ($client = $stmt->fetch(PDO::FETCH_ASSOC)) {
                                                        echo "<option value='{$client['client_id']}'>{$client['client_name']} ({$client['nationality_name']})</option>";
                                                    }
                                                }
                                                // إضافة خيار لإضافة عميل جديد
                                                echo "<option value='new'>اضافة عميل جديد</option>";
                                                $clientsQuery = "SELECT clients.ID as client_id, clients.client_name, nationality.nationality_name
                                                            FROM clients
                                                            LEFT JOIN nationality ON clients.id_nationality = nationality.ID
                                                            WHERE clients.ID != :ID";
                                                $stmt = $con->prepare($clientsQuery);
                                                $stmt->bindParam(':ID', $reservationDatas['client_id']);
                                                $stmt->execute();
                                                // $clientsResult = $con->query($clientsQuery);
                                                if ($stmt->rowCount() > 0) {
                                                    // عرض العملاء المسترجعين من الاستعلام
                                                    while ($client = $stmt->fetch(PDO::FETCH_ASSOC)) {
                                                        echo "<option value='{$client['client_id']}'>{$client['client_name']} ({$client['nationality_name']})</option>";
                                                    }
                                                }
                                                ?>
                                            </select>
                                        </div>
                                        <div id="newClientFields" style="display: none;">
                                            <!-- حقول إضافة العميل الجديد -->
                                            <div class="row">
                                                <div class="col-md-6 mb-3">
                                                    <label for="client_name" class="form-label">اسم العميل</label>
                                                    <input type="text" name="client_name" class="form-control">
                                                </div>
                                                <div class="col-md-6 mb-3">
                                                    <label for="nationality_id" class="form-label">الجنسية:</label>
                                                    <select name="nationality_id" id="clientSelect" class="form-select">
                                                        <?php
                                                        $nationalitysQuery = "SELECT *
                                                                    FROM nationality ";
                                                        $nationalitysResult = $con->query($nationalitysQuery);

                                                        // إضافة خيار لإضافة عميل جديد
                                                        echo "<option value=''>اختر الجنسية</option>";

                                                        if ($nationalitysResult->rowCount() > 0) {
                                                            // عرض الجنسيات المسترجعين من الاستعلام
                                                            while ($nationality = $nationalitysResult->fetch(PDO::FETCH_ASSOC)) {
                                                                echo "<option value='{$nationality['ID']}'>({$nationality['nationality_name']})</option>";
                                                            }
                                                        }
                                                        ?>
                                                    </select>
                                                </div>
                                            </div>
                                            <script>
                                                // كود جافا سكريبت لإظهار أو إخفاء حقول إضافة العميل الجديد
                                                document.getElementById('clientSelect').addEventListener('change', function () {
                                                    var newClientFields = document.getElementById('newClientFields');
                                                    if (this.value === 'new') {
                                                        newClientFields.style.display = 'block';
                                                    } else {
                                                        newClientFields.style.display = 'none';
                                                    }
                                                });
                                            </script>
                                        </div>
                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label for="arrival_date" class="form-label">Arrival Date:</label>
                                                <input type="date" name="arrival_date"
                                                    value="<?php echo $reservationDatas['arrival_date'] ?>" class="form-control" required>
                                            </div>

                                            <div class="col-md-6 mb-3">
                                                <label for="departure_date" class="form-label">Departure Date:</label>
                                                <input type="date" name="departure_date"
                                                    value="<?php echo $reservationDatas['departure_date'] ?>" class="form-control" required>
                                            </div>
                                        </div>

                                        <div class="mb-3">
                                            <label for="remarks" class="form-label">ملحوظة:</label>
                                            <textarea name="remarks"
                                                class="form-control"><?php echo $reservationDatas['remarks'] ?></textarea>
                                        </div>

                                        <div class="row">

                                            <div class="col-md-6 mb-3">
                                                <button type="submit" class="btn btn-primary" name="edit_file">edit file</button>
                                            </div>
                                        </div>
                                </form>
                            </div>
                        </div>
                    </div>

                    <?php
                    // }
                } else {
                    // رسالة خطأ أو إعادة توجيه إلى صفحة خطأ
                    echo "خطأ: لا يوجد حجز بهذا الرقم.";
                    exit;
                }
            } else {
                // رسالة خطأ أو إعادة توجيه إلى صفحة خطأ
                echo "خطأ: يجب تحديد رقم الحجز.";
                exit;
            }
        } else {
            echo '<div class="alert alert-danger">ليس لديك صلاحية الدخول الى هذا القسم</div>';
        }
    } elseif ($do === 'update') {
        // معالجة إضافة الحجز الجديد
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['edit_file'])) {

            $reservationsManager = new ReservationsManager($con);

            // استلام البيانات من الفورم
            $reservation_id = $_POST['reservation_id'];
            $agent_id = $_POST['agent_id'];
            $client_id = ($_POST['client_id'] === 'new') ? null : $_POST['client_id'];
            $new_client_name = ($_POST['client_id'] === 'new') ? $_POST['client_name'] : null;
            $nationality_id = ($_POST['client_id'] === 'new') ? $_POST['nationality_id'] : null;
            $arrival_date = $_POST['arrival_date'];
            $departure_date = $_POST['departure_date'];
            $remarks = $_POST['remarks'];

            // يمكنك إجراء عمليات التحقق هنا
            $formErrors = array();
            if (empty($agent_id)) {
                $formErrors[] = 'لا يجب أن يكون إسم الوكيل  <strong>فارغ</strong>';
            }
            if (empty($arrival_date)) {
                $formErrors[] = 'لا يجب أن يكون تاريخ الوصول <strong>فارغ</strong>';
            }
            if (empty($departure_date)) {
                $formErrors[] = 'لا يجب أن يكون تاريخ المغادرة <strong>فارغ</strong>';
            }
            if ($_POST['client_id'] === 'new') {
                if (empty($new_client_name)) {
                    $formErrors[] = 'لا يجب أن يكون اسم العميل <strong>فارغ</strong>';
                }
                if (empty($nationality_id)) {
                    $formErrors[] = 'برجاء إختر جنسية العميل <strong></strong>';
                }
            }
            // Loop Into Errors Array And Echo It
            foreach ($formErrors as $error) {
                echo '<div class="alert alert-danger">' . $error . '</div>';
            }
            if (empty($formErrors)) {
                try {
                    // بدء عملية إضافة العميل إذا كان تم اختيار "اضافة عميل جديد"
                    if ($_POST['client_id'] === 'new') {
                        $client_id = $reservationsManager->addNewClient($new_client_name, $nationality_id);
                    }

                    // إضافة الحجز باستخدام فئة ReservationsManager
                    $result = $reservationsManager->updateReservation($reservation_id, $agent_id, $client_id, $arrival_date, $departure_date, $remarks);
                    // $result = $reservationsManager->addReservation($agent_id, $client_id, $arrival_date, $departure_date, $remarks);

                    if ($result) {
                        $theMsg = "تم تحديث ملف الحجز بنجاح!";
                        redirectlink($theMsg, $url = "reservations?do=all_data_file&id=".$reservation_id."", $name = "عرض الملفات", $seconds = 0);
                    } else {
                        echo "حدث خطأ أثناء تحديث ملف الحجز.";
                    }
                } catch (PDOException $e) {
                    echo "حدث خطأ أثناء إضافة الحجز: " . $e->getMessage();
                }
            }
        }
    } elseif ($do === 'delete') {
        $id_file = isset($_GET['id']) && is_numeric($_GET['id']) ? intval($_GET['id']) : 0;
        $countmanagement = 0;
        $id_management = getName("reservations","id",$id_file,"id_tourism_management");
        if ($id_management >= 1) {
            $tourism_management = $con->prepare("SELECT * FROM tourism_management where ID = $id_management");
            $tourism_management->execute();
            $managements = $tourism_management->fetch(PDO::FETCH_ASSOC);
            $count = $tourism_management->rowCount();
            if ($count > 0) {
                $department_id = $managements['department_id'];
                $name_management = $managements['name_management'];
                $id_user = $_SESSION['admin'];
                if (checkadmin($id_user, $department_id, 4) == 1 ) {
                    $countmanagement += 1;
                }
            } else {
                $countmanagement = 0;
            }
        } else {
            $countmanagement = 0;
        }
        if ($countmanagement > 0) {
            // معالجة حذف الحجز
            echo "<h3 class='text-center'>حذف</h3>";
            echo "<div class='container'>";
            // Check If Get Request id Is Numeric & Get The Integer Value Of It
            $id = isset($_GET['id']) && is_numeric($_GET['id']) ? intval($_GET['id']) : 0;
            // Select All Data Depend On This ID
            $check = checkItem('id', 'reservations', $id);
            // If There's Such ID Show The Form
            if ($check > 0) {
                $stmt = $con->prepare("DELETE FROM reservations WHERE id = :zid");
                $stmt->bindParam(":zid", $id);
                // اضافة البيانات فى التقرير
                $stmtSelectIns = $con->prepare("SELECT * FROM reservations WHERE id = $id");
                $stmtSelectIns->execute();
                $dataOld = $stmtSelectIns->fetch(PDO::FETCH_ASSOC);
                logToHistory('delete', 'reservations', $id, $dataOld, '', 'id');
                // END
                $stmt->execute();
                $theMsg = "<div class='alert alert-success'>" . $stmt->rowCount() . ' تم الحذف بنجاح</div>';
                redirectlink($theMsg, $url = "reservations?do=all_file", $name = "عرض الملفات", $seconds = 1);
            } else {
                $theMsg = '<div class="alert alert-danger">برجاء إتباع رابط صحيح</div>';
                redirectHome($theMsg);
            }
        } else {
            $theMsg = '<div class="alert alert-danger">ليس لديك صلاحية الدخول الى هذا القسم</div>';
            redirectlink($theMsg, $url = "reservations?do=all_file", $name = "عرض الملفات", $seconds = 3);
        }
        echo '</div>';
    } elseif ($do === 'all_file') {
        
        if (!isset($_GET['id_management'])) {
            $agentsQuery = "SELECT * FROM tourism_management";
            $agentsResult = $con->query($agentsQuery);
            echo '<h1 class="input-group-text text-center">عرض ملفات</h1>';
            ?>
            <div class="row">
                <div class='col-md-6 list-group'>
                    <?php
                        while ($agent = $agentsResult->fetch(PDO::FETCH_ASSOC)) {
                            $id_user = $_SESSION['admin'];
                            if (checkadmin($id_user, $agent['department_id'], 2) == 1) {
                                echo "
                                <a href='?do=all_file&id_management={$agent['ID']}' class='list-group-item list-group-item-action' aria-current='true'>
                                {$agent['name_management']}
                                <!-- <span class='badge bg-primary rounded-pill'>14</span> --></a>";
                            }
                        }
                    ?>
                </div>
            </div>
                <!-- <a class="list-group-item list-group-item-action disabled" aria-disabled="true">A disabled link item</a> -->
            <?php
        } elseif(intval($_GET['id_management']) > 0) {
            $id_management = intval($_GET['id_management']);
            $countmanagement = 0;
            $tourism_management = $con->prepare("SELECT * FROM tourism_management where ID = $id_management");
            $tourism_management->execute();
            $managements = $tourism_management->fetch(PDO::FETCH_ASSOC);
                $department_id = $managements['department_id'];
                $name_management = $managements['name_management'];
                $id_user = $_SESSION['admin'];
                if (checkadmin($id_user, $department_id, 2) == 1 ) {
                    $countmanagement += 1;
                }
            if ($countmanagement > 0) {
                echo "<h1 class='input-group-text text-center'><a href='?do=all_file'>عرض ملفات </a>: {$name_management}</h1>";
                ?>
                <form action="?do=all_file&id_management=<?=$id_management?>" method="post">
                    <div class="row">
                        <div class="form-group form-group-lg col-sm-3">
                            <div class="col-sm-12">
                                <label for="start_date" class="control-label">من تاريخ:</label>
                                <input type="date" name="start_date" class="form-control" value="<?php echo $start_date_default; ?>"
                                    required>
                            </div>
                        </div>
                        <div class="form-group form-group-lg col-sm-3">
                            <div class="col-sm-12">
                                <label for="end_date" class="control-label">الى تاريخ:</label>
                                <input type="date" name="end_date" class="form-control" value="<?php echo $end_date_default; ?>"
                                    required>
                            </div>
                        </div>
                        <div class="form-group form-group-lg col-sm-1">
                            <div class="col-sm-12">
                                <label></label>
                                <button type="submit" class="btn btn-primary form-control" name="view_reservations">بحث</button>
                            </div>
                        </div>
                        <div class="form-group form-group-lg col-sm-1">
                        </div>
                        <div class="form-group form-group-lg col-sm-3">
                            <label></label>
                            <a href="?do=add" class="btn btn-warning form-control">
                                <i class="fa-solid fa-folder-plus fa-xl"></i> إضافة ملف جديد
                            </a>
                        </div>
                    </div>
                </form>
                <br>
                <?php
                $reservationsManager = new ReservationsManager($con);
                if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['view_reservations'])) {
                    $start_date = $_POST['start_date'];
                    $end_date = $_POST['end_date'];
                    // You can perform validation on $start_date and $end_date if needed
                    $reservations = $reservationsManager->getReservationsByDateRange($id_management, $start_date, $end_date);
                    $msgres = "لا يوجد سجل ملفات فى الفترة المحددة.";
                } else {
                    $reservations = $reservationsManager->getReservationsForCurrentMonthWithNames($id_management);
                    $msgres = "لا يوجد سجلات حتى الان";
                }
                if (!empty($reservations)) {
                    echo "<table class='main-table text-center table table-bordered'>";
                    echo "<tr>
                        <td>رقم الملف</td>
                        <td>الوكيل</td>
                        <td>العميل</td>
                        <td>الجنسية</td>
                        <td>Arr</td>
                        <td>Dep</td>
                        <td>حالة الدفع</td>
                        <td>ملاحظة</td>
                        <td>الإجمالى</td>
                        <td>Control</td>
                    </tr>";

                    foreach ($reservations as $reservation) {
                        if ($reservation['payment_status'] == 0) {
                            $status_payment = "لم يتم الدفع";
                        } else {
                            $status_payment = "تم الدفع";
                        }
                        echo "<tr>
                            <td>{$reservation['file_number']}</td>
                            <td>{$reservation['agent_name']}</td>
                            <td>{$reservation['client_name']}</td>
                            <td>{$reservation['nationality_name']}</td>
                            <td>{$reservation['arrival_date']}</td>
                            <td>{$reservation['departure_date']}</td>
                            <td>{$status_payment}</td>
                            <td>{$reservation['remarks']}</td>
                            <td>{$reservation['total_price']}</td>";
                        if (checkadmin($id_user, $department_id, 2) == 1) {
                            echo "<td>
                                <a href='?do=all_data_file&id=" . $reservation['id'] . "&id_management=".$id_management."' class='btn btn-primary'><i class=\"fa-solid fa-gear\"></i> </a>
                            ";
                        }
                        if (checkadmin($id_user, $department_id, 4) == 1) {
                            echo "
                                <a href='?do=edit&id=" . $reservation['id'] . "' class='btn btn-success'><i class=\"fa-solid fa-user-pen\"></i> </a>
                            ";
                        }
                        /* if (checkadmin($id_user, $department_id, 5) == 1) {
                            echo "
                                <a href='?do=delete&id=" . $reservation['id'] . "' class='btn btn-danger confirm'><i class='fa-solid fa-user-xmark'></i> </a>
                            ";
                        } */
                        echo "</td></tr>";
                    }
                    echo "</table>";
                } else {
                    echo $msgres;
                }
            } else {
                $theMsg = '<div class="alert alert-danger">ليس لديك صلاحية الدخول الى هذا القسم</div>';
                redirectHome($theMsg, NULL, 3);
            }
        } else {
            $theMsg = '<div class="alert alert-danger">برجاء إتباع رابط صحيح</div>';
            redirectHome($theMsg, 'back', 4);
        }
    } elseif ($do === 'all_data_file') {
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['search_file'])) {
            if(isset($_POST['search_name']) && !empty($_POST['search_name'])){
                try {
                    // إنشاء اتصال PDO
                    
                    // تحضير الاستعلام
                    $stmt = $con->prepare("SELECT * FROM reservations WHERE file_number = :search_name");
                    // تنفيذ الاستعلام باستخدام القيمة المعطاة
                    $stmt->execute(['search_name' => $_POST['search_name']]);
                    // استرجاع البيانات
                    $row = $stmt->fetch(PDO::FETCH_ASSOC);
                    if($row) {
                        $_GET['id'] = $row['id']; // افترضت أن id هو العمود الذي تريد استخدام قيمته
                    } else {
                        $_GET['id'] = null; // إذا لم يتم العثور على نتيجة
                        $theMsg = '<div class="alert alert-danger">لا يوجد ملف بهذا الرقم، يمكنك ادخال رقم الملف بشكل صحيح</div>';
                    }
                } catch (PDOException $e) {
                    // في حالة وجود خطأ في الاتصال بقاعدة البيانات
                    echo "Connection failed: " . $e->getMessage();
                }
            } else {
                $_GET['id'] = null;
                $theMsg = '<div class="alert alert-danger">يجب كتابة رقم الملف للبحث عنه</div>';
            }
        }
        // $id_management = isset($_GET['id_management']) && is_numeric($_GET['id_management']) ? intval($_GET['id_management']) : 0;
        $id_file = isset($_GET['id']) && is_numeric($_GET['id']) ? intval($_GET['id']) : 0;
        $countmanagement = 0;
        $id_management = getId("reservations","id",$id_file,"id_tourism_management");
        if ($id_management > 0) {
            $tourism_management = $con->prepare("SELECT * FROM tourism_management where ID = $id_management");
            $tourism_management->execute();
            $managements = $tourism_management->fetch(PDO::FETCH_ASSOC);
            $count = $tourism_management->rowCount();
            if ($count > 0) {
                $department_id = $managements['department_id'];
                $name_management = $managements['name_management'];
                $id_user = $_SESSION['admin'];
                if (checkadmin($id_user, $department_id, 2) == 1 ) {
                    $countmanagement += 1;
                }
            } else {
                $countmanagement = 0;
            }
        } else {
            $countmanagement = 0;
        }
        if ($countmanagement > 0) {
            if (isset($_GET['id']) && is_numeric($_GET['id'])) {
                $reservation_id = $_GET['id'];
                $reservationsManager = new ReservationsManager($con);
                $reservationDatas = $reservationsManager->getReservationById($reservation_id);
                if ($reservationDatas != null) {
                    $id_invoice = getId('invoicing','id_reservation',$reservation_id,'ID');
                    $currencyExchangeRateById = getId('currency','ID', 2,'currencyExchangeRate');
                    $sumInvoicingLine = $reservationsManager->sumInvoicingLineById($id_invoice);
                    $sumBookingFile = $reservationsManager->sumBookingFileById($reservation_id);
                    $InvoicingLines = $reservationsManager->getInvoicingDataById($id_invoice);

                    $currencyExchangeRateByIdEGP  = 1 / $currencyExchangeRateById;
                    $sumBookingFilecash = $sumBookingFile['cash'] * $currencyExchangeRateByIdEGP;
                    $file_number = explode("/", $reservationDatas['file_number']);
                    $sumBookingFilecash = ceil($sumBookingFilecash * 100) / 100;
                    
                    echo "<h1 class='input-group-text text-center'><a href='?do=all_file'>عرض ملفات </a>: <a href='?do=all_file&id_management={$id_management}'>{$name_management}</a> / ملف رقم : {$file_number[0]} / {$file_number[1]} </h1>";
                    if ($id_management == 1) {
                        ?>
                        <a href="?do=invoicess_vo&id=<?=$reservation_id?>&id_invoice=<?=$id_invoice?>" class="btn btn-primary">
                            <i class="fa fa-plus"></i> عرض الفاتورة
                        </a>
                        <?php 
                    } else {
                        ?>
                        <a href="?do=invoicess&id=<?=$reservation_id?>&id_invoice=<?=$id_invoice?>" class="btn btn-primary">
                            <i class="fa fa-plus"></i> عرض الفاتورة
                        </a>
                        <?php 
                    }
                    ?>
                    <br />
                    <br>
                    <?php
                    echo "<table class='main-table text-center table table-bordered'>";
                    echo "<tr>
                    <td>رقم الملف</td>
                    <td>الوكيل</td>
                    <td>العميل</td>
                    <td>الجنسية</td>
                    <td>Arr</td>
                    <td>Dep</td>
                    <td>حالة الدفع</td>
                    <td>ملاحظة</td>
                    <td>تاربخ الإضافة</td>
                    <td>إجمالى التكلفة</td>
                    <td>إجمالى الفاتورة</td>
                    <td>حالة الملف</td>
                    <td>Control</td>
                </tr>";
                    // foreach ($reservations as $reservation) {
                    if ($reservationDatas['payment_status'] == 0) {
                        $status_payment = "لم يتم الدفع";
                    } else {
                        $status_payment = "تم الدفع";
                    }
                    if ($reservationDatas['check_status'] == "off") {
                        $check_status = "مغلق";
                    } elseif ($reservationDatas['check_status'] == "on") {
                        $check_status = "مفتوح";
                    }
                    $total_cost_invice = 0;
                    if (is_array($InvoicingLines)) {
                        foreach ($InvoicingLines as $key => $value) {
                            $total_cost_invice += $value['total_invoice'];
                        }
                    }
                    echo "<tr>
                        <td>{$reservationDatas['file_number']}</td>
                        <td>{$reservationDatas['agent_name']}</td>
                        <td>{$reservationDatas['client_name']}</td>
                        <td>{$reservationDatas['nationality_name']}</td>
                        <td>{$reservationDatas['arrival_date']}</td>
                        <td>{$reservationDatas['departure_date']}</td>
                        <td>{$status_payment}</td>
                        <td>{$reservationDatas['remarks']}</td>
                        <td>{$reservationDatas['date_insert']}</td>
                        <td>\${$sumBookingFilecash}</td>
                        <td>\${$total_cost_invice}</td>
                        <td>{$check_status}</td>";
                    if (checkadmin($_SESSION['admin'], 4, 2) == 1) {
                        echo "<td>
                        <a href='?do=edit&id=" . $reservationDatas['id'] . "' class='btn btn-success'><i class=\"fa-solid fa-user-pen\"></i> </a>
                        
                    </td>";
                    }
                    echo "</tr>";
                    /* <a href='?do=delete&id=" . $reservationDatas['id'] . "' class='btn btn-danger confirm'><i class='fa-solid fa-user-xmark'></i> </a> */
                    // }
                    echo "</table>";
                    $NumberIndividuals = $reservationsManager->getNumberIndividualsReservationById($reservationDatas['id']);
                    $hotel_bookings = $reservationsManager->getHotelBookingsReservationById($reservationDatas['id']);
                    $flight_bookings = $reservationsManager->getFlightBookingsReservationById($reservationDatas['id']);
                    $train_bookings = $reservationsManager->getTrainBookingsReservationById($reservationDatas['id']);
                    $booking_file = $reservationsManager->getBookingFileReservationById($reservationDatas['id']);
                    $Transportation_bookings = $reservationsManager->getTransportationBookingsReservationById($reservationDatas['id']);
                    $employee_bookings = $reservationsManager->getEmployeeBookingsReservationById($reservationDatas['id'], 1);
                    $employee_bookings_SH = $reservationsManager->getEmployeeBookingsReservationById($reservationDatas['id'], 2);

                    $all_Individuals = 0;
                    if (!empty($NumberIndividuals)) {
                        foreach ($NumberIndividuals as $value) {
                            $all_Individuals += $value['number'];
                        }
                    } else {
                        $all_Individuals = "<strong>لا يوجد</strong>";
                    }
                    ?>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <h1 class="input-group-text text-center"> <i class="fa-solid fa-users"></i>&nbsp; عدد الأفراد :
                                <?php echo $all_Individuals; ?>
                            </h1>
                                <table class='main-table text-center table table-bordered'>
                                    <tr>
                                        <td>الأشخاص</td>
                                        <td>العدد</td>
                                        <td>ملاحظات</td>
                                        <td>Control</td>
                                    </tr>
                                        <?php
                                        if (!empty($NumberIndividuals)) {
                                            foreach ($NumberIndividuals as $value) {
                                                echo "<tr>
                                                <td>{$value['name']}</td>
                                                <td>{$value['number']}</td>
                                                <td>{$value['age_person']}</td>
                                                ";
                                                ?>
                                                <td>
                                                    <button type="button" class="btn btn-success btn-sm" data-bs-toggle="modal" data-bs-target="#modal_edit_items-<?php echo $value['id_number_individuals'] ?>" title="تعديل">
                                                        <i class='fa fa-edit'></i>
                                                    </button>
                                                    <!-- Modal -->
                                                    <div class="modal fade" id="modal_edit_items-<?php echo $value['id_number_individuals'] ?>" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
                                                        <div class="modal-dialog modal-xl">
                                                            <div class="modal-content">
                                                            <div class="modal-header">
                                                                <h1 class="modal-title fs-5" id="staticBackdropLabel">Modal title</h1>
                                                                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                                            </div>
                                                            <form action="?do=insert_in_file" method="post">
                                                            <div class="modal-body">
                                                                <input type="hidden" name="id_number_individuals" id="id_number_individuals" value="<?=$value['id_number_individuals'] ?>">
                                                                <table class='main-table text-center table table-bordered'>
                                                                    <tr>
                                                                    </tr>
                                                                    <tr>
                                                                        <td>
                                                                        <input type="hidden" name="reservation_id" value="<?php echo $reservation_id; ?>">
                                                                        <?php
                                                                        // $id_persons = getId('number_individuals', 'ID', $value['ID'], 'id_persons');
                                                                        $id_persons = $value['id_persons'];
                                                                        ?>              
                                                                        <select name="id_persons" class="form-select" required>
                                                                            <?php
                                                                            // Query to retrieve agents from the agents table
                                                                            $personsQuery = "SELECT * FROM persons where ID = $id_persons";
                                                                            $personsResult = $con->query($personsQuery);
                                                                            while ($persons = $personsResult->fetch(PDO::FETCH_ASSOC)) {
                                                                                echo "<option value='{$persons['ID']}'>{$persons['name']}</option>";
                                                                            }
                                                                            $personsQuery = "SELECT * FROM persons where ID != $id_persons";
                                                                            $personsResult = $con->query($personsQuery);
                                                                            while ($persons = $personsResult->fetch(PDO::FETCH_ASSOC)) {
                                                                                echo "<option value='{$persons['ID']}'>{$persons['name']}</option>";
                                                                            }
                                                                            ?>
                                                                        </select>
                                                                        </td>
                                                                        <td>
                                                                            <input type="text" name="numper" value="<?=$value['number']?>" class="form-control form-control-sm" required>
                                                                        </td>
                                                                        <td>
                                                                            <input type="text" name="age_person" value="<?=$value['age_person']?>" class="form-control form-control-sm">
                                                                        </td>
                                                                        <td>
                                                                            <!-- <button type="submit" class="btn btn-primary" name="add_numper">حفظ</button> -->
                                                                        </td>
                                                                    </tr>
                                                                </table>
                                                            </div>
                                                            <div class="modal-footer">
                                                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                                                                <button type="submit" class="btn btn-primary" name="add_numper">حفظ</button>
                                                            </div>
                                                        </form>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    </td>
                                                    </tr>
                                                <?php
                                            }
                                        } else {
                                            echo "
                                                <td>لا يوجد</td>
                                                <td>لا يوجد</td>
                                                <td>لا يوجد</td>
                                                <td></td>";
                                        }
                                        ?>
                                    
                                    <tr>
                                        <td>
                                            <form action="?do=insert_in_file" method="post">
                                                <input type="hidden" name="reservation_id" value="<?php echo $reservation_id; ?>">
                                                <select name="id_persons" class="form-select" required>
                                                    <?php
                                                    // Query to retrieve agents from the agents table
                                                    $personsQuery = "SELECT * FROM persons";
                                                    $personsResult = $con->query($personsQuery);
                                                    echo "<option value=''>اختر الشخص</option>";
                                                    while ($persons = $personsResult->fetch(PDO::FETCH_ASSOC)) {
                                                        echo "<option value='{$persons['ID']}'>{$persons['name']}</option>";
                                                    }
                                                    ?>
                                                </select>
                                                </td>
                                                <td>
                                                    <input type="text" name="numper" class="form-control form-control-sm" required>
                                                </td>
                                                <td>
                                                    <input type="text" name="age_person" class="form-control form-control-sm">
                                                </td>
                                                <td>
                                                    <button type="submit" class="btn btn-primary" name="add_numper">حفظ</button>
                                            </form>
                                        </td>
                                    </tr>
                                </table>
                        </div>
                        <div class="col-md-6 mb-3">
                            <h1 class="input-group-text text-center"><i class="fa-solid fa-address-card"></i>&nbsp; المندوب المرافق</h1>
                            
                                <table class='main-table text-center table table-bordered'>
                                    <tr>
                                        <td>الإسم</td>
                                        <td>رقم الهاتف</td>
                                        <td>التكلفة</td>
                                        <td>Control</td>
                                    </tr>
                                    <?php
                                    if (!empty($employee_bookings)) {
                                        foreach ($employee_bookings as $value) {

                                            $cost_mandob = getIdTowVal('booking_file', 'id_line_type', 4,'id_line_booking',$value['id_booking'],'total_cost');

                                            $id_currency_codes = getIdTowVal('booking_file', 'id_line_type', 4,'id_line_booking',$value['id_booking'],'id_currency_codes');
                                            $amountSold = getIdTowVal('booking_file', 'id_line_type', 4,'id_line_booking',$value['id_booking'],'amountSold');
                                            $currencyExchangeRate = getIdTowVal('booking_file', 'id_line_type', 4,'id_line_booking',$value['id_booking'],'currencyExchangeRate');
                                            $currency_code = getId('currency', 'ID', $id_currency_codes , 'currency_code');

                                            if ($id_currency_codes == 2  && $amountSold != 0) {
                                                $cost_mandob = $amountSold;
                                            } elseif($id_currency_codes == 1) {
                                                $cost_mandob = $cost_mandob * $currencyExchangeRate;
                                                $currency_code = getId('currency', 'ID', 2 , 'currency_code');
                                            } else {
                                                $currency_code = getId('currency', 'ID', 2 , 'currency_code');
                                                $currencyExchangeRateUSD = getId('currency', 'ID', 2,'currencyExchangeRate');
                                                $currencyExchangeRateEGP = 1 / $currencyExchangeRateUSD;
                                                $cost_mandob = $cost_mandob * $currencyExchangeRateEGP;
                                                $cost_mandob = ceil($cost_mandob * 100) / 100;
                                            }
                                            echo "<tr>
                                            <td>{$value['full_name']}</td>
                                            <td>{$value['phone_number']}</td>
                                            <td>{$cost_mandob} {$currency_code}</td>
                                            ";
                                            ?>
                                            <td>
                                                <button type="button" class="btn btn-success btn-sm" data-bs-toggle="modal" data-bs-target="#modal_edit-<?php echo $value['id_booking'] ?>" title="تعديل">
                                                    <i class='fa fa-edit'></i>
                                                </button>
                                                <!-- Modal -->
                                                <div class="modal fade" id="modal_edit-<?php echo $value['id_booking'] ?>" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
                                                    <div class="modal-dialog modal-xl">
                                                        <div class="modal-content">
                                                        <div class="modal-header">
                                                            <h1 class="modal-title fs-5" id="staticBackdropLabel">Modal title</h1>
                                                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                                        </div>
                                                        <form action="?do=insert_in_file" method="post">
                                                            <div class="modal-body">
                                                            <input type="hidden" name="id_employee_booking" id="id_employee_booking" value="<?=$value['id_booking'] ?>">
                                                            <table class='main-table text-center table table-bordered'>
                                                                <tr>
                                                                </tr>
                                                                <tr>
                                                                    <td>
                                                                    <input type="hidden" name="reservation_id" value="<?php echo $reservation_id; ?>">
                                                                    <?php
                                                                    // $id_persons = getId('number_individuals', 'ID', $value['ID'], 'id_persons');
                                                                    // $id_persons = $value['id_persons'];
                                                                    ?>              
                                                                    <select name="id_employees" class="form-select" required>
                                                                        <?php
                                                                        // Query to retrieve agents from the agents table
                                                                        $id_employee = $value['id_employee'];
                                                                        $personsQuery = "SELECT * FROM employees where ID = $id_employee";
                                                                        $personsResult = $con->query($personsQuery);
                                                                        while ($persons = $personsResult->fetch(PDO::FETCH_ASSOC)) {
                                                                            echo "<option value='{$persons['ID']}'>{$persons['full_name']}</option>";
                                                                        }
                                                                        $personsQuery = "SELECT * FROM employees where id_department_employees = 1 AND ID != $id_employee";
                                                                        $personsResult = $con->query($personsQuery);
                                                                        while ($persons = $personsResult->fetch(PDO::FETCH_ASSOC)) {
                                                                            echo "<option value='{$persons['ID']}'>{$persons['full_name']}</option>";
                                                                        }
                                                                        ?>
                                                                    </select>
                                                                    </td>
                                                                    <td>
                                                                    <select name="id_currency_codes" class="form-select" required>
                                                                            <?php
                                                                            if (empty($id_currency_codes)) {
                                                                                $id_currency_codes = 1;
                                                                            }
                                                                            // Query to retrieve agents from the agents table
                                                                            $personsQuery = "SELECT * FROM currency where ID = $id_currency_codes ";
                                                                            $personsResult = $con->query($personsQuery);
                                                                            while ($persons = $personsResult->fetch(PDO::FETCH_ASSOC)) {
                                                                                echo "<option value='{$persons['ID']}'>{$persons['currency_shortcut']}</option>";
                                                                            }
                                                                            $personsQuery = "SELECT * FROM currency where ID != $id_currency_codes ";
                                                                            $personsResult = $con->query($personsQuery);
                                                                            while ($persons = $personsResult->fetch(PDO::FETCH_ASSOC)) {
                                                                                echo "<option value='{$persons['ID']}'>{$persons['currency_shortcut']}</option>";
                                                                            }

                                                                            if ($id_currency_codes == 1) {
                                                                                $costemp = getIdTowVal('booking_file', 'id_line_type', 4,'id_line_booking',$value['id_booking'],'total_cost');
                                                                            } else {
                                                                                $costemp = $amountSold;
                                                                            }
                                                                            ?>
                                                                    </select>
                                                                    </td>
                                                                    <td>
                                                                    <input type="text" name="cost" value="<?=$costemp?>" class="form-control form-control-sm" placeholder="التكلفة" required>
                                                                    </td>
                                                                    <td>
                                                                        <!-- <button type="submit" class="btn btn-primary" name="add_numper">حفظ</button> -->
                                                                    </td>
                                                                </tr>
                                                            </table>
                                                        </div>
                                                        <div class="modal-footer">
                                                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                                                            <button type="submit" class="btn btn-primary" name="add_employeesM">حفظ</button>
                                                        </div>
                                                    </form>
                                                        </div>
                                                    </div>
                                                </div>
                                            </td>
                                            </tr>   
                                            <?php
                                        }
                                    } else {
                                        echo "<tr>
                                            <td>لا يوجد</td>
                                            <td>لا يوجد</td>
                                            <td>لا يوجد</td>
                                            <td>Control</td>
                                            </tr>";
                                    }
                                    ?>
                                    <tr>
                                        <td>
                                        <form action="?do=insert_in_file" method="post">
                                            <input type="hidden" name="reservation_id" value="<?php echo $reservation_id; ?>">
                                            <select name="id_employees" class="form-select" required>
                                                <?php
                                                // Query to retrieve agents from the agents table
                                                $personsQuery = "SELECT * FROM employees where id_department_employees = 1";
                                                $personsResult = $con->query($personsQuery);
                                                echo "<option value=''>اختر المندوب</option>";
                                                while ($persons = $personsResult->fetch(PDO::FETCH_ASSOC)) {
                                                    echo "<option value='{$persons['ID']}'>{$persons['full_name']}</option>";
                                                }
                                                ?>
                                            </select>
                                        </td>
                                        <td>
                                            <select name="id_currency_codes" class="form-select" required>
                                                    <?php
                                                    // Query to retrieve agents from the agents table
                                                    echo "<option value=''>حدد العملة</option>";
                                                    $personsQuery = "SELECT * FROM currency ";
                                                    $personsResult = $con->query($personsQuery);
                                                    while ($persons = $personsResult->fetch(PDO::FETCH_ASSOC)) {
                                                        echo "<option value='{$persons['ID']}'>{$persons['currency_shortcut']}</option>";
                                                    }
                                                    ?>
                                            </select>
                                        </td>
                                        <td>
                                            <input type="text" name="cost" class="form-control form-control-sm" placeholder="التكلفة" required>
                                        </td>
                                        <td>
                                            <button type="submit" class="btn btn-primary" name="add_employeesM">حفظ</button>
                                            </form>
                                        </td>
                                    </tr>
                                </table>
                            
                        </div>
                        <div class="col-md-6 mb-3">
                        </div>
                        <div class="col-md-6 mb-3">
                            <h1 class="input-group-text text-center"><i class="fa-solid fa-address-card"></i>&nbsp; المرشد السياحى</h1>
                            <form action="?do=insert_in_file" method="post">
                            <table class='main-table text-center table table-bordered'>
                                <tr>
                                    <td>الإسم</td>
                                    <td>رقم الهاتف</td>
                                    <td>التكلفة</td>
                                    <td>Control</td>
                                </tr>
                                    <?php
                                    if (!empty($employee_bookings_SH)) {
                                        foreach ($employee_bookings_SH as $value) {

                                            // $cost_morshed = getIdTowVal('invoicing_line', 'id_type', 3,'id_line_booking',$value['id_booking'],'total_invoice');
                                            $cost_morshed = getIdTowVal('booking_file', 'id_line_type', 3,'id_line_booking',$value['id_booking'],'total_cost');
                                            $id_currency_codes = getIdTowVal('booking_file', 'id_line_type', 3,'id_line_booking',$value['id_booking'],'id_currency_codes');
                                            $amountSold = getIdTowVal('booking_file', 'id_line_type', 3,'id_line_booking',$value['id_booking'],'amountSold');
                                            $currencyExchangeRate = getIdTowVal('booking_file', 'id_line_type', 3,'id_line_booking',$value['id_booking'],'currencyExchangeRate');
                                            $currency_code = getId('currency', 'ID', $id_currency_codes , 'currency_code');
                                            if ($id_currency_codes ==2  && $amountSold != 0) {
                                                $cost_morshed = $amountSold;
                                            } elseif($id_currency_codes == 1) {
                                                $cost_morshed = $cost_morshed * $currencyExchangeRate;
                                                $currency_code = getId('currency', 'ID', 2 , 'currency_code');
                                            } else {
                                                $currency_code = getId('currency', 'ID', 2 , 'currency_code');
                                                $currencyExchangeRateUSD = getId('currency', 'ID', 2,'currencyExchangeRate');
                                                $currencyExchangeRateEGP = 1 / $currencyExchangeRateUSD;
                                                $cost_morshed = $cost_morshed * $currencyExchangeRateEGP;
                                                $cost_morshed = ceil($cost_morshed * 100) / 100;
                                            }
                                            echo "<tr>
                                            <td>{$value['full_name']}</td>
                                            <td>{$value['phone_number']}</td>
                                            <td>\${$cost_morshed}</td>
                                            ";
                                            ?>
                                            <td>
                                                <button type="button" class="btn btn-success btn-sm" data-bs-toggle="modal" data-bs-target="#modal_-<?php echo $value['id_booking'] ?>" title="تعديل">
                                                    <i class='fa fa-edit'></i>
                                                </button>
                                                <!-- Modal -->
                                                <div class="modal fade" id="modal_-<?php echo $value['id_booking'] ?>" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
                                                    <div class="modal-dialog modal-xl">
                                                        <div class="modal-content">
                                                        <div class="modal-header">
                                                            <h1 class="modal-title fs-5" id="staticBackdropLabel">Modal title</h1>
                                                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                                        </div>
                                                        <form action="?do=insert_in_file" method="post">
                                                            <div class="modal-body">
                                                            <input type="hidden" name="id_employee_booking" id="id_employee_booking" value="<?=$value['id_booking'] ?>">
                                                            <table class='main-table text-center table table-bordered'>
                                                                <tr>
                                                                </tr>
                                                                <tr>
                                                                    <td>
                                                                    <input type="hidden" name="reservation_id" value="<?php echo $reservation_id; ?>">
                                                                    <?php
                                                                    // $id_persons = getId('number_individuals', 'ID', $value['ID'], 'id_persons');
                                                                    // $id_persons = $value['id_persons'];
                                                                    ?>              
                                                                    <select name="id_employees" class="form-select" required>
                                                                        <?php
                                                                        // Query to retrieve agents from the agents table
                                                                        $id_employee = $value['id_employee'];
                                                                        $personsQuery = "SELECT * FROM employees where ID = $id_employee";
                                                                        $personsResult = $con->query($personsQuery);
                                                                        while ($persons = $personsResult->fetch(PDO::FETCH_ASSOC)) {
                                                                            echo "<option value='{$persons['ID']}'>{$persons['full_name']}</option>";
                                                                        }
                                                                        $personsQuery = "SELECT * FROM employees where id_department_employees = 1 AND ID != $id_employee";
                                                                        $personsResult = $con->query($personsQuery);
                                                                        while ($persons = $personsResult->fetch(PDO::FETCH_ASSOC)) {
                                                                            echo "<option value='{$persons['ID']}'>{$persons['full_name']}</option>";
                                                                        }
                                                                        ?>
                                                                    </select>
                                                                    </td>
                                                                    <td>
                                                                    <select name="id_currency_codes" class="form-select" required>
                                                                            <?php
                                                                            if (empty($id_currency_codes)) {
                                                                                $id_currency_codes = 1;
                                                                            }
                                                                            // Query to retrieve agents from the agents table
                                                                            $personsQuery = "SELECT * FROM currency where ID = $id_currency_codes ";
                                                                            $personsResult = $con->query($personsQuery);
                                                                            while ($persons = $personsResult->fetch(PDO::FETCH_ASSOC)) {
                                                                                echo "<option value='{$persons['ID']}'>{$persons['currency_shortcut']}</option>";
                                                                            }
                                                                            $personsQuery = "SELECT * FROM currency where ID != $id_currency_codes ";
                                                                            $personsResult = $con->query($personsQuery);
                                                                            while ($persons = $personsResult->fetch(PDO::FETCH_ASSOC)) {
                                                                                echo "<option value='{$persons['ID']}'>{$persons['currency_shortcut']}</option>";
                                                                            }

                                                                            if ($id_currency_codes == 1) {
                                                                                $costemp = getIdTowVal('booking_file', 'id_line_type', 3,'id_line_booking',$value['id_booking'],'total_cost');
                                                                            } else {
                                                                                $costemp = $amountSold;
                                                                            }
                                                                            ?>
                                                                    </select>
                                                                    </td>
                                                                    <td>
                                                                    <input type="text" name="cost" value="<?=$costemp?>" class="form-control form-control-sm" placeholder="التكلفة" required>
                                                                    </td>
                                                                    <td>
                                                                        <!-- <button type="submit" class="btn btn-primary" name="add_numper">حفظ</button> -->
                                                                    </td>
                                                                </tr>
                                                            </table>
                                                        </div>
                                                        <div class="modal-footer">
                                                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                                                            <button type="submit" class="btn btn-primary" name="add_employeesSH">حفظ</button>
                                                        </div>
                                                    </form>
                                                        </div>
                                                    </div>
                                                </div>
                                            </td>
                                            </tr>   
                                            <?php
                                        }
                                    } else {
                                        echo "<tr>
                                            <td>لا يوجد</td>
                                            <td>لا يوجد</td>
                                            <td>لا يوجد</td>
                                            <td>Control</td>
                                            </tr>";
                                    }
                                    ?>
                                <tr>
                                    <td>
                                    <form action="?do=insert_in_file" method="post">
                                        <input type="hidden" name="reservation_id" value="<?php echo $reservation_id; ?>">
                                        <select name="id_employees" class="form-select" required>
                                            <?php
                                            // Query to retrieve agents from the agents table
                                            $personsQuery = "SELECT * FROM employees where id_department_employees = 2";
                                            $personsResult = $con->query($personsQuery);
                                            echo "<option value=''>اختر المرشد السياحى</option>";
                                            while ($persons = $personsResult->fetch(PDO::FETCH_ASSOC)) {
                                                echo "<option value='{$persons['ID']}'>{$persons['full_name']}</option>";
                                            }
                                            ?>
                                        </select>
                                    </td>
                                    <td>
                                        <select name="id_currency_codes" class="form-select" required>
                                                <?php
                                                // Query to retrieve agents from the agents table
                                                echo "<option value=''>حدد العملة</option>";
                                                $personsQuery = "SELECT * FROM currency ";
                                                $personsResult = $con->query($personsQuery);
                                                while ($persons = $personsResult->fetch(PDO::FETCH_ASSOC)) {
                                                    echo "<option value='{$persons['ID']}'>{$persons['currency_shortcut']}</option>";
                                                }
                                                ?>
                                        </select>
                                    </td>
                                    <td>
                                        <input type="text" name="cost" class="form-control form-control-sm" placeholder="التكلفة بالدولار" required>
                                    </td>
                                    <td>
                                        <button type="submit" class="btn btn-primary" name="add_employeesSH">حفظ</button>
                                        </form>
                                    </td>
                                </tr>
                            </table>
                            
                        </div>
                        <div class="col-md-12 mb-3">
                            <h1 class="input-group-text text-center"><i class="fa-solid fa-bed"></i>&nbsp; حجز غرف </h1>
                            <table class='main-table text-center table table-bordered'>
                                <tr>
                                    <td>اسم الفندق</td>
                                    <td>الغرف</td>
                                    <td>نوع الإقامة</td>
                                    <td>عدد الغرف</td>
                                    <td>عدد الأفراد</td>
                                    <td>الإطلالة</td>
                                    <td>من تاريخ</td>
                                    <td>الى تاريخ</td>
                                    <td>عدد الليالى</td>
                                    <td>عدد الأطفال</td>
                                    <td>مجانى</td>
                                    <td>التكلفة</td>
                                    <td>ملاحظات</td>
                                    <td>Control</td>
                                </tr>
                                <?php
                                if (!empty($hotel_bookings)) {
                                    foreach ($hotel_bookings as $value) {
                                        $calculatedates = $reservationsManager->calculateNightAndDayCount($value['check_in_date'], $value['check_out_date']);
                                        $currency_code = getName('currency', 'ID', $value['id_currency_codes'] , 'currency_code');
                                        if ($value['id_currency_codes'] != 1 && $value['amountSold'] != 0) {
                                            $price = $value['amountSold'];
                                            $price_sale = $value['amountSold_sale'];
                                        } else {
                                        }

                                        $invaled_number = $value['invaled_number'];

                                        if (empty($invaled_number)) {
                                            if ($value['code_2'] == "X" || $value['code_1'] == "SGL") {
                                                $price = $value['rooms_number'] * $price;
                                                $price *= $calculatedates['number_of_nights'];
                                            } elseif ($value['code_2'] == "XX" || $value['code_1'] == "DBL") {
                                                $price = $value['rooms_number'] * $price;
                                                $price *= 2;
                                                $price *= $calculatedates['number_of_nights'];
                                            } elseif ($value['code_2'] == "XXX" || $value['code_1'] == "TPL") {
                                                $price = $value['rooms_number'] * $price;
                                                $price *= 3;
                                                $price *= $calculatedates['number_of_nights'];
                                            } else {
                                                $price = $value['rooms_number'] * $price;
                                                $price *= $calculatedates['number_of_nights'];
                                            }
                                        } else {
                                            $price = ($invaled_number * $price) * $calculatedates['number_of_nights'];
                                        }

                                        $check_status = $value['check_status'];
                                        if ($check_status == 'off') {
                                            $cs = "<form action='?do=insert_in_file' method='post'>
                                            <input type='hidden' name='id_hotel_bookings' value='{$value['id_hotel_bookings']}'>
                                            <button type='submit' class='btn btn-primary' name='reservation_confirmation'>تأكيد</button>
                                            </form>";
                                        } else {
                                            $cs = "حجز مؤكد";
                                        }
                                        
                                        if ($value['cost_children'] > 0 && $value['children_number'] > 0) {
                                            $all_cost_children = ($value['cost_children'] * $value['children_number']) * $calculatedates['number_of_nights'];
                                            $price += $all_cost_children;
                                        }

                                        $price = $price - $value['discount_free'];
                                        ?>
                                        <tr>
                                            <?php
                                            echo "
                                            <td>{$value['hotel_name']}</td>
                                            <td>{$value['code_1']}</td>
                                            <td>{$value['short_name']}</td>
                                            <td style=\"direction: ltr;\">{$value['rooms_number']} {$value['code_2']}</td>
                                            <td>{$value['invaled_number']}</td>
                                            <td>{$value['room_disc']}</td>
                                            <td>{$value['check_in_date']}</td>
                                            <td>{$value['check_out_date']}</td>
                                            <td>{$calculatedates['number_of_nights']} ليلة</td>
                                            <td>{$value['children_number']}</td>
                                            <td>{$value['discount_free']}</td>
                                            <td>{$currency_code} {$price}</td>
                                            <td>{$value['note']}</td>";
                                            ?>
                                            <td>
                                            <button type="button" class="btn btn-success btn-sm" data-bs-toggle="modal" data-bs-target="#modal_edit_items-<?php echo $value['id_hotel_bookings'] ?>" title="تعديل">
                                                <i class='fa fa-edit'></i>
                                            </button>
                                            <!-- Modal -->
                                            <div class="modal fade" id="modal_edit_items-<?php echo $value['id_hotel_bookings'] ?>" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
                                                <div class="modal-dialog modal-xl">
                                                    <div class="modal-content">
                                                    <div class="modal-header">
                                                        <h1 class="modal-title fs-5" id="staticBackdropLabel">Modal title</h1>
                                                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                                    </div>
                                                    <div class="modal-body">
                                                    <form action="?do=insert_in_file" method="post">
                                                    <input type="hidden" name="id_hotel_bookings" id="id_hotel_bookings" value="<?=$value['id_hotel_bookings'] ?>">
                                                        <?php
                                                            $hotel_bookings = $reservationsManager->getHotelBookingsById($value['id_hotel_bookings'] );
                                                            foreach ($hotel_bookings as $key => $value_hotel_bookings) {

                                                                $date_go = getId('hotel_booking_pay_arr', 'id_hotel_booking', $value_hotel_bookings['ID'], 'date_go');
                                                                $cash_payment = getId('hotel_booking_pay_arr', 'id_hotel_booking', $value_hotel_bookings['ID'], 'cash');
                                                                
                                                                $room_disc = getId('room_prices', 'ID', $value_hotel_bookings['id_room_prices'], 'room_disc');
                                                                $id_currency_codes = getId('room_prices', 'ID', $value_hotel_bookings['id_room_prices'], 'id_currency_codes');

                                                                if ($id_currency_codes == 1) {
                                                                    $amountSold = getId('room_prices', 'ID', $value_hotel_bookings['id_room_prices'], 'price');
                                                                } else {
                                                                    $amountSold = getId('room_prices', 'ID', $value_hotel_bookings['id_room_prices'], 'amountSold');
                                                                }
                                                                ?>
                                                                <table  class='main-table text-center table table-bordered'>
                                                                    <tr>
                                                                    </tr>
                                                                    <tr>
                                                                        <td>
                                                                            <input type="hidden" name="reservation_id" value="<?php echo $reservation_id; ?>">
                                                                            <select name="id_hotels" class="form-select " required>
                                                                                <?php
                                                                                // Query to retrieve agents from the agents table
                                                                                $id_hotel = $value_hotel_bookings['id_hotel'];
                                                                                $personsQuery = "SELECT * FROM hotels where ID = $id_hotel";
                                                                                $personsResult = $con->query($personsQuery);
                                                                                while ($persons = $personsResult->fetch(PDO::FETCH_ASSOC)) {
                                                                                    echo "<option value='{$persons['ID']}'>{$persons['hotel_name']}</option>";
                                                                                }
                                                                                ?>
                                                                                <?php
                                                                                // Query to retrieve agents from the agents table
                                                                                $personsQuery = "SELECT * FROM hotels where ID != $id_hotel";
                                                                                $personsResult = $con->query($personsQuery);
                                                                                while ($persons = $personsResult->fetch(PDO::FETCH_ASSOC)) {
                                                                                    echo "<option value='{$persons['ID']}'>{$persons['hotel_name']}</option>";
                                                                                }
                                                                                ?>
                                                                            </select>
                                                                        </td>
                                                                        <td>
                                                                            <select name="id_room_type" class="form-select" required>
                                                                                <?php
                                                                                $id_room_type = getId('room_prices', 'ID', $value_hotel_bookings['id_room_prices'], 'id_room_type');
                                                                                // Query to retrieve agents from the agents table
                                                                                $personsQuery = "SELECT * FROM room_type where ID = $id_room_type";
                                                                                $personsResult = $con->query($personsQuery);
                                                                                while ($persons = $personsResult->fetch(PDO::FETCH_ASSOC)) {
                                                                                    echo "<option value='{$persons['ID']}'>{$persons['code_1']}</option>";
                                                                                }
                                                                                $personsQuery = "SELECT * FROM room_type where ID != $id_room_type";
                                                                                $personsResult = $con->query($personsQuery);
                                                                                while ($persons = $personsResult->fetch(PDO::FETCH_ASSOC)) {
                                                                                    echo "<option value='{$persons['ID']}'>{$persons['code_1']}</option>";
                                                                                }
                                                                                ?>
                                                                            </select>
                                                                        </td>
                                                                        <td>
                                                                            <select name="id_meal_system" class="form-select" required>
                                                                                <?php
                                                                                $id_meal_system = getId('room_prices', 'ID', $value_hotel_bookings['id_room_prices'], 'id_meal_system');
                                                                                // Query to retrieve agents from the agents table
                                                                                $personsQuery = "SELECT * FROM meal_system where ID = $id_meal_system";
                                                                                $personsResult = $con->query($personsQuery);
                                                                                while ($persons = $personsResult->fetch(PDO::FETCH_ASSOC)) {
                                                                                    echo "<option value='{$persons['ID']}'>{$persons['short_name']}</option>";
                                                                                }
                                                                                $personsQuery = "SELECT * FROM meal_system where ID != $id_meal_system";
                                                                                $personsResult = $con->query($personsQuery);
                                                                                while ($persons = $personsResult->fetch(PDO::FETCH_ASSOC)) {
                                                                                    echo "<option value='{$persons['ID']}'>{$persons['short_name']}</option>";
                                                                                }
                                                                                ?>
                                                                            </select>
                                                                        </td>
                                                                        <td>
                                                                            <input type="text" name="rooms_numper" value="<?=$value_hotel_bookings['rooms_number']?>" class="form-control form-control-sm" placeholder="عدد الغرف"
                                                                                required>
                                                                        </td>
                                                                        <td>
                                                                            <input type="text" name="disc" value="<?=$room_disc?>" class="form-control form-control-sm" placeholder="الإطلالة" required>
                                                                        </td>
                                                                        <td>
                                                                            <label class="form-label">check in date</label>
                                                                            <input type="date" name="check_in_date" value="<?=$value_hotel_bookings['check_in_date']?>" class="form-control form-control-sm" placeholder="تاريخ الوصول" required>
                                                                        </td>
                                                                        <td>
                                                                        <label class="form-label">check out date</label>
                                                                            <input type="date" name="check_out_date" value="<?=$value_hotel_bookings['check_out_date']?>" class="form-control form-control-sm" placeholder="تاريخ المغادرة" required>
                                                                        </td>
                                                                        <td>
                                                                            <label class="form-label">العملة</label>
                                                                            <select name="id_currency_codes" class="form-select" required>
                                                                                <?php
                                                                                // Query to retrieve agents from the agents table
                                                                                $personsQuery = "SELECT * FROM currency where ID = $id_currency_codes";
                                                                                $personsResult = $con->query($personsQuery);
                                                                                while ($persons = $personsResult->fetch(PDO::FETCH_ASSOC)) {
                                                                                    echo "<option value='{$persons['ID']}'>{$persons['currency_shortcut']}</option>";
                                                                                }
                                                                                $personsQuery = "SELECT * FROM currency where ID != $id_currency_codes";
                                                                                $personsResult = $con->query($personsQuery);
                                                                                while ($persons = $personsResult->fetch(PDO::FETCH_ASSOC)) {
                                                                                    echo "<option value='{$persons['ID']}'>{$persons['currency_shortcut']}</option>";
                                                                                }
                                                                                ?>
                                                                            </select>
                                                                            <!-- <input type="text" name="currencyExchangeRate" class="form-control form-control-sm" placeholder="سعر الصرف" > -->
                                                                        </td>
                                                                        
                                                                    </tr>
                                                                    <tr>
                                                                        <td colspan="1">
                                                                            <label class="form-label">عدد الاطفال</label>
                                                                            <input type="number" name="children_number" class="form-control form-control-sm" min="0" placeholder="عدد الاطفال" value="<?=$value_hotel_bookings['children_number']?>">
                                                                        </td>
                                                                        <td colspan="1">
                                                                            <label class="form-label">تكلفة الطفل</label>
                                                                            <input type="text" name="cost_children" class="form-control form-control-sm"  value="<?=$value_hotel_bookings['cost_children']?>" placeholder="تكلفة الطفل فى الليلة" title="تكلفة الطفل فى الليلة">
                                                                        </td>
                                                                        <td colspan="1">
                                                                            <label class="form-label">عدد الأفراد</label>
                                                                            <input type="text" name="invaled_number" class="form-control form-control-sm"  value="<?=$value_hotel_bookings['invaled_number']?>" placeholder="عدد الأفراد" title="عدد الأفراد" required>
                                                                        </td>
                                                                        <td colspan="1">
                                                                            <label class="form-label">تكلفة الفرد فى الليلة</label>
                                                                            <input type="text" name="price" class="form-control form-control-sm" value="<?=$amountSold?>" placeholder="سعر الفرد فى الليلة" title="سعر الفرد فى الليلة" required>
                                                                        </td>
                                                                        <td colspan="1">
                                                                            <select name="TAX" class="form-select" required>
                                                                                <?php
                                                                                if ($value_hotel_bookings['cost_children'] == 1) {
                                                                                    ?>
                                                                                    <option value='1'>يوجد ضريبة 3%</option>
                                                                                    <option value='0'>لا يوجد ضريبة 3%</option>
                                                                                    <?php
                                                                                } elseif($value_hotel_bookings['cost_children'] == 0) {
                                                                                    ?>
                                                                                    <option value='0'>لا يوجد ضريبة 3%</option>
                                                                                    <option value='1'>يوجد ضريبة 3%</option>
                                                                                    <?php
                                                                                } else {
                                                                                    ?>
                                                                                    <option>حدد الضريبة</option>
                                                                                    <option value='0'>لا يوجد ضريبة 3%</option>
                                                                                    <option value='1'>يوجد ضريبة 3%</option>
                                                                                    <?php
                                                                                }
                                                                                ?>
                                                                            </select>
                                                                        </td>
                                                                        <td>
                                                                            <label class="form-label">تاريخ ال payment</label>
                                                                            <input type="date" name="payment_date" value="<?=$date_go?>" class="form-control form-control-sm" placeholder="تاريخ payment" title="تاريخ payment" required>
                                                                        </td>
                                                                        <td>
                                                                            <label class="form-label">مبلغ ال payment</label>
                                                                            <input type="text" name="payment_cash" value="<?=$cash_payment?>" class="form-control form-control-sm" placeholder="مبلغ ال payment" >
                                                                        </td>
                                                                        <td>
                                                                            <input type="text" name="note" value="<?=$value_hotel_bookings['note']?>" class="form-control form-control-sm" placeholder="ملاحظة">
                                                                            <br>
                                                                            <button type="submit" class="btn btn-primary" name="hotel_booking">حفظ</button>
                                                                        </td>
                                                                    </tr>
                                                                </table>
                                                                <?php
                                                            } ?>
                                                    </form>
                                                    </div>
                                                    <div class="modal-footer">
                                                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                                                        <!-- <button type="submit" class="btn btn-primary" name="hotel_booking">حفظ</button> -->
                                                    </div>
                                                    </div>
                                                </div>
                                            </div>
                                            </td>
                                        </tr>
                                        <?php
                                    }
                                } else {
                                    echo "<tr>
                                        <td>لا يوجد</td>
                                        <td>لا يوجد</td>
                                        <td>لا يوجد</td>
                                        <td>لا يوجد</td>
                                        <td>لا يوجد</td>
                                        <td>لا يوجد</td>
                                        <td>لا يوجد</td>
                                        <td>لا يوجد</td>
                                        <td>لا يوجد</td>
                                        <td>لا يوجد</td>
                                        <td>Control</td>
                                        </tr>";
                                }
                                ?>
                                
                            </table>
                            <form action="?do=insert_in_file" method="post">
                                <table  class='main-table text-center table table-bordered'>
                                    <tr>
                                    </tr>
                                    <tr>
                                        <td>
                                            <input type="hidden" name="reservation_id" value="<?php echo $reservation_id; ?>">
                                            <select name="id_hotels" class="form-select getsearch" required>
                                                <?php
                                                // Query to retrieve agents from the agents table
                                                $personsQuery = "SELECT * FROM hotels";
                                                $personsResult = $con->query($personsQuery);
                                                echo "<option value=''>الفندق</option>";
                                                while ($persons = $personsResult->fetch(PDO::FETCH_ASSOC)) {
                                                    echo "<option value='{$persons['ID']}'>{$persons['hotel_name']}</option>";
                                                }
                                                ?>
                                            </select>
                                        </td>
                                        <td>
                                            <select name="id_room_type" class="form-select" required>
                                                <?php
                                                // Query to retrieve agents from the agents table
                                                $personsQuery = "SELECT * FROM room_type";
                                                $personsResult = $con->query($personsQuery);
                                                echo "<option value=''>الغرفة</option>";
                                                while ($persons = $personsResult->fetch(PDO::FETCH_ASSOC)) {
                                                    echo "<option value='{$persons['ID']}'>{$persons['code_1']}</option>";
                                                }
                                                ?>
                                            </select>
                                        </td>
                                        <td>
                                            <select name="id_meal_system" class="form-select" required>
                                                <?php
                                                // Query to retrieve agents from the agents table
                                                $personsQuery = "SELECT * FROM meal_system";
                                                $personsResult = $con->query($personsQuery);
                                                echo "<option value=''>الإقامة</option>";
                                                while ($persons = $personsResult->fetch(PDO::FETCH_ASSOC)) {
                                                    echo "<option value='{$persons['ID']}'>{$persons['short_name']}</option>";
                                                }
                                                ?>
                                            </select>
                                        </td>
                                        <td>
                                            <input type="text" name="rooms_numper" class="form-control form-control-sm" placeholder="عدد الغرف"
                                                required>
                                        </td>
                                        <td>
                                            <input type="text" name="disc" class="form-control form-control-sm" placeholder="الإطلالة" required>
                                        </td>
                                        <td>
                                            <label class="form-label">check in date</label>
                                            <input type="date" name="check_in_date" class="form-control form-control-sm" placeholder="تاريخ الوصول" required>
                                        </td>
                                        <td>
                                        <label class="form-label">check out date</label>
                                            <input type="date" name="check_out_date" class="form-control form-control-sm" placeholder="تاريخ المغادرة" required>
                                        </td>
                                        <td>
                                            <label class="form-label">العملة</label>
                                            <select name="id_currency_codes" class="form-select" required>
                                                <?php
                                                // Query to retrieve agents from the agents table
                                                $personsQuery = "SELECT * FROM currency where ID = 2";
                                                $personsResult = $con->query($personsQuery);
                                                while ($persons = $personsResult->fetch(PDO::FETCH_ASSOC)) {
                                                    echo "<option value='{$persons['ID']}'>{$persons['currency_shortcut']}</option>";
                                                }
                                                $personsQuery = "SELECT * FROM currency where ID != 2";
                                                $personsResult = $con->query($personsQuery);
                                                while ($persons = $personsResult->fetch(PDO::FETCH_ASSOC)) {
                                                    echo "<option value='{$persons['ID']}'>{$persons['currency_shortcut']}</option>";
                                                }
                                                ?>
                                            </select>
                                            <!-- <input type="text" name="currencyExchangeRate" class="form-control form-control-sm" placeholder="سعر الصرف" > -->
                                        </td>
                                        
                                    </tr>
                                    <tr>
                                        <td colspan="1">
                                            <label class="form-label">عدد الأطفال</label>
                                            <input type="number" name="children_number" class="form-control form-control-sm" min="0" placeholder="عدد الاطفال" >
                                        </td>
                                        <td colspan="1">
                                            <label class="form-label">تكلفة الطفل</label>
                                            <input type="text" name="cost_children" class="form-control form-control-sm" placeholder="تكلفة الطفل فى الليلة" title="تكلفة الطفل فى الليلة">
                                        </td>
                                        <td colspan="1">
                                            <label class="form-label">عدد الأفراد</label>
                                            <input type="text" name="invaled_number" class="form-control form-control-sm" placeholder="عدد الأفراد" title="عدد الأفراد" required>
                                        </td>
                                        <td colspan="1">
                                            <label class="form-label">تكلفة الفرد فى الليلة</label>
                                            <input type="text" name="price" class="form-control form-control-sm" placeholder="تكلفة الفرد فى الليلة" title="تكلفة الفرد فى الليلة" required>
                                        </td>
                                        <td colspan="1">
                                            <select name="TAX" class="form-select" required>
                                                    <option>حدد الضريبة</option>
                                                    <option value='0'>لا يوجد ضريبة 3%</option>
                                                    <option value='1'>يوجد ضريبة 3%</option>
                                            </select>
                                        </td>
                                        <td>
                                            <label class="form-label">تاريخ ال payment</label>
                                            <input type="date" name="payment_date" class="form-control form-control-sm" placeholder="تاريخ payment" title="تاريخ payment" required>
                                        </td>
                                        <td>
                                            <label class="form-label">مبلغ ال payment</label>
                                            <input type="text" name="payment_cash" class="form-control form-control-sm" placeholder="مبلغ ال payment" >
                                        </td>
                                        <td>
                                            <input type="text" name="note" class="form-control form-control-sm" placeholder="ملاحظة">
                                            <br>
                                            <button type="submit" class="btn btn-primary" name="hotel_booking">حفظ</button>
                                        </td>
                                    </tr>
                                </table>
                            </form>
                        </div>
                        <div class="col-md-12 mb-3">
                            <h1 class="input-group-text text-center"><i class="fa-solid fa-bus-simple"></i>&nbsp; النقل السياحي </h1>
                            <form action="?do=insert_in_file" method="post">
                                <table class='main-table text-center table table-bordered'>
                                    <tr>
                                        <td>الشركة المؤجرة</td>
                                        <td>رقم السيارة / سعة السيارة</td>
                                        <td>السائق</td>
                                        <td>المندوب أو المرشد</td>
                                        <td>عدد الافراد</td>
                                        <td>تاريخ البداية</td>
                                        <td>تاريخ العودة</td>
                                        <td>بيان التشغيل</td>
                                        <td>مدير الحركة</td>
                                        <td>التكلفة</td>
                                        <!-- <td>سعر البيع</td> -->
                                        <td>ملاحظات</td>
                                        <td>Control</td>
                                    </tr>
                                    <?php
                                    if (!empty($Transportation_bookings)) {
                                        foreach ($Transportation_bookings as $value) {

                                            // $id_currency_codes = getIdTowVal('booking_file', 'id_line_type', 4,'id_line_booking',$value['id_booking'],'id_currency_codes');
                                            // $amountSold = getIdTowVal('booking_file', 'id_line_type', 4,'id_line_booking',$value['id_booking'],'amountSold');
                                            // $currencyExchangeRate = getIdTowVal('booking_file', 'id_line_type', 4,'id_line_booking',$value['id_booking'],'currencyExchangeRate');
                                            $currency_code = getId('currency', 'ID', $value['id_currency_codes'] , 'currency_code');

                                            $price = $value['total_cost'];

                                            if ($value['id_currency_codes'] == 2 && $value['amountSold'] != 0) {
                                                $price = $value['amountSold'];
                                                $total_cost = $price ;
                                            } elseif($value['id_currency_codes'] == 1) {
                                                $price = $value['total_cost'] * $value['currencyExchangeRate'];
                                                $total_cost = $price ;
                                                $currency_code = getId('currency', 'ID', 2 , 'currency_code');
                                            } else {
                                                // $price = $value['total_cost'];
                                                $currency_code = getId('currency', 'ID', 2 , 'currency_code');
                                                $currencyExchangeRateUSD = getId('currency', 'ID', 2,'currencyExchangeRate');
                                                $currencyExchangeRateEGP = 1 / $currencyExchangeRateUSD;
                                                $total_cost = $price;
                                                $price = $value['total_cost'] * $currencyExchangeRateEGP;
                                                $price = ceil($price * 100) / 100;
                                            }
                                            $name_companies_transportation = getName('companies_transportation', 'ID', $value['id_companies_transportation'], 'name_companie');
                                            // $driver_name = getName('drivers', 'ID', $value['id_driver'], 'driver_name');
                                            $id_employee_M = getName('employees', 'ID', $value['id_employee_M'], 'full_name');
                                            $id_employee_mang = getName('employees', 'ID', $value['id_employee_mang'], 'full_name');
                                            echo "<tr>
                                            <td>{$name_companies_transportation}</td>
                                            <td>{$value['no_car']} / {$value['vehicle_capacity']} راكب</td>
                                            <td>{$value['name_driver']}</td>
                                            <td>{$id_employee_M}</td>
                                            <td>{$value['number_individuals']} فرد</td>
                                            <td>{$value['date_run']} {$value['hour_doing']}</td>
                                            <td>{$value['date_out']} {$value['hour_return']}</td>
                                            <td>{$value['operation_statement']}</td>
                                            <td>{$id_employee_mang}</td>
                                            <td>$currency_code {$total_cost}</td>
                                            <td>{$value['nots_run']}</td>
                                            <td>تعديل</td>
                                            </tr>";
                                            /* <td>$currency_code {$total_cost_sale}</td> */
                                        }
                                    } else {
                                        echo "<tr>
                                            <td>لا يوجد</td>
                                            <td>لا يوجد</td>
                                            <td>لا يوجد</td>
                                            <td>لا يوجد</td>
                                            <td>لا يوجد</td>
                                            <td>لا يوجد</td>
                                            <td>لا يوجد</td>
                                            <td>لا يوجد</td>
                                            <td>لا يوجد</td>
                                            <td>لا يوجد</td>
                                            <td>لا يوجد</td>
                                            <td>Control</td>
                                            </tr>";
                                    }
                                    ?>
                                    <tr>
                                        <td>
                                            <input type="hidden" name="reservation_id" value="<?php echo $reservation_id; ?>">
                                            <!-- <input type="date" name="date_run" class="form-control" placeholder="تاريخ التشغيل" required> -->
                                            <div >
                                                <select name="companies_transportation" id="companies_transportation" class="form-select form-control-sm" required>
                                                    <?php
                                                    // Query to retrieve agents from the agents table
                                                    $agentsQuery = "SELECT * FROM companies_transportation";
                                                    $agentsResult = $con->query($agentsQuery);
                                                    echo "<option value=''>اختر الشركة</option>";
                                                    while ($agent = $agentsResult->fetch(PDO::FETCH_ASSOC)) {
                                                            echo "<option value='{$agent['ID']}'>{$agent['name_companie']}</option>";
                                                    }
                                                    ?>
                                                </select>
                                            </div>
                                        </td>
                                        <td>
                                            <div id="existingClientSelect" style="display: none;">
                                                <select name="id_vehicles" id="id_vehicles" class="form-select form-control-sm" >
                                                    <?php
                                                    // Query to retrieve agents from the agents table
                                                    $agentsQuery = "SELECT * FROM vehicles";
                                                    $agentsResult = $con->query($agentsQuery);
                                                    echo "<option value=''>اختر السيارة</option>";
                                                    while ($agent = $agentsResult->fetch(PDO::FETCH_ASSOC)) {
                                                            echo "<option value='{$agent['ID']}'>{$agent['vehicle_plate_number']}</option>";
                                                    }
                                                    ?>
                                                </select>
                                            </div>
                                            <div id="newClientFields" >
                                                <input type="text" name="car_num" class="form-control form-control-sm" placeholder="رقم السيارة" >
                                                <input type="text" name="vehicle_capacity" class="form-control form-control-sm" placeholder="سعة السيارة" >
                                            </div>
                                        </td>
                                        <td>
                                            <input type="text" name="drivers" class="form-control form-control-sm" placeholder="إسم السائق" required>
                                        </td>
                                        <td>
                                        <select name="id_employees" class="form-select" required>
                                        <?php
                                            // Query to retrieve agents from the agents table
                                            $personsQuery = "SELECT * FROM employees where id_department_employees = 1 OR id_department_employees = 2 ";
                                            $personsResult = $con->query($personsQuery);
                                            echo "<option value=''>اختر المرشد او المندوب</option>";
                                            while ($persons = $personsResult->fetch(PDO::FETCH_ASSOC)) {
                                                echo "<option value='{$persons['ID']}'>{$persons['full_name']}</option>";
                                            }
                                        ?>
                                        </select>
                                        </td>
                                        <td>
                                            <input type="text" name="number_individuals" class="form-control" placeholder="عدد الافراد" required>
                                        </td>
                                        <td colspan="">
                                            <input type="date" name="date_in" class="form-control form-control-sm" placeholder="تاريخ البداية" required>
                                            <input type="time" name="time_in" class="form-control form-control-sm" placeholder="ساعة القيام" title="ساعة القيام" >
                                        </td>
                                        <td>
                                            <input type="date" name="date_out" class="form-control form-control-sm" placeholder="تاريخ العودة" required>
                                            <input type="time" name="time_out" class="form-control form-control-sm" placeholder="ساعة العودة" title="ساعة العودة" >
                                        </td>
                                        <td>
                                            <input type="text" name="operation_statement" class="form-control" placeholder="بيان التشغيل" required>
                                        </td>
                                        <td>
                                            <select name="id_employee_mang" class="form-select" required>
                                            <?php
                                            // Query to retrieve agents from the agents table
                                            $personsQuery = "SELECT * FROM employees ";
                                            $personsResult = $con->query($personsQuery);
                                            echo "<option value=''>اختر مدير الحركة</option>";
                                            while ($persons = $personsResult->fetch(PDO::FETCH_ASSOC)) {
                                                echo "<option value='{$persons['ID']}'>{$persons['full_name']}</option>";
                                            }
                                            ?>
                                            </select>
                                            <select name="id_currency_codes" class="form-select" required>
                                                    <?php
                                                    // Query to retrieve agents from the agents table
                                                    $personsQuery = "SELECT * FROM currency where ID = 2";
                                                    $personsResult = $con->query($personsQuery);
                                                    while ($persons = $personsResult->fetch(PDO::FETCH_ASSOC)) {
                                                        echo "<option value='{$persons['ID']}'>{$persons['currency_shortcut']}</option>";
                                                    }
                                                    $personsQuery = "SELECT * FROM currency where ID != 2";
                                                    $personsResult = $con->query($personsQuery);
                                                    while ($persons = $personsResult->fetch(PDO::FETCH_ASSOC)) {
                                                        echo "<option value='{$persons['ID']}'>{$persons['currency_shortcut']}</option>";
                                                    }
                                                    ?>
                                            </select>
                                            <!-- <input type="text" name="currencyExchangeRate" class="form-control form-control-sm" placeholder="سعر الصرف" > -->
                                        </td>
                                        <td colspan="">
                                            <input type="text" name="price" class="form-control form-control-sm" placeholder="إجمالى تكلفة السيارة" required>
                                            <!-- <input type="text" name="price_sale" class="form-control form-control-sm" placeholder="إجمالى سعر البيع" required> -->
                                        </td>
                                        <td>
                                            <input type="text" name="remarks" class="form-control form-control-sm" placeholder="ملحوظة" >
                                        </td>
                                        <td>
                                            <button type="submit" class="btn btn-primary" name="transportation_booking">حفظ</button>
                                        </td>
                                    </tr>
                                </table>
                                <script>
                                    // كود جافا سكريبت لإظهار أو إخفاء حقول إضافة العميل الجديد
                                    $(document).ready(function () {
                                        $("#companies_transportation").change(function () {
                                            var accountup = $("#companies_transportation").val();
                                            var existingClientSelect = $("#existingClientSelect");
                                            var newClientFields = $("#newClientFields");
                                            if (accountup == 1) {
                                                existingClientSelect.css('display', 'block');
                                                newClientFields.css('display', 'none');
                                            } else {
                                                existingClientSelect.css('display', 'none');
                                                newClientFields.css('display', 'block');
                                            }
                                            return false;
                                        }).keyup();
                                    });
                                </script>
                            </form>
                        </div>
                        <?php
                        if ($id_management != 1) {
                        ?>
                        <div class="col-md-12 mb-3">
                            <h1 class="input-group-text text-center"><i class="fa-solid fa-plane-up"></i>&nbsp; حجز الطيران </h1>
                            <form action="?do=insert_in_file" method="post">
                                <table class='main-table text-center table table-bordered'>
                                    <tr>
                                        <td>شركة الطيران</td>
                                        <td>رقم الرحلة</td>
                                        <td>مطار المغادرة</td>
                                        <td>مطار الوصول</td>
                                        <td>تاريخ وموعد المغادرة</td>
                                        <td>تاريخ وموعد الوصول</td>
                                        <td>عدد التذاكر</td>
                                        <td>تكلفة التذكرة</td>
                                        <td>إجمالى التكلفة</td>
                                        <td>#</td>
                                    </tr>
                                    <?php
                                    if (!empty($flight_bookings)) {
                                        foreach ($flight_bookings as $value) {
                                            
                                            $currency_code = getId('currency', 'ID', $value['id_currency_codes'] , 'currency_code');

                                            $price = $value['total_cost'];

                                            if ($value['id_currency_codes'] == 2 && $value['amountSold'] != 0) {
                                                $price = $value['amountSold'];
                                                $total_cost = $price * $value['number_individuals'] ;
                                            } elseif($value['id_currency_codes'] == 1) {
                                                $price = $value['cost_individual'] * $value['currencyExchangeRate'];
                                                $total_cost = $price * $value['number_individuals'];
                                                $currency_code = getId('currency', 'ID', 2 , 'currency_code');
                                            } else {
                                                // $price = $value['total_cost'];
                                                $currency_code = getId('currency', 'ID', 2 , 'currency_code');
                                                $currencyExchangeRateUSD = getId('currency', 'ID', 2,'currencyExchangeRate');
                                                $currencyExchangeRateEGP = 1 / $currencyExchangeRateUSD;
                                                $price = $value['cost_individual'] * $currencyExchangeRateEGP;
                                                $total_cost = $price * $value['number_individuals'];
                                                $price = ceil($price * 100) / 100;
                                                $total_cost = ceil($total_cost * 100) / 100;
                                            }
                                            echo "<tr>
                                            <td>{$value['name_airline']}</td>
                                            <td>{$value['flight_number']}</td>
                                            <td>{$value['departure_airport']}</td>
                                            <td>{$value['arrival_airport']}</td>
                                            <td>{$value['departure_date']}{$value['departure_time']}</td>
                                            <td>{$value['arrival_date']}{$value['arrival_time']}</td>
                                            <td>{$value['number_individuals']} تذكرة</td>
                                            <td>$currency_code{$price}</td>
                                            <td>$currency_code{$total_cost}</td>
                                            <td>Control</td>
                                            </tr>";
                                        }
                                    } else {
                                        echo "<tr>
                                            <td>لا يوجد</td>
                                            <td>لا يوجد</td>
                                            <td>لا يوجد</td>
                                            <td>لا يوجد</td>
                                            <td>لا يوجد</td>
                                            <td>لا يوجد</td>
                                            <td>لا يوجد</td>
                                            <td>لا يوجد</td>
                                            <td>لا يوجد</td>
                                            <td>Control</td>
                                            </tr>";
                                    }
                                    ?>
                                    <tr>
                                        <td>
                                            <input type="hidden" name="reservation_id" value="<?php echo $reservation_id; ?>">
                                            <select name="id_airline" id="id_airline" class="form-select form-control-sm" required>
                                                <?php
                                                // Query to retrieve agents from the agents table
                                                $agentsQuery = "SELECT * FROM airline";
                                                $agentsResult = $con->query($agentsQuery);
                                                echo "<option value=''>اختر الشركة</option>";
                                                while ($agent = $agentsResult->fetch(PDO::FETCH_ASSOC)) {
                                                        echo "<option value='{$agent['ID']}'>{$agent['name_airline']}</option>";
                                                }
                                                ?>
                                            </select>
                                        </td>
                                        <td>
                                            <input type="text" name="flight_number" class="form-control form-control-sm" placeholder="رقم الرحلة" required>
                                        </td>
                                        <td>
                                            <input type="text" name="departure_station" class="form-control form-control-sm" placeholder="مطار المغادرة" required>
                                        </td>
                                        <td>
                                            <input type="text" name="arrival_station" class="form-control form-control-sm" placeholder="مطار الوصول" required>
                                        </td>
                                        <td>
                                            <input type="date" name="departure_date" class="form-control form-control-sm" placeholder="تاريخ المغادرة" required>
                                            <input type="time" name="departure_time" class="form-control form-control-sm" placeholder="وقت المغادرة" required>
                                        </td>
                                        <td>
                                            <input type="date" name="arrival_date" class="form-control form-control-sm" placeholder="تاريخ الوصول" required>
                                            <input type="time" name="arrival_time" class="form-control form-control-sm" placeholder="وقت الوصول" required>
                                        </td>
                                        <td>
                                            <input type="text" name="number_individuals" class="form-control form-control-sm" placeholder="عدد التذاكر" required>
                                            <select name="id_currency_codes" class="form-select" required>
                                                    <?php
                                                    // Query to retrieve agents from the agents table
                                                    $personsQuery = "SELECT * FROM currency where ID = 2";
                                                    $personsResult = $con->query($personsQuery);
                                                    while ($persons = $personsResult->fetch(PDO::FETCH_ASSOC)) {
                                                        echo "<option value='{$persons['ID']}'>{$persons['currency_shortcut']}</option>";
                                                    }
                                                    $personsQuery = "SELECT * FROM currency where ID != 2";
                                                    $personsResult = $con->query($personsQuery);
                                                    while ($persons = $personsResult->fetch(PDO::FETCH_ASSOC)) {
                                                        echo "<option value='{$persons['ID']}'>{$persons['currency_shortcut']}</option>";
                                                    }
                                                    ?>
                                            </select>
                                            <!-- <input type="text" name="currencyExchangeRate" class="form-control form-control-sm" placeholder="سعر الصرف" > -->
                                        </td>
                                        <td>
                                            <input type="text" name="price" class="form-control form-control-sm" placeholder="تكلفة التذكرة" required>
                                        </td>
                                        <td>
                                            <!-- <input type="text" name="price_sale" class="form-control form-control-sm" placeholder="سعر بيع التذكرة" required> -->
                                        </td>
                                        <td>
                                            <button type="submit" class="btn btn-primary" name="airline_booking">حفظ</button>
                                            
                                        </td>
                                    </tr>
                                </table>
                            </form>
                        </div>
                        <div class="col-md-12 mb-3">
                            <h1 class="input-group-text text-center"><i class="fa-solid fa-train"></i>&nbsp; حجز قطار </h1>
                            <form action="?do=insert_in_file" method="post">
                                <table class='main-table text-center table table-bordered'>
                                    <tr>
                                        <td>رقم القطار</td>
                                        <td>محطة المغادرة</td>
                                        <td>محطة الوصول</td>
                                        <td>موعد المغادرة</td>
                                        <td>موعد الوصول</td>
                                        <td>عدد التذاكر</td>
                                        <td>سعر التكلفة</td>
                                        <td>اجمالى التكلفة</td>
                                        <td>Control</td>
                                    </tr>
                                    <?php
                                    if (!empty($train_bookings)) {
                                        foreach ($train_bookings as $value) {
                                            $currency_code = getId('currency', 'ID', $value['id_currency_codes'] , 'currency_code');

                                            $price = $value['total_cost'];

                                            if ($value['id_currency_codes'] == 2 && $value['amountSold'] != 0) {
                                                $price = $value['amountSold'];
                                                $total_cost = $price * $value['number_individuals'];
                                            } elseif($value['id_currency_codes'] == 1) {
                                                $price = $value['cost_individual'] * $value['currencyExchangeRate'];
                                                $total_cost = $price * $value['number_individuals'];
                                                $currency_code = getName('currency', 'ID', 2 , 'currency_code');
                                                $price = ceil($price * 100) / 100;
                                                $total_cost = ceil($total_cost * 100) / 100;
                                            } else {
                                                // $price = $value['total_cost'];
                                                $currency_code = getId('currency', 'ID', 2 , 'currency_code');
                                                $currencyExchangeRateUSD = getId('currency', 'ID', 2,'currencyExchangeRate');
                                                $currencyExchangeRateEGP = 1 / $currencyExchangeRateUSD;
                                                $price = $value['cost_individual'] * $currencyExchangeRateEGP;
                                                $total_cost = $price * $value['number_individuals'];
                                                $price = ceil($price * 100) / 100;
                                                $total_cost = ceil($total_cost * 100) / 100;
                                            }
                                            echo <<<EOD
                                            <tr>
                                            <td>{$value['train_name']}</td>
                                            <td>{$value['departure_station']}</td>
                                            <td>{$value['arrival_station']}</td>
                                            <td>{$value['departure_date']} - {$value['departure_time']}</td>
                                            <td>{$value['arrival_date']} - {$value['arrival_time']}</td>
                                            <td>{$value['number_individuals']}</td>
                                            <td>{$currency_code} {$price}</td>
                                            <td>{$currency_code} {$total_cost}</td>
                                            <td>Control</td>
                                            </tr>
                                            EOD;
                                        }
                                    } else {
                                        echo "<tr>
                                            <td>لا يوجد</td>
                                            <td>لا يوجد</td>
                                            <td>لا يوجد</td>
                                            <td>لا يوجد</td>
                                            <td>لا يوجد</td>
                                            <td>لا يوجد</td>
                                            <td>لا يوجد</td>
                                            <td>Control</td>
                                            </tr>";
                                    }
                                    ?>
                                    <tr>
                                        <td>
                                            <input type="hidden" name="reservation_id" value="<?php echo $reservation_id; ?>">
                                            <input type="text" name="train_numper" class="form-control form-control-sm" placeholder="رقم القطار" required>
                                        </td>
                                        <td>
                                            <input type="text" name="departure_station" class="form-control form-control-sm" placeholder="محطة المغادرة" required>
                                        </td>
                                        <td>
                                            <input type="text" name="arrival_station" class="form-control form-control-sm" placeholder="محطة الوصول" required>
                                        </td>
                                        <td>
                                            <input type="date" name="departure_date" class="form-control form-control-sm" placeholder="تاريخ المغادرة" required>
                                            <input type="time" name="departure_time" class="form-control form-control-sm" placeholder="وقت المغادرة" required>
                                        </td>
                                        <td>
                                            <input type="date" name="arrival_date" class="form-control form-control-sm" placeholder="تاريخ الوصول" required>
                                            <input type="time" name="arrival_time" class="form-control form-control-sm" placeholder="وقت الوصول" required>
                                        </td>
                                        <td>
                                            <input type="text" name="number_individuals" class="form-control form-control-sm" placeholder="عدد التذاكر" required>
                                            <select name="id_currency_codes" class="form-select" required>
                                                    <?php
                                                    // Query to retrieve agents from the agents table
                                                    $personsQuery = "SELECT * FROM currency where ID = 2";
                                                    $personsResult = $con->query($personsQuery);
                                                    while ($persons = $personsResult->fetch(PDO::FETCH_ASSOC)) {
                                                        echo "<option value='{$persons['ID']}'>{$persons['currency_shortcut']}</option>";
                                                    }
                                                    $personsQuery = "SELECT * FROM currency where ID != 2";
                                                    $personsResult = $con->query($personsQuery);
                                                    while ($persons = $personsResult->fetch(PDO::FETCH_ASSOC)) {
                                                        echo "<option value='{$persons['ID']}'>{$persons['currency_shortcut']}</option>";
                                                    }
                                                    ?>
                                            </select>
                                            <!-- <input type="text" name="currencyExchangeRate" class="form-control form-control-sm" placeholder="سعر الصرف" > -->
                                        </td>
                                        <td>
                                            <input type="text" name="price" class="form-control form-control-sm" placeholder="تكلفة التذكرة" required>
                                        </td>
                                        <td>
                                            <!-- <input type="text" name="price_sale" class="form-control form-control-sm" placeholder="سعر بيع التذكرة" required> -->
                                        </td>
                                        <td>
                                            <button type="submit" class="btn btn-primary" name="train_booking">حفظ</button>
                                            
                                        </td>
                                    </tr>
                                </table>
                            </form>
                        </div>
                        <?php
                        }
                        ?>
                        <div class="col-md-12 mb-3">
                            <h1 class="input-group-text text-center"><i class="fa-solid fa-circle-plus"></i>&nbsp; حجوزات ومصاريف أخرى </h1>
                            
                                <table class='main-table text-center table table-bordered'>
                                    <tr>
                                        <td>التاريخ</td>
                                        <td>البند</td>
                                        <td>الاسم</td>
                                        <td>العدد</td>
                                        <td>تكلفة الفرد</td>
                                        <td>إجمالى التكلفة</td>
                                        <td>Control</td>
                                    </tr>
                                    <?php
                                    if (!empty($booking_file)) {
                                        foreach ($booking_file as $value) {

                                            $currency_code = getId('currency', 'ID', $value['id_currency_codes'] , 'currency_code');

                                            $price = $value['total_cost'];

                                            if ($value['id_currency_codes'] == 2 && $value['amountSold'] != 0) {
                                                $price = $value['amountSold'];
                                                $total_cost = $price * $value['number_individuals'] ;
                                            } elseif($value['id_currency_codes'] == 1) {
                                                $price = $value['cost_individual'] * $value['currencyExchangeRate'];
                                                $total_cost = $price * $value['number_individuals'];
                                                $currency_code = getName('currency', 'ID', 2 , 'currency_code');
                                                $price = ceil($price * 100) / 100;
                                                $total_cost = ceil($total_cost * 100) / 100;
                                            } else {
                                                // $price = $value['total_cost'];
                                                $currency_code = getId('currency', 'ID', 2 , 'currency_code');
                                                $currencyExchangeRateUSD = getId('currency', 'ID', 2,'currencyExchangeRate');
                                                $currencyExchangeRateEGP = 1 / $currencyExchangeRateUSD;
                                                $price = $value['cost_individual'] * $currencyExchangeRateEGP;
                                                $total_cost = $price * $value['number_individuals'];
                                                $price = ceil($price * 100) / 100;
                                                $total_cost = ceil($total_cost * 100) / 100;
                                            }
                                            if (!empty($value['id_invoicing_type_exp'])) {
                                                $name_invoicing_type = getId('invoicing_type_exp', 'ID', $value['id_invoicing_type_exp'], 'name');
                                                if(empty($name_invoicing_type)){
                                                    $name_invoicing_type = getName('invoicing_line_type', 'ID', $value['id_line_type'], 'name');
                                                    if(empty($name_invoicing_type)) {
                                                        $name_invoicing_type = 'أخرى';
                                                    }
                                                }
                                            } elseif (!empty($value['id_line_type'])){
                                                $name_invoicing_type = getName('invoicing_line_type', 'ID', $value['id_line_type'], 'name');
                                            } else {
                                                $name_invoicing_type = 'أخرى';
                                            }
                                            echo "<tr>
                                            <td>{$value['mydate']}</td>
                                            <td>{$name_invoicing_type}</td>
                                            <td>{$value['name_type']}</td>
                                            <td>{$value['number_individuals']}</td>
                                            <td>{$currency_code} {$price}</td>
                                            <td>{$currency_code} {$total_cost}</td>
                                            <td>Control</td>
                                            </tr>";
                                        }
                                    } else {
                                        echo "<tr>
                                            <td>لا يوجد</td>
                                            <td>لا يوجد</td>
                                            <td>لا يوجد</td>
                                            <td>لا يوجد</td>
                                            <td>لا يوجد</td>
                                            <td>لا يوجد</td>
                                            <td>Control</td>
                                            </tr>";
                                    }
                                    ?>
                                    <tr>
                                        <td>
                                        <form action="?do=insert_in_file" method="post">
                                            <input type="hidden" name="reservation_id" value="<?php echo $reservation_id; ?>">
                                            <input type="date" name="mydate" class="form-control form-control-sm" placeholder="التاريخ " required>
                                        </td>
                                        <td>
                                            <select name="id_invoicing_type_exp" id="id_invoicing_type_exp" class="form-select form-control-sm" required>
                                                <?php
                                                // Query to retrieve agents from the agents table
                                                $agentsQuery = "SELECT * FROM invoicing_type_exp";
                                                $agentsResult = $con->query($agentsQuery);
                                                echo "<option value=''>اختر البند</option>";
                                                while ($agent = $agentsResult->fetch(PDO::FETCH_ASSOC)) {
                                                        echo "<option value='{$agent['ID']}'>{$agent['name']}</option>";
                                                }
                                                ?>
                                            </select>
                                        </td>
                                        <td>
                                            <input type="text" name="name_type" class="form-control form-control-sm" placeholder="الإسم" required>
                                        </td>
                                        <td>
                                            <input type="text" name="number_individuals" class="form-control form-control-sm" placeholder="عدد الافراد" required>
                                            <select name="id_currency_codes" class="form-select" required>
                                                    <?php
                                                    // Query to retrieve agents from the agents table
                                                    $personsQuery = "SELECT * FROM currency where ID = 2";
                                                    $personsResult = $con->query($personsQuery);
                                                    while ($persons = $personsResult->fetch(PDO::FETCH_ASSOC)) {
                                                        echo "<option value='{$persons['ID']}'>{$persons['currency_shortcut']}</option>";
                                                    }
                                                    $personsQuery = "SELECT * FROM currency where ID != 2";
                                                    $personsResult = $con->query($personsQuery);
                                                    while ($persons = $personsResult->fetch(PDO::FETCH_ASSOC)) {
                                                        echo "<option value='{$persons['ID']}'>{$persons['currency_shortcut']}</option>";
                                                    }
                                                    ?>
                                            </select>
                                            <!-- <input type="text" name="currencyExchangeRate" class="form-control form-control-sm" placeholder="سعر الصرف" > -->
                                        </td>
                                        <td>
                                            <input type="text" name="price" class="form-control form-control-sm" placeholder="تكلفة للفرد" required>
                                        </td>
                                        <td>
                                        <!-- <select name="payment" class="form-select" required>
                                                <?php
                                                // Query to retrieve agents from the agents table
                                                echo "<option value=''>طريقة الدفع</option>";
                                                $personsQuery = "SELECT * FROM level_acc where ID = 12 OR ID = 13";
                                                $personsResult = $con->query($personsQuery);
                                                while ($persons = $personsResult->fetch(PDO::FETCH_ASSOC)) {
                                                    $indentation = str_repeat("&nbsp;&nbsp;&nbsp;&nbsp;", 2 - 1);
                                                    $subAccounts = getSubAccounts($persons['ID'] ,$persons['lev_acc'] + 1);
                                                    $hasSubAccounts = !empty($subAccounts);
                                                    $displayedAccounts = [];
                                                    // لا تطبع <option> إذا كان لديها حسابات فرعية
                                                    if (!in_array($persons['ID'], $displayedAccounts) && !$hasSubAccounts) {
                                                        echo "<option value='{$persons['ID']}'>{$indentation}{$persons['name_account']}</option>";
                                                        $displayedAccounts[] = $persons['ID']; // إضافة الحساب الحالي للمصفوفة
                                                    }
                                                    if ($hasSubAccounts) {
                                                        echo "<optgroup label='{$persons['name_account']}'>";
                                                        printAccountOptions($subAccounts, $persons['lev_acc'] + 1, $displayedAccounts);
                                                        echo "</optgroup>";
                                                    }
                                                }
                                                ?>
                                        </select> -->
                                        </td>
                                        <td>
                                            <button type="submit" class="btn btn-primary" name="booking_exp">حفظ</button>
                                            </form>
                                        </td>
                                    </tr>
                                </table>
                            
                        </div>
                    </div>
                    <?php
                } else {
                    // رسالة خطأ أو إعادة توجيه إلى صفحة خطأ
                    echo "خطأ: لا يوجد حجز بهذا الرقم.";
                    exit;
                }
            } else {
                // رسالة خطأ أو إعادة توجيه إلى صفحة خطأ
                echo "خطأ: يجب تحديد رقم الحجز.";
                exit;
            }
        } else {
            if(!isset($theMsg)){
                $theMsg = '<div class="alert alert-danger">ليس لديك صلاحية الدخول الى هذا القسم</div>';
            }
            redirectHome($theMsg);
        }
    } elseif ($do === 'insert_in_file') {
        // معالجة إضافة الحجز الجديد
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            if (isset($_POST['add_numper'])) {
                $id_number_individuals = $_POST['id_number_individuals'] ?? null; // معرّف الحجز للتحقق مما إذا كان التعديل مطلوبًا

                $FileManager = new FileManager($con);
                // استلام البيانات من الفورم
                $reservation_id = $_POST['reservation_id'];
                $id_persons = $_POST['id_persons'];
                $numper = $_POST['numper'];
                $age_person = $_POST['age_person'];
                // يمكنك إجراء عمليات التحقق هنا
                $formErrors = array();
                if (empty($reservation_id)) {
                    $formErrors[] = 'لا يوجد <strong>رقم ملف</strong>';
                }
                if (empty($id_persons)) {
                    $formErrors[] = 'برجاء إختر <strong>الشخص</strong>';
                }
                if (empty($numper)) {
                    $formErrors[] = 'لا يجب أن يكون عدد الأفراد <strong>فارغ</strong>';
                }
                // Loop Into Errors Array And Echo It
                foreach ($formErrors as $error) {
                    echo '<div class="alert alert-danger">' . $error . '</div>';
                }
                if (empty($formErrors)) {
                    try {
                        if (empty($id_number_individuals)) {
                            $result = $FileManager->addNewNumberIndividuals($reservation_id, $id_persons, $numper, $age_person);
                            if ($result) {
                                $theMsg = "تمت إضافة الأشخاص بنجاح!";
                                redirectlink($theMsg, $url = "reservations?do=all_data_file&id=" . $reservation_id, $name = "عرض الملف", $seconds = 0);
                            } else {
                                echo "حدث خطأ أثناء الإضافة.";
                            }
                        } else {
                            $result = $FileManager->updateNumberIndividuals($id_number_individuals, $reservation_id, $id_persons, $numper, $age_person);
                            if ($result) {
                                $theMsg = "تمت تعديل الأشخاص بنجاح!";
                                redirectlink($theMsg, $url = "reservations?do=all_data_file&id=" . $reservation_id, $name = "عرض الملف", $seconds = 0);
                            } else {
                                echo "حدث خطأ أثناء التعديل.";
                            }
                        }
                    } catch (PDOException $e) {
                        echo "حدث خطأ أثناء التعديل: " . $e->getMessage();
                    }
                }
            } elseif (isset($_POST['add_employeesM'])) {
                $id_employee_booking = $_POST['id_employee_booking'] ?? null; // معرّف الحجز للتحقق مما إذا كان التعديل مطلوبًا
                $reservationsManager = new ReservationsManager($con);
                $FileManager = new FileManager($con);
                $reservation_id = $_POST['reservation_id'];
                $id_employees = $_POST['id_employees'];
                $id_currency_codes = $_POST['id_currency_codes'];
                $cost = $_POST['cost'];
                $formErrors = array();
                if (empty($reservation_id)) {
                    $formErrors[] = 'لا يوجد <strong>رقم ملف</strong>';
                }
                if (empty($id_employees)) {
                    $formErrors[] = 'برجاء إختر <strong>المندوب</strong>';
                }
                if (empty($id_currency_codes)) {
                    $formErrors[] = 'برجاء حدد <strong>العملة</strong>';
                }
                foreach ($formErrors as $error) {
                    echo '<div class="alert alert-danger">' . $error . '</div>';
                }
                if (empty($formErrors)) {
                    try {
                        if (empty($id_employee_booking)) {
                            $NumberIndividuals = $reservationsManager->getNumberIndividualsReservationById($reservation_id);
                            $all_Individuals = 0;
                            if (!empty($NumberIndividuals)) {
                                foreach ($NumberIndividuals as $value) {
                                    $all_Individuals += $value['number'];
                                }
                            } else {
                                $all_Individuals = 0;
                            }
                            // $id_invoice = getId('invoicing','id_reservation',$reservation_id,'ID');
                            
                            // $id_invoicing_line = getIdTowVal('invoicing_line','id_type', 4,'id_line_booking',$employee_booking_id,'ID');
                            $currencyExchangeRate = getId('currency','ID',$id_currency_codes,'currencyExchangeRate');
                            $currencyExchangeRateUSD = getId('currency','ID', 2,'currencyExchangeRate');
                            if ($currencyExchangeRateUSD > 0) {
                                $currencyExchangeRateEGP = 1 / $currencyExchangeRateUSD;
                            }
                            if ($id_currency_codes != 1) {
                                $amountSold = $cost;
                                if ($currencyExchangeRate > 0) {
                                    $cost = $cost * $currencyExchangeRate;
                                }
                                $total_cost = $cost;
                            } else {
                                // سوف يتم اضافة سعر صرف الدولار للجنيه المصري
                                $currencyExchangeRate = $currencyExchangeRateEGP;
                                $amountSold = NULL;
                                $total_cost = $cost;
                            }
                            $mydate = date('Y-m-d');
                            $employee_booking_id = $FileManager->addNewempM($reservation_id, $id_employees, 1);
                            $id_booking_file = $FileManager->addBookingFile(
                                $reservation_id,
                                4,
                                $employee_booking_id,
                                '',
                                'مندوب مرافق للمجموعة',
                                $mydate,
                                1,
                                $id_currency_codes,
                                $amountSold,
                                '',
                                $currencyExchangeRate,
                                $cost,
                                '',
                                $total_cost,
                                '',
                                $sessionUser
                            );
                            // $addInvoicingLine = $reservationsManager->addInvoicingLine($employee_booking_id, $id_invoice, $cost, $sessionUser, $all_Individuals, 4, 'مندوب مرافق للمجموعة');
                            if ($employee_booking_id) {
                                $theMsg = "تمت إضافة المندوب بنجاح!";
                                redirectlink($theMsg, $url = "reservations?do=all_data_file&id=" . $reservation_id, $name = "عرض الملف", $seconds = 0);
                            } else {
                                echo "حدث خطأ أثناء الإضافة.";
                            }
                        } else {
                        $NumberIndividuals = $reservationsManager->getNumberIndividualsReservationById($reservation_id);

                        $all_Individuals = 0;
                        if (!empty($NumberIndividuals)) {
                            foreach ($NumberIndividuals as $value) {
                                $all_Individuals += $value['number'];
                            }
                        } else {
                            $all_Individuals = 0;
                        }
                        // $id_invoice = getId('invoicing','id_reservation',$reservation_id,'ID');
                        
                        // $id_invoicing_line = getIdTowVal('invoicing_line','id_type', 4,'id_line_booking',$employee_booking_id,'ID');
                        $currencyExchangeRate = getId('currency','ID',$id_currency_codes,'currencyExchangeRate');
                        $currencyExchangeRateUSD = getId('currency','ID', 2,'currencyExchangeRate');
                        if ($currencyExchangeRateUSD > 0) {
                            $currencyExchangeRateEGP = 1 / $currencyExchangeRateUSD;
                        }
                        if ($id_currency_codes != 1) {
                            $amountSold = $cost;
                            if ($currencyExchangeRate > 0) {
                                $cost = $cost * $currencyExchangeRate;
                            }
                            $total_cost = $cost;
                        } else {
                            // سوف يتم اضافة سعر صرف الدولار للجنيه المصري
                            $currencyExchangeRate = $currencyExchangeRateEGP;
                            $amountSold = NULL;
                            $total_cost = $cost;
                        }
                        $mydate = date('Y-m-d');
                        $employee_booking_id = $FileManager->updateEmpM($id_employee_booking, $reservation_id, $id_employees, 1);
                        $id_booking_file = $FileManager->updateBookingFile(
                            $reservation_id,
                            4,
                            $id_employee_booking,
                            '',
                            'مندوب مرافق للمجموعة',
                            $mydate,
                            1,
                            $id_currency_codes,
                            $amountSold,
                            '',
                            $currencyExchangeRate,
                            $cost,
                            '',
                            $total_cost,
                            '',
                            $sessionUser
                        );
                        // $addInvoicingLine = $reservationsManager->addInvoicingLine($employee_booking_id, $id_invoice, $cost, $sessionUser, $all_Individuals, 4, 'مندوب مرافق للمجموعة');
                        if ($employee_booking_id) {
                            $theMsg = "تمت تعديل المندوب بنجاح!";
                            redirectlink($theMsg, $url = "reservations?do=all_data_file&id=" . $reservation_id, $name = "عرض الملف", $seconds = 0);
                        } else {
                            echo "حدث خطأ أثناء التعديل.";
                        }
                    }
                    } catch (PDOException $e) {
                        echo "حدث خطأ أثناء تعديل المندوب: " . $e->getMessage();
                    }
                }
            } elseif (isset($_POST['add_employeesSH'])) {
                $id_employee_booking = $_POST['id_employee_booking'] ?? null; // معرّف الحجز للتحقق مما إذا كان التعديل مطلوبًا
                $reservationsManager = new ReservationsManager($con);
                $FileManager = new FileManager($con);

                $reservation_id = $_POST['reservation_id'];
                $id_employees = $_POST['id_employees'];
                $id_currency_codes = $_POST['id_currency_codes'];
                $cost = $_POST['cost'];
                $formErrors = array();
                if (empty($reservation_id)) {
                    $formErrors[] = 'لا يوجد <strong>رقم ملف</strong>';
                }
                if (empty($id_employees)) {
                    $formErrors[] = 'برجاء إختر <strong>المرشد السياحى</strong>';
                }
                if (empty($id_currency_codes)) {
                    $formErrors[] = 'برجاء حدد <strong>العملة</strong>';
                }
                foreach ($formErrors as $error) {
                    echo '<div class="alert alert-danger">' . $error . '</div>';
                }
                if (empty($formErrors)) {
                    try {
                        if (empty($id_employee_booking)) {
                        $NumberIndividuals = $reservationsManager->getNumberIndividualsReservationById($reservation_id);

                        $all_Individuals = 0;
                        if (!empty($NumberIndividuals)) {
                            foreach ($NumberIndividuals as $value) {
                                $all_Individuals += $value['number'];
                            }
                        } else {
                            $all_Individuals = 0;
                        }
                        // $id_invoice = getId('invoicing','id_reservation',$reservation_id,'ID');
                        // $id_invoicing_line = getIdTowVal('invoicing_line','id_type', 4,'id_line_booking',$employee_booking_id,'ID');

                        $currencyExchangeRate = getId('currency','ID',$id_currency_codes,'currencyExchangeRate');
                        $currencyExchangeRateUSD = getId('currency','ID', 2,'currencyExchangeRate');
                        if ($currencyExchangeRateUSD > 0) {
                            $currencyExchangeRateEGP = 1 / $currencyExchangeRateUSD;
                        }
                        if ($id_currency_codes != 1) {
                            $amountSold = $cost;
                            if ($currencyExchangeRate > 0) {
                                $cost = $cost * $currencyExchangeRate;
                            }
                            $total_cost = $cost;
                        } else {
                            // سوف يتم اضافة سعر صرف الدولار للجنيه المصري
                            $currencyExchangeRate = $currencyExchangeRateEGP;
                            $amountSold = NULL;
                            $total_cost = $cost;
                        }
                        $mydate = date('Y-m-d');
                        $employee_booking_id = $FileManager->addNewempM($reservation_id, $id_employees, 2);
                        $id_booking_file = $FileManager->addBookingFile(
                            $reservation_id,
                            3,
                            $employee_booking_id,
                            '',
                            'مرشد مرافق للمجموعة',
                            $mydate,
                            1,
                            $id_currency_codes,
                            $amountSold,
                            '',
                            $currencyExchangeRate,
                            $cost,
                            '',
                            $total_cost,
                            '',
                            $sessionUser
                        );
                        // $addInvoicingLine = $reservationsManager->addInvoicingLine($employee_booking_id, $id_invoice, $cost, $sessionUser, $all_Individuals, 3, 'مرشد سياحى مرافق للمجموعة');

                        // $result = $FileManager->addNewempM($reservation_id, $id_employees, 2);
                        if ($id_booking_file) {
                            $theMsg = "تمت إضافة المرشد السياحى بنجاح!";
                            redirectlink($theMsg, $url = "reservations?do=all_data_file&id=" . $reservation_id, $name = "عرض الملف", $seconds = 0);
                        } else {
                            echo "حدث خطأ أثناء الإضافة.";
                        }
                    } else {
                        $NumberIndividuals = $reservationsManager->getNumberIndividualsReservationById($reservation_id);

                        $all_Individuals = 0;
                        if (!empty($NumberIndividuals)) {
                            foreach ($NumberIndividuals as $value) {
                                $all_Individuals += $value['number'];
                            }
                        } else {
                            $all_Individuals = 0;
                        }
                        // $id_invoice = getId('invoicing','id_reservation',$reservation_id,'ID');
                        
                        // $id_invoicing_line = getIdTowVal('invoicing_line','id_type', 4,'id_line_booking',$employee_booking_id,'ID');
                        $currencyExchangeRate = getId('currency','ID',$id_currency_codes,'currencyExchangeRate');
                        $currencyExchangeRateUSD = getId('currency','ID', 2,'currencyExchangeRate');
                        if ($currencyExchangeRateUSD > 0) {
                            $currencyExchangeRateEGP = 1 / $currencyExchangeRateUSD;
                        }
                        if ($id_currency_codes != 1) {
                            $amountSold = $cost;
                            if ($currencyExchangeRate > 0) {
                                $cost = $cost * $currencyExchangeRate;
                            }
                            $total_cost = $cost;
                        } else {
                            // سوف يتم اضافة سعر صرف الدولار للجنيه المصري
                            $currencyExchangeRate = $currencyExchangeRateEGP;
                            $amountSold = NULL;
                            $total_cost = $cost;
                        }
                        $mydate = date('Y-m-d');
                        $employee_booking_id = $FileManager->updateEmpM($id_employee_booking, $reservation_id, $id_employees, 2);
                        $id_booking_file = $FileManager->updateBookingFile(
                            $reservation_id,
                            3,
                            $id_employee_booking,
                            '',
                            'مرشد مرافق للمجموعة',
                            $mydate,
                            1,
                            $id_currency_codes,
                            $amountSold,
                            '',
                            $currencyExchangeRate,
                            $cost,
                            '',
                            $total_cost,
                            '',
                            $sessionUser
                        );
                        // $addInvoicingLine = $reservationsManager->addInvoicingLine($employee_booking_id, $id_invoice, $cost, $sessionUser, $all_Individuals, 4, 'مندوب مرافق للمجموعة');
                        if ($employee_booking_id) {
                            $theMsg = "تمت تعديل المندوب بنجاح!";
                            redirectlink($theMsg, $url = "reservations?do=all_data_file&id=" . $reservation_id, $name = "عرض الملف", $seconds = 0);
                        } else {
                            echo "حدث خطأ أثناء التعديل.";
                        }
                    }
                    } catch (PDOException $e) {
                        echo "حدث خطأ أثناء إضافة المرشد: " . $e->getMessage();
                    }
                }
            } elseif (isset($_POST['hotel_booking'])) {
                $id_hotel_bookings = $_POST['id_hotel_bookings'] ?? null; // معرّف الحجز للتحقق مما إذا كان التعديل مطلوبًا

                $FileManager = new FileManager($con);
                // استلام البيانات من الفورم
                $reservation_id = $_POST['reservation_id'];
                $id_hotels = $_POST['id_hotels'];
                $id_room_type = $_POST['id_room_type'];
                $id_meal_system = $_POST['id_meal_system'];
                $rooms_numper = $_POST['rooms_numper'];
                $disc = $_POST['disc'];
                $check_in_date = $_POST['check_in_date'];
                $check_out_date = $_POST['check_out_date'];
                $id_currency_codes = $_POST['id_currency_codes'];
                // $currencyExchangeRate = $_POST['currencyExchangeRate'];
                $children_number = $_POST['children_number'];
                $invaled_number = $_POST['invaled_number'];
                $cost_children = $_POST['cost_children'];
                $TAX = $_POST['TAX'];
                $payment_date = $_POST['payment_date'];
                $payment_cash = $_POST['payment_cash'];
                $price = $_POST['price'];
                // $price_sale = $_POST['price_sale'];
                $note = $_POST['note'];
                // يمكنك إجراء عمليات التحقق هنا
                $formErrors = array();
                if (empty($reservation_id)) {
                    $formErrors[] = 'لا يوجد <strong>رقم ملف</strong>';
                }
                if (empty($id_hotels)) {
                    $formErrors[] = 'برجاء إختر <strong>الفندق</strong>';
                }
                if (empty($id_room_type)) {
                    $formErrors[] = 'برجاء تحديد نوع<strong>الغرفة</strong>';
                }
                if (empty($rooms_numper)) {
                    $formErrors[] = 'لا يجب أن يكون عدد الغرف <strong>فارغ</strong>';
                }
                if (empty($invaled_number)) {
                    $formErrors[] = 'لا يجب أن يكون عدد الأفراد <strong>فارغ</strong>';
                }
                if (empty($price)) {
                    $formErrors[] = 'لا يجب أن يكون سعر الغرفة <strong>فارغ</strong>';
                }
                // Loop Into Errors Array And Echo It
                foreach ($formErrors as $error) {
                    echo '<div class="alert alert-danger">' . $error . '</div>';
                }
                if (empty($formErrors)) {
                    try {
                        if (empty($id_hotel_bookings)) {
                            $reservationsManager = new ReservationsManager($con);
                            $payment_percentage = getId('hotel_conditions', 'id_hotels', $id_hotels, 'payment_percentage');
                            $discount_from = 0;
                            // $discount_from = getId('hotel_discount_booking', 'id_hotel', $id_hotels, 'discount_from');
                            // $discount_free = getId('hotel_discount_booking', 'id_hotel', $id_hotels, 'discount_free');
                            $calculatedates = $reservationsManager->calculateNightAndDayCount($check_in_date, $check_out_date);
                            $code_1 = getId('room_type', 'ID', $id_room_type, 'code_1');
                            $code_2 = getId('room_type', 'ID', $id_room_type, 'code_2');
                            // $all_Individuals = 0;
                            
                            /*if ($code_2 == "X" || $code_1 == "SGL") {
                                $all_Individuals = $rooms_numper;
                            } elseif ($code_2 == "XX" || $code_1 == "DBL") {
                                $all_Individuals = $rooms_numper * 2;
                            } elseif ($code_2 == "XXX" || $code_1 == "TPL") {
                                $all_Individuals = $rooms_numper * 3;
                            } else {
                                $all_Individuals = $rooms_numper ;
                            } */
                            $all_Individuals = $invaled_number;
                            if ($discount_from != 0) {
                                $free_invaled = calculatePayment($all_Individuals, $discount_from);
                                $discount_free = 0;
                            } else {
                                $discount_free = 0;
                                $free_invaled = 0;
                            }
                            /* if ($free_invaled > 0) {
                                $discount_free = ($price * $free_invaled) * $calculatedates['number_of_nights'];
                            } */
                            $currencyExchangeRate = getId('currency','ID',$id_currency_codes,'currencyExchangeRate');
                            $currencyExchangeRateUSD = getId('currency','ID', 2,'currencyExchangeRate');
                            if ($currencyExchangeRateUSD > 0) {
                                $currencyExchangeRateEGP = 1 / $currencyExchangeRateUSD;
                            }

                            if ($id_currency_codes != 1) {
                                $amountSold = $price;
                                $price = $price * $currencyExchangeRate;
                            } else {
                                $currencyExchangeRate = $currencyExchangeRateEGP;
                                $amountSold = NULL;
                            }

                            $RoomPrice_id = $FileManager->addRoomPrice($id_hotels, $id_room_type, $id_meal_system, $id_currency_codes, $amountSold, '', $currencyExchangeRate, $disc, $price, '');

                            $id_hotel_bookings = $FileManager->addHotelBooking($reservation_id, $id_hotels, $RoomPrice_id, $rooms_numper, $check_in_date, $check_out_date, 'on', $note, $TAX, $invaled_number, $children_number, $cost_children, $free_invaled, $discount_free, $sessionUser);
                            
                            $hotel_bookings = $reservationsManager->getHotelBookingsById($id_hotel_bookings);

                            foreach ($hotel_bookings as $value) {

                                $id_hotel_bookings =  $value['id_hotel_bookings'];
                                $price = $value['price'];
                                $price_sale = $value['price_sale'];
                                $id_currency_codes = $value['id_currency_codes'];
                                $amountSold = $value['amountSold'];
                                $amountSold_sale = $value['amountSold_sale'];
                                $currencyExchangeRate = $value['currencyExchangeRate'];
                                $children_number = $value['children_number'];
                                $cost_children = $value['cost_children'];
                                $invaled_number = $value['invaled_number'];
                                $discount_free = $value['discount_free'];

                                $calculatedates = $reservationsManager->calculateNightAndDayCount($value['check_in_date'], $value['check_out_date']);

                                if (!empty($amountSold) && $amountSold > 0) {
                                    $price = $amountSold;
                                }

                                /* $all_Individuals = 0;
                                $number_room = 1;
                                if ($value['code_2'] == "X" || $value['code_1'] == "SGL") {
                                    $number_room = 1;
                                } elseif ($value['code_2'] == "XX" || $value['code_1'] == "DBL") {
                                    $price *= 2;
                                    $number_room = 2;
                                } elseif ($value['code_2'] == "XXX" || $value['code_1'] == "TPL") {
                                    $price *= 3;
                                    $number_room = 3;
                                } else {
                                    $number_room = 1;
                                } */

                                // $price = $value['rooms_number'] * $price;
                                $price = $invaled_number * $price;
                                $price *= $calculatedates['number_of_nights'];
                                // $all_Individuals = $value['rooms_number'] * $number_room;
                                $all_Individuals = $invaled_number;
                                
                                if ($discount_free > 0) {
                                    $price = $price - $discount_free;
                                }
                                
                                if ($cost_children > 0 && $children_number > 0) {
                                    $all_cost_children = ($cost_children * $children_number) * $calculatedates['number_of_nights'];
                                    $price += $all_cost_children;
                                }
                                
                                
                                $id_tourism_management = getId('reservations', 'id', $value['id_reservation'], 'id_tourism_management');
                                $id_agent = getId('reservations', 'id', $value['id_reservation'], 'agent_id');

                                $id_cost_center_hotel = $value['id_cost_center'];

                                $mydate = date('Y-m-d');

                                $NumberIndividuals = $reservationsManager->getNumberIndividualsReservationById($reservation_id);
                                
                                $payan = "حجز عدد " . $value['rooms_number'] . " غرفة " . $value['code_1'];
                                
                                $cost = $price / $value['rooms_number'];
                                $total_cost = $price;
                                if ($payment_percentage > 0 || !empty($payment_cash)) {
                                    $cash_befor = $total_cost ;
                                    $cash_tax = 0 ;
                                    if ($TAX == 1) {
                                        $cash_tax = (($cash_befor / 1.14) * 0.03);
                                    }

                                    if(isset($payment_cash) && !empty($payment_cash)){
                                        $cash_payment = $payment_cash;
                                    } else {
                                        $cash_after = $cash_befor -  $cash_tax;
                                        $cash_payment = ($cash_after * $payment_percentage) / 100;
                                    }

                                    $hotel_conditions = "INSERT INTO hotel_booking_pay_arr (id_type, id_reservation, id_hotel_booking, date_go, cash) 
                                                                        VALUES (1, :id_reservation, :id_hotel_booking, :date_go, :cash)";
                                    $hotel_conditionsStmt = $con->prepare($hotel_conditions);
                                    $hotel_conditionsStmt->bindParam(':id_reservation', $reservation_id);
                                    $hotel_conditionsStmt->bindParam(':id_hotel_booking', $id_hotel_bookings);
                                    $hotel_conditionsStmt->bindParam(':date_go', $payment_date);
                                    $hotel_conditionsStmt->bindParam(':cash', $cash_payment);
                                    $stmtret = $hotel_conditionsStmt->execute();
                                }

                                if ($id_currency_codes != 1) {
                                    $amountSold = $cost;
                                    $cost = $cost * $currencyExchangeRate;
                                    $total_cost = $price * $currencyExchangeRate;
                                } else {
                                    $currencyExchangeRate = $currencyExchangeRateEGP;
                                    $amountSold = NULL;
                                }
                                $id_booking_file = $FileManager->addBookingFile(
                                    $reservation_id,
                                    1,
                                    $id_hotel_bookings,
                                    '',
                                    $payan,
                                    $mydate,
                                    $value['rooms_number'],
                                    $id_currency_codes,
                                    $amountSold,
                                    '',
                                    $currencyExchangeRate,
                                    $cost,
                                    '',
                                    $total_cost,
                                    '',
                                    $sessionUser
                                );
                            }
                            $hotel_name = getId('hotels','ID', $id_hotels,'hotel_name');
                            $name= 'طلب دفع لفندق';
                            $disc_notifications = "مطلوب الدفع لفندق " . $hotel_name ;
                            $date_notifications = "";
                            // addnotifications($name, $disc_notifications, $date_notifications);
                            if ($id_booking_file) {
                                $theMsg = "تمت إضافة الحجز بنجاح!";
                                redirectlink($theMsg, $url = "reservations?do=all_data_file&id=" . $reservation_id, $name = "عرض الملف", $seconds = 0);
                            } else {
                                echo "حدث خطأ أثناء الإضافة.";
                            }
                        } else {
                            $discount_free = 0;
                            $reservationsManager = new ReservationsManager($con);
                            $payment_percentage = getId('hotel_conditions', 'id_hotels', $id_hotels, 'payment_percentage');
                            $discount_from = getId('hotel_discount_booking', 'id_hotel', $id_hotels, 'discount_from');
                            // $discount_free = getId('hotel_discount_booking', 'id_hotel', $id_hotels, 'discount_free');
                            $calculatedates = $reservationsManager->calculateNightAndDayCount($check_in_date, $check_out_date);

                            $code_1 = getId('room_type', 'ID', $id_room_type, 'code_1');
                            $code_2 = getId('room_type', 'ID', $id_room_type, 'code_2');
                            $all_Individuals = $invaled_number;

                            /* if ($code_2 == "X" || $code_1 == "SGL") {
                                $all_Individuals = $rooms_numper;
                            } elseif ($code_2 == "XX" || $code_1 == "DBL") {
                                $all_Individuals = $rooms_numper * 2;
                            } elseif ($code_2 == "XXX" || $code_1 == "TPL") {
                                $all_Individuals = $rooms_numper * 3;
                            } else {
                                $all_Individuals = $rooms_numper;
                            } */
                            if ($discount_from != 0) {
                                $free_invaled = calculatePayment($all_Individuals, $discount_from);
                            } else {
                                $discount_free = 0;
                                $free_invaled = 0;
                            }
                            /* if ($free_invaled > 0) {
                                $discount_free = ($price * $free_invaled) * $calculatedates['number_of_nights'];
                            } */
                            $currencyExchangeRate = getId('currency','ID',$id_currency_codes,'currencyExchangeRate');
                            $currencyExchangeRateUSD = getId('currency','ID', 2,'currencyExchangeRate');
                            if ($currencyExchangeRateUSD > 0) {
                                $currencyExchangeRateEGP = 1 / $currencyExchangeRateUSD;
                            }

                            if ($id_currency_codes != 1) {
                                $amountSold = $price;
                                $price = $price * $currencyExchangeRate;
                            } else {
                                $currencyExchangeRate = $currencyExchangeRateEGP;
                                $amountSold = NULL;
                            }
                            
                            $id_room_prices = getId('hotel_bookings','ID', $id_hotel_bookings,'id_room_prices');
                            $update_RoomPrice_id = $FileManager->updateRoomPrice($id_room_prices, $id_hotels, $id_room_type, $id_meal_system, $id_currency_codes, $amountSold, '', $currencyExchangeRate, $disc, $price, '');
                            $update_hotel_bookings = $FileManager->updateHotelBooking($id_hotel_bookings, $reservation_id, $id_hotels, $id_room_prices, $rooms_numper, $check_in_date, $check_out_date, 'on', $note, $TAX, $invaled_number, $children_number, $cost_children, $free_invaled, $discount_free, $sessionUser);
                            
                            $hotel_bookings = $reservationsManager->getHotelBookingsById($id_hotel_bookings);
                            
                            foreach ($hotel_bookings as $value) {
                                
                                // $id_room_prices =  $value['id_room_prices'];
                                
                                $id_hotel_bookings =  $value['id_hotel_bookings'];
                                $price = $value['price'];
                                $price_sale = $value['price_sale'];
                                $id_currency_codes = $value['id_currency_codes'];
                                $amountSold = $value['amountSold'];
                                $amountSold_sale = $value['amountSold_sale'];
                                $currencyExchangeRate = $value['currencyExchangeRate'];
                                $invaled_number = $value['invaled_number'];
                                $children_number = $value['children_number'];
                                $cost_children = $value['cost_children'];
                                $discount_free = $value['discount_free'];

                                $calculatedates = $reservationsManager->calculateNightAndDayCount($value['check_in_date'], $value['check_out_date']);

                                if (!empty($amountSold) && $amountSold > 0) {
                                    $price = $amountSold;
                                }

                                /* $all_Individuals = 0;
                                $number_room = 1;
                                if ($value['code_2'] == "X" || $value['code_1'] == "SGL") {
                                    $number_room = 1;
                                } elseif ($value['code_2'] == "XX" || $value['code_1'] == "DBL") {
                                    $price *= 2;
                                    $number_room = 2;
                                } elseif ($value['code_2'] == "XXX" || $value['code_1'] == "TPL") {
                                    $price *= 3;
                                    $number_room = 3;
                                } else {
                                    $number_room = 1;
                                } */

                                $price = $invaled_number * $price;
                                $price *= $calculatedates['number_of_nights'];
                                $all_Individuals = $invaled_number;
                                
                                if ($discount_free > 0) {
                                    $price = $price - $discount_free;
                                }
                                
                                if ($cost_children > 0 && $children_number > 0) {
                                    $all_cost_children = ($cost_children * $children_number) * $calculatedates['number_of_nights'];
                                    $price += $all_cost_children;
                                }

                                $mydate = date('Y-m-d');
                                
                                $payan = "حجز عدد " . $value['rooms_number'] . " غرفة " . $value['code_1'];
                                
                                $cost = $price / $value['rooms_number'];
                                $total_cost = $price;
                                if ($payment_percentage > 0 || !empty($payment_cash)) {
                                    $cash_befor = $total_cost ;
                                    $cash_tax = 0 ;
                                    if ($TAX == 1) {
                                        $cash_tax = (($cash_befor / 1.14) * 0.03);
                                    }

                                    if(isset($payment_cash) && !empty($payment_cash)){
                                        $cash_payment = $payment_cash;
                                    } else {
                                        $cash_after = $cash_befor -  $cash_tax;
                                        $cash_payment = ($cash_after * $payment_percentage) / 100;
                                    }

                                    $updateQuery = "UPDATE hotel_booking_pay_arr 
                                                    SET id_reservation = :id_reservation, 
                                                        date_go = :date_go, 
                                                        cash = :cash 
                                                    WHERE id_type = 1 AND id_hotel_booking = :id_hotel_booking";
                                    $stmt = $con->prepare($updateQuery);
                                    $stmt->bindParam(':id_reservation', $reservation_id);
                                    $stmt->bindParam(':date_go', $payment_date);
                                    $stmt->bindParam(':cash', $cash_payment);
                                    $stmt->bindParam(':id_hotel_booking', $id_hotel_bookings);
                                    $stmt->execute();
                                }

                                if ($id_currency_codes != 1) {
                                    $amountSold = $cost;
                                    /* $cost = $cost - (($cost / 1.14) * 0.03);
                                    $price = $price - (($price / 1.14) * 0.03); */
                                    $cost = $cost * $currencyExchangeRate;
                                    $total_cost = $price * $currencyExchangeRate;
                                } else {
                                    $currencyExchangeRate = $currencyExchangeRateEGP;
                                    $amountSold = NULL;
                                }
                                $id_booking_file = $FileManager->updateBookingFile(
                                    $reservation_id,
                                    1,
                                    $id_hotel_bookings,
                                    '',
                                    $payan,
                                    $mydate,
                                    $value['rooms_number'],
                                    $id_currency_codes,
                                    $amountSold,
                                    '',
                                    $currencyExchangeRate,
                                    $cost,
                                    '',
                                    $total_cost,
                                    '',
                                    $sessionUser
                                );
                            }
                            /* $hotel_name = getId('hotels','ID', $id_hotels,'hotel_name');
                            $name= 'طلب دفع لفندق';
                            $disc_notifications = "مطلوب الدفع لفندق " . $hotel_name ;
                            $date_notifications = ""; */
                            // addnotifications($name, $disc_notifications, $date_notifications);
                            if ($id_booking_file) {
                                $theMsg = "تمت تعديل الحجز بنجاح!";
                                redirectlink($theMsg, $url = "reservations?do=all_data_file&id=" . $reservation_id, $name = "عرض الملف", $seconds = 0);
                            } else {
                                echo "حدث خطأ أثناء التعديل.";
                            }
                        }
                    } catch (PDOException $e) {
                        echo "حدث خطأ فى السيرفر أثناء تعديل الحجز: " . $e->getMessage();
                    }
                }
            } elseif (isset($_POST['train_booking'])) {
                $FileManager = new FileManager($con);
                // استلام البيانات من الفورم
                $reservation_id = $_POST['reservation_id'];
                $train_numper = $_POST['train_numper'];

                $departure_station = $_POST['departure_station'];
                $arrival_station = $_POST['arrival_station'];
                $departure_date = $_POST['departure_date'];
                $departure_time = $_POST['departure_time'];
                $arrival_date = $_POST['arrival_date'];
                $arrival_time = $_POST['arrival_time'];

                $number_individuals = $_POST['number_individuals'];

                $id_currency_codes = $_POST['id_currency_codes'];
                // $currencyExchangeRate = $_POST['currencyExchangeRate'];
                $price = $_POST['price'];
                // $price_sale = $_POST['price_sale'];
                // يمكنك إجراء عمليات التحقق هنا
                $formErrors = array();
                if (empty($reservation_id)) {
                    $formErrors[] = 'لا يوجد <strong>رقم ملف</strong>';
                }
                if (empty($train_numper)) {
                    $formErrors[] = 'برجاء أكتب رقم  <strong>القطار</strong>';
                }
                if (empty($departure_station)) {
                    $formErrors[] = 'برجاء تحديد محطة<strong>المغادرة</strong>';
                }
                if (empty($arrival_station)) {
                    $formErrors[] = 'برجاء تحديد محطة<strong>الوصول</strong>';
                }
                if (empty($number_individuals)) {
                    $formErrors[] = 'لا يجب أن يكون عدد التذاكر <strong>فارغ</strong>';
                }
                if (empty($price)) {
                    $formErrors[] = 'لا يجب أن يكون سعر التذكرة <strong>فارغ</strong>';
                }
                // Loop Into Errors Array And Echo It
                foreach ($formErrors as $error) {
                    echo '<div class="alert alert-danger">' . $error . '</div>';
                }
                if (empty($formErrors)) {
                    try {
                        $currencyExchangeRate = getId('currency','ID',$id_currency_codes,'currencyExchangeRate');
                        $currencyExchangeRateUSD = getId('currency','ID', 2,'currencyExchangeRate');
                        if ($currencyExchangeRateUSD > 0) {
                            $currencyExchangeRateEGP = 1 / $currencyExchangeRateUSD;
                        }

                        if ($id_currency_codes != 1) {
                            $amountSold = $price;
                            $price = $price * $currencyExchangeRate;
                        } else {
                            $currencyExchangeRate = $currencyExchangeRateEGP;
                            $amountSold = NULL;
                            $amountSold_sale = NULL;
                            /* $totalToYomya = $price * $number_individuals;
                            $totalToYomyaSale = $price_sale * $number_individuals; */
                        }
                        $total_cost = $number_individuals * $price;
                        // $RoomPrice_id = $FileManager->addRoomPrice($id_hotels, $id_room_type, $id_meal_system, $id_currency_codes, $amountSold, $amountSold_sale, $currencyExchangeRate, $disc, $price, $price_sale);

                        // $id_hotel_bookings = $FileManager->addTrainBooking($reservation_id, $id_hotels, $RoomPrice_id, $rooms_numper, $check_in_date, $check_out_date, 'on');
                        $id_train_bookings = $FileManager->addTrainBooking(
                            $reservation_id,
                            $train_numper,
                            $arrival_station,
                            $departure_station,
                            $arrival_time,
                            $departure_time,
                            $arrival_date,
                            $departure_date,
                            $number_individuals,
                            $id_currency_codes,
                            $amountSold,
                            '',
                            $currencyExchangeRate,
                            $price,
                            '',
                            $total_cost,
                            '',
                            $sessionUser
                        );
                        $reservationsManager = new ReservationsManager($con);

                        $id_cost_center_reservation = getId('reservations', 'id', $reservation_id, 'id_cost_center');
                        $id_tourism_management = getId('reservations', 'id', $reservation_id, 'id_tourism_management');

                /*         $id_lv_exp = getId('tourism_management', 'ID', $id_tourism_management, 'lv_exp');
                        $id_lv_eradat = getId('tourism_management', 'ID', $id_tourism_management, 'lv_eradat');
                */
                        $id_agent = getId('reservations', 'id', $reservation_id, 'agent_id');
                        
                        /* $id_lv_maden = getId('agents', 'ID', $id_agent, 'id_level_acc');
                        // $id_lv_daen = getId('hotels', 'ID', $value['id_hotel'], 'id_level_acc');
                        $id_lv_daen = 25;
                    */
                        $mydate = date('Y-m-d');

                     /*    $id_invoice = getId('invoicing','id_reservation',$reservation_id,'ID');
                        $no_invoice = getId('invoicing','ID',$id_invoice,'invoicing_no');
             */
                        $payan = "حجز عدد " . $number_individuals . " تذكرة قطار";

                        /* $NumberIndividuals = $reservationsManager->getNumberIndividualsReservationById($reservation_id);

                        $all_Individuals = 0;
                        if (!empty($NumberIndividuals)) {
                            foreach ($NumberIndividuals as $value) {
                                $all_Individuals += $value['number'];
                            }
                        } else {
                            $all_Individuals = 0;
                        } */

                        $transaction = new YomyaTransaction($con);

                        // $addyomya1 = $transaction->insertTransaction($mydate, $totalToYomya, $payan, $sessionUser, array($totalToYomya), array($id_lv_exp), array($totalToYomya), array($id_lv_daen), $id_currency_codes, $currencyExchangeRate, array($id_cost_center_reservation), NULL);
                        // $addyomya2 = $transaction->insertTransaction($mydate, $price_sale, "ايراد غرف فندق فاتورة رقم ".$no_invoice, $sessionUser, array($price_sale), array($id_lv_maden), array($price_sale), array($id_lv_eradat), $id_currency_codes, $currencyExchangeRate, NULL, array($id_cost_center_reservation));
                        
                        // $addInvoicingLine = $reservationsManager->addInvoicingLine($id_train_bookings, $id_invoice, $total_cost_sale, $sessionUser, $number_individuals, 11, $payan);
                        $id_booking_file = $FileManager->addBookingFile(
                            $reservation_id,
                            11,
                            $id_train_bookings,
                            '',
                            $payan,
                            $mydate,
                            $number_individuals,
                            $id_currency_codes,
                            $amountSold,
                            '',
                            $currencyExchangeRate,
                            $price,
                            '',
                            $total_cost,
                            '',
                            $sessionUser
                        );
                        if ($id_booking_file) {
                            $theMsg = "تمت إضافة الحجز بنجاح!";
                            redirectlink($theMsg, $url = "reservations?do=all_data_file&id=" . $reservation_id, $name = "عرض الملف", $seconds = 20);
                        } else {
                            echo "حدث خطأ أثناء الإضافة.";
                        }
                    } catch (PDOException $e) {
                        echo "حدث خطأ أثناء إضافة الحجز: " . $e->getMessage();
                    }
                }
            } elseif (isset($_POST['transportation_booking'])) {
                $FileManager = new FileManager($con);
                // استلام البيانات من الفورم
                $reservation_id = $_POST['reservation_id'];
                
                // $date_run = $_POST['date_run'];
                $id_companies_transportation = $_POST['companies_transportation'];
                $id_vehicles = $_POST['id_vehicles'];
                $car_num = $_POST['car_num'];
                $vehicle_capacity = $_POST['vehicle_capacity'];
                $name_driver = $_POST['drivers'];
                $id_employee_M = $_POST['id_employees'];
                $number_individuals = $_POST['number_individuals'];
                $date_run = $_POST['date_in'];
                $date_out = $_POST['date_out'];
                $time_in = $_POST['time_in'];
                $time_out = $_POST['time_out'];
                // $location_now = $_POST['location_now'];
                $location_now = '';
                $operation_statement = $_POST['operation_statement'];
                $id_employee_mang = $_POST['id_employee_mang'];
                $id_currency_codes = $_POST['id_currency_codes'];
                // $currencyExchangeRate = $_POST['currencyExchangeRate'];
                $price = $_POST['price'];
                // $price_sale = $_POST['price_sale'];
                $remarks = $_POST['remarks'];
                // يمكنك إجراء عمليات التحقق هنا
                $formErrors = array();
                if (empty($reservation_id)) {
                    $formErrors[] = 'لا يوجد <strong>رقم ملف</strong>';
                }
                if (empty($id_companies_transportation)) {
                    $formErrors[] = 'برجاء إختر  <strong>الشركة الؤجرة</strong>';
                }
                if (empty($price)) {
                    $formErrors[] = 'برجاء تحديد تكلفة<strong>السسيارة</strong>';
                }
                if ($id_companies_transportation == 1){
                    if (empty($id_vehicles)) {
                        $formErrors[] = 'برجاء تحديد<strong>السسيارة</strong>';
                    }
                } else {
                    if (empty($vehicle_capacity)) {
                        $formErrors[] = 'برجاء تحديد سعة<strong>السسيارة</strong>';
                    }
                    if (empty($car_num)) {
                        $formErrors[] = 'برجاء تحديد رقم<strong>السسيارة</strong>';
                    }
                }
                // Loop Into Errors Array And Echo It
                foreach ($formErrors as $error) {
                    echo '<div class="alert alert-danger">' . $error . '</div>';
                }
                if (empty($formErrors)) {
                    try {
                        if ($id_companies_transportation == 1){
                                $car_num = getId('vehicles','ID',$id_vehicles,'vehicle_plate_number');
                                $vehicle_capacity = getId('vehicles','ID',$id_vehicles,'seating_capacity');
                        }

                        $currencyExchangeRate = getId('currency','ID',$id_currency_codes,'currencyExchangeRate');
                        $currencyExchangeRateUSD = getId('currency','ID', 2,'currencyExchangeRate');
                        if ($currencyExchangeRateUSD > 0) {
                            $currencyExchangeRateEGP = 1 / $currencyExchangeRateUSD;
                        }
                        if ($id_currency_codes != 1) {
                            $amountSold = $price;
                            $price = $price * $currencyExchangeRate;    
                            $total_cost = $price;
                        } else {
                            $currencyExchangeRate = $currencyExchangeRateEGP;
                            $amountSold = NULL;
                            $total_cost = $price;
                        }
                        $new_NO_run = $FileManager->generateNoRunCommand();
                        // $RoomPrice_id = $FileManager->addRoomPrice($id_hotels, $id_room_type, $id_meal_system, $id_currency_codes, $amountSold, $amountSold_sale, $currencyExchangeRate, $disc, $price, $price_sale);

                        // $id_hotel_bookings = $FileManager->addTrainBooking($reservation_id, $id_hotels, $RoomPrice_id, $rooms_numper, $check_in_date, $check_out_date, 'on');
                        
                        $id_RunCommand = $FileManager->addRunCommandBooking(
                            $date_run, 
                            $date_out, 
                            '', 
                            $name_driver, 
                            $id_companies_transportation, 
                            $id_vehicles, 
                            $car_num, 
                            $location_now, 
                            $vehicle_capacity, 
                            $operation_statement, 
                            2, 
                            $reservation_id, 
                            $id_employee_M, 
                            $number_individuals, 
                            $new_NO_run, 
                            $time_in, 
                            $time_out, 
                            NULL, 
                            NULL, 
                            NULL, 
                            $id_employee_mang, 
                            $remarks,
                            $id_currency_codes,
                            $amountSold,
                            '',
                            $currencyExchangeRate,
                            $total_cost,
                            '', 
                            $sessionUser
                        );
                        $reservationsManager = new ReservationsManager($con);

                        $id_cost_center_reservation = getId('reservations', 'id', $reservation_id, 'id_cost_center');

                        $id_tourism_management = getId('reservations', 'id', $reservation_id, 'id_tourism_management');

                        $id_lv_exp = getId('tourism_management', 'ID', $id_tourism_management, 'lv_exp');
                        $id_lv_eradat = getId('tourism_management', 'ID', $id_tourism_management, 'lv_eradat');

                        $id_agent = getId('reservations', 'id', $reservation_id, 'agent_id');
                        
                        $id_lv_maden = getId('agents', 'ID', $id_agent, 'id_level_acc');
                        $id_lv_daen = getId('companies_transportation', 'ID', $id_companies_transportation, 'id_level_acc');
                        
                        $name_companies_transportation = getName('companies_transportation', 'ID', $id_companies_transportation, 'name_companie');
                        // $id_lv_daen = 25;

                        $mydate = date('Y-m-d');

                        $id_invoice = getId('invoicing','id_reservation',$reservation_id,'ID');
                        $no_invoice = getId('invoicing','ID',$id_invoice,'invoicing_no');

                        $payan = "حجز سيارة إنتقالات من شركة  " . $name_companies_transportation;

                        $transaction = new YomyaTransaction($con);

                        // $addyomya1 = $transaction->insertTransaction($mydate, $totalToYomya, $payan, $sessionUser, array($totalToYomya), array($id_lv_exp), array($totalToYomya), array($id_lv_daen), $id_currency_codes, $currencyExchangeRate, array($id_cost_center_reservation), NULL);
                        // $addyomya2 = $transaction->insertTransaction($mydate, $price_sale, "ايراد غرف فندق فاتورة رقم ".$no_invoice, $sessionUser, array($price_sale), array($id_lv_maden), array($price_sale), array($id_lv_eradat), $id_currency_codes, $currencyExchangeRate, NULL, array($id_cost_center_reservation));
                        $cost = $total_cost / $number_individuals;
                        $id_booking_file = $FileManager->addBookingFile(
                            $reservation_id,
                            2,
                            $id_RunCommand,
                            '',
                            $payan,
                            $mydate,
                            $number_individuals,
                            $id_currency_codes,
                            $amountSold,
                            '',
                            $currencyExchangeRate,
                            $cost,
                            '',
                            $total_cost,
                            '',
                            $sessionUser
                        );
                        // $addInvoicingLine = $reservationsManager->addInvoicingLine($id_RunCommand, $id_invoice, $total_cost_sale, $sessionUser, $number_individuals, 2, $payan);
                        if ($id_booking_file) {
                            $theMsg = "تمت إضافة الحجز بنجاح!";
                            redirectlink($theMsg, $url = "reservations?do=all_data_file&id=" . $reservation_id, $name = "عرض الملف", $seconds = 0);
                        } else {
                            echo "حدث خطأ أثناء الإضافة.";
                        }
                    } catch (PDOException $e) {
                        echo "حدث خطأ أثناء إضافة الحجز: " . $e->getMessage();
                    }
                }
            } elseif (isset($_POST['airline_booking'])) {
                $FileManager = new FileManager($con);
                // استلام البيانات من الفورم
                $reservation_id = $_POST['reservation_id'];
                $id_airline = $_POST['id_airline'];
                $flight_number = $_POST['flight_number'];

                $departure_station = $_POST['departure_station'];
                $arrival_station = $_POST['arrival_station'];
                $departure_date = $_POST['departure_date'];
                $departure_time = $_POST['departure_time'];
                $arrival_date = $_POST['arrival_date'];
                $arrival_time = $_POST['arrival_time'];

                $number_individuals = $_POST['number_individuals'];

                $id_currency_codes = $_POST['id_currency_codes'];
                // $currencyExchangeRate = $_POST['currencyExchangeRate'];
                $price = $_POST['price'];
                // $price_sale = $_POST['price_sale'];
                // يمكنك إجراء عمليات التحقق هنا
                $formErrors = array();
                if (empty($reservation_id)) {
                    $formErrors[] = 'لا يوجد <strong>رقم ملف</strong>';
                }
                if (empty($id_airline)) {
                    $formErrors[] = 'برجاء إختر شركة الطيران  <strong>الرحلة</strong>';
                }
                if (empty($flight_number)) {
                    $formErrors[] = 'برجاء أكتب رقم  <strong>الرحلة</strong>';
                }
                if (empty($departure_station)) {
                    $formErrors[] = 'برجاء تحديد محطة<strong>المغادرة</strong>';
                }
                if (empty($arrival_station)) {
                    $formErrors[] = 'برجاء تحديد محطة<strong>الوصول</strong>';
                }
                if (empty($number_individuals)) {
                    $formErrors[] = 'لا يجب أن يكون عدد التذاكر <strong>فارغ</strong>';
                }
                if (empty($price)) {
                    $formErrors[] = 'لا يجب أن يكون سعر التذكرة <strong>فارغ</strong>';
                }
                // Loop Into Errors Array And Echo It
                foreach ($formErrors as $error) {
                    echo '<div class="alert alert-danger">' . $error . '</div>';
                }
                if (empty($formErrors)) {
                    try {

                        $currencyExchangeRate = getId('currency','ID',$id_currency_codes,'currencyExchangeRate');
                        $currencyExchangeRateUSD = getId('currency','ID', 2,'currencyExchangeRate');
                        if ($currencyExchangeRateUSD > 0) {
                            $currencyExchangeRateEGP = 1 / $currencyExchangeRateUSD;
                        }
                        
                        if ($id_currency_codes != 1) {
                            $amountSold = $price;
                            $price = $price * $currencyExchangeRate;
                        } else {
                            $currencyExchangeRate = $currencyExchangeRateEGP;
                            $amountSold = NULL;
                            $amountSold_sale = NULL;
                            /* $totalToYomya = $price * $number_individuals;
                            $totalToYomyaSale = $price_sale * $number_individuals; */
                        }
                        $total_cost = $number_individuals * $price;

                        // $id_hotel_bookings = $FileManager->addTrainBooking($reservation_id, $id_hotels, $RoomPrice_id, $rooms_numper, $check_in_date, $check_out_date, 'on');
                        $id_flight_bookings = $FileManager->addFlightBooking(
                            $reservation_id,
                            $id_airline,
                            $flight_number,
                            $arrival_station,
                            $departure_station,
                            $arrival_time,
                            $departure_time,
                            $arrival_date,
                            $departure_date,
                            $number_individuals,
                            $id_currency_codes,
                            $amountSold,
                            '',
                            $currencyExchangeRate,
                            $price,
                            '',
                            $total_cost,
                            '',
                            $sessionUser
                        );
                        $reservationsManager = new ReservationsManager($con);

                        $id_cost_center_reservation = getId('reservations', 'id', $reservation_id, 'id_cost_center');
                        $id_tourism_management = getId('reservations', 'id', $reservation_id, 'id_tourism_management');
                /* 
                        $id_lv_exp = getId('tourism_management', 'ID', $id_tourism_management, 'lv_exp');
                        $id_lv_eradat = getId('tourism_management', 'ID', $id_tourism_management, 'lv_eradat');
                */
                        $id_agent = getId('reservations', 'id', $reservation_id, 'agent_id');
                        
                        /* $id_lv_maden = getId('agents', 'ID', $id_agent, 'id_level_acc');
                        $id_lv_daen = getId('airline', 'ID', $id_airline, 'id_level_acc'); */
                        // $id_lv_daen = 25;

                        $mydate = date('Y-m-d');

                        /* $id_invoice = getId('invoicing','id_reservation',$reservation_id,'ID');
                        $no_invoice = getId('invoicing','ID',$id_invoice,'invoicing_no');
                 */
                        $payan = "حجز عدد " . $number_individuals . " تذكرة طيران";


                        $transaction = new YomyaTransaction($con);

                        // $addyomya1 = $transaction->insertTransaction($mydate, $totalToYomya, $payan, $sessionUser, array($totalToYomya), array($id_lv_exp), array($totalToYomya), array($id_lv_daen), $id_currency_codes, $currencyExchangeRate, array($id_cost_center_reservation), NULL);
                        // $addyomya2 = $transaction->insertTransaction($mydate, $price_sale, "ايراد غرف فندق فاتورة رقم ".$no_invoice, $sessionUser, array($price_sale), array($id_lv_maden), array($price_sale), array($id_lv_eradat), $id_currency_codes, $currencyExchangeRate, NULL, array($id_cost_center_reservation));
                        
                        // $addInvoicingLine = $reservationsManager->addInvoicingLine($id_flight_bookings, $id_invoice, $total_cost_sale, $sessionUser, $number_individuals, 12, $payan);
                        $id_booking_file = $FileManager->addBookingFile(
                            $reservation_id,
                            12,
                            $id_flight_bookings,
                            '',
                            $payan,
                            $mydate,
                            $number_individuals,
                            $id_currency_codes,
                            $amountSold,
                            '',
                            $currencyExchangeRate,
                            $price,
                            '',
                            $total_cost,
                            '',
                            $sessionUser
                        );
                        if ($id_booking_file) {
                            $theMsg = "تمت إضافة الحجز بنجاح!";
                            redirectlink($theMsg, $url = "reservations?do=all_data_file&id=" . $reservation_id, $name = "عرض الملف", $seconds = 0);
                        } else {
                            echo "حدث خطأ أثناء الإضافة.";
                        }
                    } catch (PDOException $e) {
                        echo "حدث خطأ أثناء إضافة الحجز: " . $e->getMessage();
                    }
                }
            } elseif (isset($_POST['booking_exp'])) {
                $FileManager = new FileManager($con);
                // استلام البيانات من الفورم
                $reservation_id = $_POST['reservation_id'];
                $id_invoicing_type_exp = $_POST['id_invoicing_type_exp'];
                $mydate = $_POST['mydate'];
                $name_type = $_POST['name_type'];
                $number_individuals = $_POST['number_individuals'];
                
                $id_currency_codes = $_POST['id_currency_codes'];
                // $currencyExchangeRate = $_POST['currencyExchangeRate'];
                $price = $_POST['price'];
                // $price_sale = $_POST['price_sale'];
                // $payment = $_POST['payment'];

                // يمكنك إجراء عمليات التحقق هنا
                $formErrors = array();
                if (empty($reservation_id)) {
                    $formErrors[] = 'لا يوجد <strong>رقم ملف</strong>';
                }
                if (empty($id_invoicing_type_exp)) {
                    $formErrors[] = 'برجاء إختر <strong>البند</strong>';
                }
                if (empty($name_type)) {
                    $formErrors[] = 'برجاء أكتب <strong>الاسم</strong>';
                }
                if (empty($mydate)) {
                    $formErrors[] = 'برجاء تحديد<strong>التاريخ</strong>';
                }
                if (empty($number_individuals)) {
                    $formErrors[] = 'لا يجب أن يكون العدد <strong>فارغ</strong>';
                }
                if (empty($price)) {
                    $formErrors[] = 'لا يجب أن يكون التكلفة للفرد <strong>فارغ</strong>';
                }
                /* if (empty($payment)) {
                    $formErrors[] = 'برجاء حدد طريقة الدفع <strong>فارغ</strong>';
                } */
                // Loop Into Errors Array And Echo It
                foreach ($formErrors as $error) {
                    echo '<div class="alert alert-danger">' . $error . '</div>';
                }
                if (empty($formErrors)) {
                    try {
                        $currencyExchangeRate = getId('currency','ID',$id_currency_codes,'currencyExchangeRate');
                        $currencyExchangeRateUSD = getId('currency','ID', 2,'currencyExchangeRate');
                        if ($currencyExchangeRateUSD > 0) {
                            $currencyExchangeRateEGP = 1 / $currencyExchangeRateUSD;
                        }

                        if ($id_currency_codes != 1) {
                            $amountSold = $price;
                            $price = $price * $currencyExchangeRate;
                        } else {
                            $currencyExchangeRate = $currencyExchangeRateEGP;
                            $amountSold = NULL;
                            $amountSold_sale = NULL;
                        }
                        $total_cost = $number_individuals * $price;

                        $id_line_type = getId('invoicing_type_exp', 'ID', $id_invoicing_type_exp, 'id_line_type');
                        // $id_hotel_bookings = $FileManager->addTrainBooking($reservation_id, $id_hotels, $RoomPrice_id, $rooms_numper, $check_in_date, $check_out_date, 'on');
                        $id_booking_file = $FileManager->addBookingFile(
                            $reservation_id,
                            $id_line_type,
                            '',
                            $id_invoicing_type_exp,
                            $name_type,
                            $mydate,
                            $number_individuals,
                            $id_currency_codes,
                            $amountSold,
                            '',
                            $currencyExchangeRate,
                            $price,
                            '',
                            $total_cost,
                            '',
                            $sessionUser
                        );
                        /* $reservationsManager = new ReservationsManager($con);

                        $id_cost_center_reservation = getId('reservations', 'id', $reservation_id, 'id_cost_center');
                        $id_tourism_management = getId('reservations', 'id', $reservation_id, 'id_tourism_management');

                        $id_lv_exp = getId('tourism_management', 'ID', $id_tourism_management, 'lv_exp');
                        $id_lv_eradat = getId('tourism_management', 'ID', $id_tourism_management, 'lv_eradat');

                        $id_agent = getId('reservations', 'id', $reservation_id, 'agent_id');
                        
                        $id_lv_maden = getId('agents', 'ID', $id_agent, 'id_level_acc');
                        // $id_lv_daen = getId('airline', 'ID', $id_airline, 'id_level_acc');
                        // $id_lv_daen = $payment;

                        $mydate = date('Y-m-d');

                        $id_invoice = getId('invoicing','id_reservation',$reservation_id,'ID');
                        $no_invoice = getId('invoicing','ID',$id_invoice,'invoicing_no');
                        
                        $id_line_type = getId('invoicing_type_exp','ID', $id_invoicing_type_exp,'id_line_type');
                        $name_exp = getName('invoicing_type_exp','ID', $id_invoicing_type_exp,'name');
                        $payan = "تكلفة عدد " . $number_individuals . " فرد فى ". $name_exp. " " . $name_type;
                */
                        /* $NumberIndividuals = $reservationsManager->getNumberIndividualsReservationById($reservation_id);

                        $all_Individuals = 0;
                        if (!empty($NumberIndividuals)) {
                            foreach ($NumberIndividuals as $value) {
                                $all_Individuals += $value['number'];
                            }
                        } else {
                            $all_Individuals = 0;
                        } */

                        // $transaction = new YomyaTransaction($con);

                        // $addyomya1 = $transaction->insertTransaction($mydate, $totalToYomya, $payan, $sessionUser, array($totalToYomya), array($id_lv_exp), array($totalToYomya), array($id_lv_daen), $id_currency_codes, $currencyExchangeRate, array($id_cost_center_reservation), NULL);
                        // $addyomya2 = $transaction->insertTransaction($mydate, $price_sale, "ايراد غرف فندق فاتورة رقم ".$no_invoice, $sessionUser, array($price_sale), array($id_lv_maden), array($price_sale), array($id_lv_eradat), $id_currency_codes, $currencyExchangeRate, NULL, array($id_cost_center_reservation));
                        
                        // $addInvoicingLine = $reservationsManager->addInvoicingLine($id_booking_file, $id_invoice, $total_cost_sale, $sessionUser, $number_individuals, $id_line_type, $payan);
                        if ($id_line_type) {
                            $theMsg = "تمت إضافة الحجز بنجاح!";
                            redirectlink($theMsg, $url = "reservations?do=all_data_file&id=" . $reservation_id, $name = "عرض الملف", $seconds = 0);
                        } else {
                            echo "حدث خطأ أثناء الإضافة.";
                        }
                    } catch (PDOException $e) {
                        echo "حدث خطأ أثناء إضافة الحجز: " . $e->getMessage();
                    }
                }
            } elseif (isset($_POST['reservation_confirmation'])) {
                
                $FileManager = new FileManager($con);
                $id_hotel_bookings = $_POST['id_hotel_bookings'];
                $formErrors = array();
                if (empty($id_hotel_bookings)) {
                    $formErrors[] = 'لا يوجد <strong>رقم حجز</strong>';
                }
                foreach ($formErrors as $error) {
                    echo '<div class="alert alert-danger">' . $error . '</div>';
                }
                if (empty($formErrors)) {
                    try {
                        // $con->beginTransaction();
                        $reservationsManager = new ReservationsManager($con);
                        $hotel_bookings = $reservationsManager->getHotelBookingsById($id_hotel_bookings);
                        foreach ($hotel_bookings as $value) {
                            $id_hotel_bookings =  $value['id_hotel_bookings'];
                            $price = $value['price'];
                            $price_sale = $value['price_sale'];
                            $id_currency_codes = $value['id_currency_codes'];
                            $amountSold = $value['amountSold'];
                            $amountSold_sale = $value['amountSold_sale'];
                            $currencyExchangeRate = $value['currencyExchangeRate'];

                            $calculatedates = $reservationsManager->calculateNightAndDayCount($value['check_in_date'], $value['check_out_date']);

                            if (!empty($amountSold) && $amountSold > 0) {
                                $price = $amountSold;
                            }
                            if (!empty($amountSold_sale) && $amountSold_sale > 0) {
                                $price_sale = $amountSold_sale;
                            }

                            if ($value['code_2'] == "X" || $value['code_1'] == "SGL") {
                                $price = $value['rooms_number'] * $price;
                                $price *= $calculatedates['number_of_nights'];
                            } elseif ($value['code_2'] == "XX" || $value['code_1'] == "DBL") {
                                $price = $value['rooms_number'] * $price;
                                $price *= 2;
                                $price *= $calculatedates['number_of_nights'];
                            } elseif ($value['code_2'] == "XXX" || $value['code_1'] == "TPL") {
                                $price = $value['rooms_number'] * $price;
                                $price *= 3;
                                $price *= $calculatedates['number_of_nights'];
                            } else {
                                $price = $value['rooms_number'] * $price;
                                $price *= $calculatedates['number_of_nights'];
                            }
                            if ($value['code_2'] == "X" || $value['code_1'] == "SGL") {
                                $price_sale = $value['rooms_number'] * $price_sale;
                                $price_sale *= $calculatedates['number_of_nights'];
                            } elseif ($value['code_2'] == "XX" || $value['code_1'] == "DBL") {
                                $price_sale = $value['rooms_number'] * $price_sale;
                                $price_sale *= 2;
                                $price_sale *= $calculatedates['number_of_nights'];
                            } elseif ($value['code_2'] == "XXX" || $value['code_1'] == "TPL") {
                                $price_sale = $value['rooms_number'] * $price_sale;
                                $price_sale *= 3;
                                $price_sale *= $calculatedates['number_of_nights'];
                            } else {
                                $price_sale = $value['rooms_number'] * $price_sale;
                                $price_sale *= $calculatedates['number_of_nights'];
                            }

                            
                            $id_cost_center_reservation = getId('reservations', 'id', $value['id_reservation'], 'id_cost_center');
                            $id_tourism_management = getId('reservations', 'id', $value['id_reservation'], 'id_tourism_management');
                            $id_agent = getId('reservations', 'id', $value['id_reservation'], 'agent_id');

                            $id_lv_exp = getId('tourism_management', 'ID', $id_tourism_management, 'lv_exp');
                            $id_lv_eradat = getId('tourism_management', 'ID', $id_tourism_management, 'lv_eradat');

                            $id_lv_maden = getId('agents', 'ID', $id_agent, 'id_level_acc');
                            $id_lv_daen = getId('hotels', 'ID', $value['id_hotel'], 'id_level_acc');

                            $id_cost_center_hotel = $value['id_cost_center'];

                            $mydate = date('Y-m-d');

                            $transaction = new YomyaTransaction($con);

                            // $addyomya1 = $transaction->insertTransaction($mydate, $price, "حجز غرف فندق", $sessionUser, array($price), array($id_lv_exp), array($price), array($id_lv_daen), $id_currency_codes, $currencyExchangeRate, array($id_cost_center_reservation), array($id_cost_center_hotel));
                            // $addyomya2 = $transaction->insertTransaction($mydate, $price_sale, "ايراد غرف فندق", $sessionUser, array($price_sale), array($id_lv_maden), array($price_sale), array($id_lv_eradat), $id_currency_codes, $currencyExchangeRate, NULL, array($id_cost_center_reservation));

                            $sql = "UPDATE hotel_bookings SET check_status = 'on' WHERE ID = $id_hotel_bookings";
                            $result = $con->exec($sql);
                        }
                        
                        /* if ($getstm) {
                            
                        } else {

                            $theMsg = "هناك خطاء فى الترحيل برجاء الرجوع للمبرمج";
                            redirectlink($theMsg, $url = 'reports_account.php?Manage=tree&do=add_yomya&err[]=' . $msgErr[0], $name = "الرجوع للخلف", $seconds = 15);
                        } */
                        // $con->commit();
                        $theMsg = "تم تأكيد الحجز بنجاح!";
                        redirectlink($theMsg, $url = "reservations?do=all_data_file&id=" . $value['id_reservation'], $name = "عرض الملف", $seconds = 0);
                        
                    } catch (Exception $e) {
                        // $con->rollBack();
                        echo "حدث خطأ أثناء تأكيد الحجز: " . $e->getMessage();
                    }
                }
            }
        }
    } elseif ($do === 'invoicess') {
        $id_file = isset($_GET['id']) && is_numeric($_GET['id']) ? intval($_GET['id']) : 0;
        $countmanagement = 0;
        $id_management = getId("reservations","id",$id_file,"id_tourism_management");
        if ($id_management > 0) {
            $tourism_management = $con->prepare("SELECT * FROM tourism_management where ID = $id_management");
            $tourism_management->execute();
            $managements = $tourism_management->fetch(PDO::FETCH_ASSOC);
            $count = $tourism_management->rowCount();
            if ($count > 0) {
                $department_id = $managements['department_id'];
                $name_management = $managements['name_management'];
                $id_user = $_SESSION['admin'];
                if (checkadmin($id_user, $department_id, 2) == 1 ) {
                    $countmanagement += 1;
                }
            } else {
                $countmanagement = 0;
            }
        } else {
            $countmanagement = 0;
        }
        
        if ($countmanagement > 0 && $id_file > 0) {
            if (isset($_GET['id_invoice']) && is_numeric($_GET['id_invoice'])) {
                $id_invoice = $_GET['id_invoice'];
                $reservationsManager = new ReservationsManager($con);
                $reservation_id = $id_file;
                $reservationDatas = $reservationsManager->getReservationById($reservation_id);
                $invoicingDatas = $reservationsManager->getInvoicingById($id_invoice);
                $InvoicingLines = $reservationsManager->getInvoicingDataById($id_invoice);
                $getBookingFileById = $reservationsManager->getBookingFileById($reservation_id, 1);

                $sumInvoicingLine = $reservationsManager->sumInvoicingLineById($id_invoice);
                $file_number = explode("/", $reservationDatas['file_number']);
                $invoicing_no = getName("invoicing", "ID", $id_invoice,"invoicing_no");
                $invoice_status = getName("invoicing", "ID", $id_invoice,"invoice_status");
                $agent_name = getName("agents", "ID", $reservationDatas['agent_id'],"agent_name");
                $nationality_id = getId('clients','ID',$reservationDatas['client_id'], 'id_nationality');
                $nationality_name_en = getId('nationality','ID',$nationality_id, 'nationality_name_en');

                $NumberIndividuals = $reservationsManager->getNumberIndividualsReservationById($reservation_id);

                $all_Individuals = 0;

                $sumInvoicingLine_float = (float) $sumInvoicingLine['cash'];

                // تحويل القيمة إلى نوع "int" (إذا كان ذلك ضرورياً)
                $sumInvoicingLine_int = (int) $sumInvoicingLine_float;
                $rate = 0;
                if (!empty($NumberIndividuals)) {
                    foreach ($NumberIndividuals as $value) {
                        $all_Individuals += $value['number'];
                    }
                    if ($sumInvoicingLine_int != 0) {
                        $rate = $sumInvoicingLine_int / $all_Individuals;
                    }
                } else {
                    $all_Individuals = 0;
                }
                echo "<h1 class='input-group-text text-center'><a href='?do=all_file'>عرض ملفات </a>: <a href='?do=all_file&id_management={$id_management}'>{$name_management}</a> / <a href='?do=all_data_file&id=" . $reservation_id . "'> ملف رقم : {$file_number[0]} / {$file_number[1]} </a> فاتورة رقم {$invoicing_no}</h1>";

                $head = '<table>
                <tr>
                    <td>
                        <img src="img/logo.png" width="100"  />
                    </td>
                    <td>
                    إكسبلور ناسا ترافل
                    </td>
                </tr>
            </table>
            <div></div>';
                $html = '<div class="row" style="position: relative;width: 21cm;padding-bottom: 95px;" >
                
                <table class="table table-bordered" style="border: 1px solid #000;text-align: left;width: 250px;">
                <tr>
                    <td>
                        invoice NO. '.$invoicing_no.'
                    </td>
                </tr>
                     <tr>
                        <td>
                        FILE NO : '.$reservationDatas['file_number'].'
                        </td>
                     </tr>
                </table>

                <div></div>

                <table style="border: 1px solid #000; text-align: left;">
                <tr>
                    <td style="border: 1px solid #000; text-align: left;">
                        AGENTE 
                    </td>
                    <td colspan="4" style="border: 1px solid #000; text-align: left;">
                        '.$agent_name.'
                    </td>
                    </tr>
                    <tr>
                        <td style="border: 1px solid #000; text-align: left;">
                            Date 
                        </td>
                        <td style="border: 1px solid #000; text-align: left;">
                            FROM : '.$reservationDatas['arrival_date'].'
                        </td>
                        <td style="border: 1px solid #000; text-align: left;">
                            TO : '.$reservationDatas['departure_date'].'
                        </td>
                        <td style="border: 1px solid #000; text-align: left;">
                            Nationality 
                        </td>
                        <td style="border: 1px solid #000; text-align: left;">
                            '.$nationality_name_en.'
                        </td>
                    </tr>
                </table>

                <br>
                <hr>
                <div style="text-align: center;">
                    Thank you for your business
                </div>

                <table>
                    <tr>
                        <td style="border: 1px solid #000;border-bottom: none;text-align: center;">
                            NO. OF PAX
                        </td>
                        <td style="border: 1px solid #000;border-bottom: none;text-align: center;">
                            DESCRIPTION
                        </td>
                        <td style="border: 1px solid #000;border-bottom: none;text-align: center;">
                            RATE P/P 
                        </td>
                        <td style="border: 1px solid #000;border-bottom: none;text-align: center;">
                            TOTAL 
                        </td>
                    </tr>';
                    $total_cost_invice = 0;
                    if (is_array($InvoicingLines)) {
                        foreach ($InvoicingLines as $key => $value) {
                            $total_cost_invice += $value['total_invoice'];
                            $html .= '<tr>
                                <td style="border: 1px solid #000;border-bottom: none;text-align: center;">
                                    <div>'.$value['no_of'].' Pax</div>
                                    <div> </div>
                                </td>
                                <td style="border: 1px solid #000;border-bottom: none;text-align: left;">
                                    <div> - '.$value['disc'].'.</div>
                                    <div> -</div>
                                </td>
                                <td style="border: 1px solid #000;border-bottom: none;text-align: center;">
                                    <div>'.$value['rate_pp'] .' $</div>
                                    <div> </div>
                                </td>
                                <td style="border: 1px solid #000;border-bottom: none;text-align: center;">
                                    <div>'.$value['total_invoice'].' $</div>
                                    <div> </div>
                                </td>
                            </tr>';
                        }
                    }
                    $html .= '<tr>
                        <td style="border: 1px solid #000; text-align: center;">
                            Total
                        </td>
                        <td colspan="2" style="border: 1px solid #000; text-align: center;">
                        '.NumberToWords::transformNumber('en', $total_cost_invice).' dollars
                        </td>
                        <td style="border: 1px solid #000; text-align: center;">
                            '.$total_cost_invice.' $
                        </td>
                    </tr>
                </table>

                <div class="col-md-9 mt-lg-5">
                    
                </div>
                <div class="col-md-3 mt-lg-5">
                    Account Manager
                </div>
            ';
            $htmlvo = '<div class="row" style="position: relative;width: 21cm;padding-bottom: 95px;" >
                <h2 style="text-align: center;">Confirmation Hotel</h2>
                <div></div>

                <div style=" width: 50%; ">
                    <table cellspacing="0" cellpadding="1" style="border: 1px solid #000; text-align: left;width: 250px;">
                        <tr>
                            <td style="border: 1px solid #000; text-align: left;">
                            FILE NO : '.$reservationDatas['file_number'].'
                            </td>
                        </tr>
                    </table>
                    </div>
                    <div style=" width: 50%; ">
                    <table style="border: 1px solid #000; text-align: left;width: 250px;">
                        <tr>
                            <td style="border: 1px solid #000; text-align: left;">
                                Agent :  
                                '.$agent_name.'
                            </td>
                        </tr>
                    </table>
                </div>
                

                <br>
                <hr>
                <table>
                    <tr>
                        <td style="border: 1px solid #000;border-bottom: none;text-align: center;">
                            From
                        </td>
                        <td style="border: 1px solid #000;border-bottom: none;text-align: center;">
                            To
                        </td>
                        <td style="border: 1px solid #000;border-bottom: none;text-align: center;">
                            Nights
                        </td>
                        <td style="border: 1px solid #000;border-bottom: none;text-align: center;">
                            meal_system  
                        </td>
                        <td style="border: 1px solid #000;border-bottom: none;text-align: center;">
                            Rooms 
                        </td>
                    </tr>';
                    if (is_array($getBookingFileById)) {
                        foreach ($getBookingFileById as $key => $value) {
                            $check_in_date = getName("hotel_bookings", "ID", $value['id_line_booking'],"check_in_date");
                            $check_out_date = getName("hotel_bookings", "ID", $value['id_line_booking'],"check_out_date");
                            $id_room_prices = getName("hotel_bookings", "ID", $value['id_line_booking'],"id_room_prices");
                            $rooms_number = getName("hotel_bookings", "ID", $value['id_line_booking'],"rooms_number");
                            $id_meal_system = getId("room_prices", "ID", $id_room_prices,"id_meal_system");
                            $id_room_type = getId("room_prices", "ID", $id_room_prices,"id_room_type");
                            $code_1 = getId("room_type", "ID", $id_room_type,"code_1");
                            $id_room_prices = getName("meal_system", "ID", $id_meal_system,"short_name");
                            $calculatedates = $reservationsManager->calculateNightAndDayCount($check_in_date, $check_out_date);
                            $htmlvo .='
                            <tr>
                                <td style="border: 1px solid #000;border-bottom: none;text-align: center;">
                                    <div>'.$check_in_date.'</div>
                                </td>
                                <td style="border: 1px solid #000;border-bottom: none;text-align: center;">
                                    <div>'.$check_out_date.'</div>
                                </td>
                                <td style="border: 1px solid #000;border-bottom: none;text-align: center;">
                                    <div>'.$calculatedates['number_of_nights'] .'</div>
                                </td>
                                <td style="border: 1px solid #000;border-bottom: none;text-align: center;">
                                    <div>'.$id_room_prices.'</div>
                                </td>
                                <td style="border: 1px solid #000;border-bottom: none;text-align: center;">
                                    <div>'.$rooms_number.' ' . $code_1. ' </div>
                                </td>
                            </tr>';
                        }
                    }
                    
                    $htmlvo .=<<<EOD
                        </table>

                        <div class="col-md-9 mt-lg-5">
                            
                        </div>
                        <div class="col-md-12 mt-lg-5">
                        <p>
                        Cancellation Policy:  Full Charge Deduction / Non Refundable Stay.
                        </p>
                        <p>
                        Check-In Policy: Obligatory National Id's, Marriage Certificates, Children's Certificates - Customary marriage not accepted.
                        </p>
                        </div>
                        EOD;
                $htmlBank = <<<EOD
                    <br>
                    <br>
                    <br>
                    <br>
                    <br>
                    <br>
                    <table style="border: 1px solid #000; text-align: center;">
                    <tr>
                        <td colspan="2" style="border: 1px solid #000;text-align: center;font-size: 20px;font-weight: 800;">
                            Bank account details
                        </td>
                    </tr>
                    <tr>
                        <td colspan="2" style="border: 1px solid #000;text-align: center;font-size: 18px;font-weight: 800;">
                            Arab African International Bank 
                        </td>
                    </tr>
                    <tr>
                    
                    <td style="border: 1px solid #000; text-align: center;">
                        SWIFT CODE 
                    </td>
                    <td style="border: 1px solid #000; text-align: center;">
                        ARAIEGCXMRG
                    </td>
                    </tr>
                    <tr>
                        <td rowspan="" style="border: 1px solid #000; text-align: center;">
                            رقم الحساب USD
                        </td>
                        <td style="border: 1px solid #000; text-align: center;">
                            1163963510010101
                        </td>
                    </tr>
                    <tr>
                        <td rowspan="" style="border: 1px solid #000; text-align: center;">
                            رقم الحساب EUR
                        </td>
                        <td style="border: 1px solid #000; text-align: center;">
                            1163963510010301
                        </td>
                    </tr>
                    <tr>
                        <td rowspan="" style="border: 1px solid #000; text-align: center;">
                            IBAN USD
                        </td>
                        <td style="border: 1px solid #000; text-align: center;">
                            EG090057000801163963510010101
                        </td>
                    </tr>
                    <tr>
                        <td style="border: 1px solid #000; text-align: center;">
                            IBAN EUR
                        </td>
                        <td style="border: 1px solid #000; text-align: center;">
                            EG410057000801163963510010301
                        </td>
                    </tr>
                
                </table></div>
                EOD;
        /* 
            <tr>
                <td colspan="2" style="border: 1px solid #000;text-align: center;font-size: 18px;font-weight: 800;">
                    EG Bank 
                </td>
           </tr>
            <tr>
                
                <td style="border: 1px solid #000; text-align: center;">
                    SWIFT CODE 
                </td>
                <td style="border: 1px solid #000; text-align: center;">
                    EGGBEGCAXXX
                </td>
            </tr>
            <tr>
                <td rowspan="4" style="border: 1px solid #000; text-align: center;">
                    رقم الحساب
                </td>
                <td style="border: 1px solid #000; text-align: center;">
                    USD
                </td>
            </tr>
            <tr>
                <td style="border: 1px solid #000; text-align: center;">
                0032-618652-002
                </td>
            </tr>
            <tr>
                <td style="border: 1px solid #000; text-align: center;">
                    EUR
                </td>
            </tr>
            <tr>
                <td style="border: 1px solid #000; text-align: center;">
                0032-618652-003
                </td>
            </tr>
            <tr>
                <td rowspan="4" style="border: 1px solid #000; text-align: center;">
                    IBAN
                </td>
                <td style="border: 1px solid #000; text-align: center;">
                    USD
                </td>
            </tr>
            <tr>
                <td style="border: 1px solid #000; text-align: center;">
                EG550029003200000032618652002
                </td>
            </tr>
            <tr>
                <td style="border: 1px solid #000; text-align: center;">
                    EUR
                </td>
            </tr>
            <tr>
                <td style="border: 1px solid #000; text-align: center;">
                EG280029003200000032618652003
                </td>
            </tr>
         */
        //////////////////////////////////////////////////////////////////////////////////////////////////////////
            
                ?>
                <div class="container mt-5">
                    <!-- <form action="?do=insert_invoices_line" method="post">
                        <input type="hidden" name="reservation_id" value="<?php echo $reservation_id; ?>">
                        <input type="hidden" name="id_invoice" value="<?php echo $id_invoice; ?>">
                        <div class="row">
                            <div class="col-md-2 mb-3">
                                <br>
                                <button type="submit" class="btn btn-primary" name="invoce_ok">تأكيد الفاتورة</button>
                            </div>
                        </div>
                    </form> -->
                        <?php
                            if ($invoice_status == 1) {
                                $chek_disabled = 'disabled';
                            } else {
                                $chek_disabled = '';
                            }
                        ?>  
                        <form action="?do=insert_invoices_line" method="post">
                            <input type="hidden" name="reservation_id" value="<?php echo $reservation_id; ?>"  <?=$chek_disabled?>>
                            <input type="hidden" name="id_invoice" value="<?php echo $id_invoice; ?>">
                            <input type="hidden" name="back_invoice" value="1">
                            <div class="row">
                                <div class="col-md-3 mb-3">
                                    <div class="form-floating">
                                        <input type="text" name="number" class="form-control" placeholder="عدد الافراد" required  <?=$chek_disabled?>>
                                        <label for="number" class="form-label">عدد الافراد</label>
                                    </div>
                                </div>
                                <div class="col-md-2 mb-3">
                                    <div class="form-floating">
                                        <input type="text" name="payan" class="form-control" placeholder="البيان" required  <?=$chek_disabled?>>
                                        <label for="payan" class="form-label">البيان</label>
                                    </div>
                                </div>
                                <!-- <div class="col-md-2 mb-3">
                                    <div class="form-floating">
                                        <input type="text" name="cost_child" class="form-control" placeholder="السعر للطفل"   <?=$chek_disabled?>>
                                        <label for="cost_child" class="form-label">السعر للطفل</label>
                                    </div>
                                </div>
                                <div class="col-md-2 mb-3">
                                    <div class="form-floating">
                                        <input type="text" name="num_child" class="form-control" placeholder="عدد الاطفال"  <?=$chek_disabled?>>
                                        <label for="num_child" class="form-label">عدد الاطفال</label>
                                    </div>
                                </div> -->
                                <div class="col-md-2 mb-3">
                                    <div class="form-floating">
                                        <input type="text" name="cost" class="form-control" placeholder="السعر للفرد" required  <?=$chek_disabled?>>
                                        <label for="cost" class="form-label">السعر للفرد</label>
                                    </div>
                                </div>
                                <div class="col-md-2 mb-3">
                                    <br>
                                    <button type="submit" class="btn btn-primary" name="add_line" <?=$chek_disabled?>>Add Line</button>
                                </div>
                            </div>
                        </form>
                        <div class="card " style="width: 21cm;direction: ltr;">
                        <div class="card-header">
                            <div class="row">
                                <div class="col-sm-2">
                                    <button id="invoice_download_btn" class="btn form-control">PDF <i class="fa-solid fa-download"></i></button>
                                </div>
                                <div class="col-sm-2">
                                    <button class="btn form-control" onclick="printSpecificSection('section1')">طباعة الفاتورة <i class="fa-solid fa-print fa-xl"></i></button>
                                </div>
                                <div class="col-sm-2">
                                    <button class="btn form-control" onclick="printSpecificSection('section2')">طباعة الفوتشر <i class="fa-solid fa-print fa-xl"></i></button>
                                </div>
                                <div class="col-sm-3">
                                    <?php
                                    if($invoice_status == 1){
                                        ?>
                                        <a href="" class="btn btn-success disabled">فاتورة مؤكدة</a>
                                    <?php } else {
                                        ?>
                                        <a href="?do=confirm_invoice&id=<?php echo $reservation_id; ?>&id_invoice=<?php echo $id_invoice; ?>" class="btn btn-success confirm">تأكيد الفاتورة</a>
                                        <input type="hidden" name="msgcon" id="msgcon" value="هل أنت متأكد من تنفيذ هذا الأجراء">
                                        
                                    <?php }
                                    ?>
                                </div>
                                <div class="col-sm-3">
                                    <h3 class="card-title"> فاتورة رقم <?=$invoicing_no?> <i class="fa-solid fa-file-invoice-dollar"></i></h3>
                                </div>
                            </div>
                        </div>
                        <div id="sectionAll" class="" >
                            <div id="section1" class="container" >
                                <div id="invoice_wrapper">
                                    <div id="card-body" style="position: relative;padding-bottom: 95px;min-height: 29.7cm;padding: 8px;" >
                                        <div class="container">
                                        <div class="row" style="direction: ltr;">
                                            <div class="col-md-6 pt-3" style="text-align: center;width: 50%;">
                                                <img src="img/logo.png" width="120"  />
                                            </div>
                                            <div class="col-md-6 align-self-center pt-3" style="font-size: 18px; font-weight: 700; text-align: center;width: 50%;">
                                            Explore Nasa Travel
                                            </div>
                                        
                                        </div>
                                        </div>
                                        <div></div>
                                            <div class="row" style="direction: ltr;">
                                                <div class="col-md-6 " style="text-align: left;width: 50%;">
                                                    <div class="p-1 alert alert-primary" style="border: 1px solid;">
                                                            invoice NO : <?=$invoicing_no?>
                                                    </div>
                                                    <!-- <div class="alert alert-primary p-1" style="text-align: left;border: 1px solid;">
                                                        Hotel Name :  
                                                            <?=$hotel_name?>
                                                    </div> -->
                                                    <div class="alert alert-primary p-1" style="text-align: left;border: 1px solid;">
                                                            Agent :  
                                                            <?=$agent_name?>
                                                    </div>
                                                    <div class="p-1 alert alert-primary" style="text-align: left;border: 1px solid;">
                                                            Nationality: <?=$nationality_name_en?>
                                                    </div>
                                                </div>
                                                <div class="col-md-6" style="width: 50%;">
                                                    <div class="">
                                                        <div class="p-1 alert alert-primary" style="border: 1px solid;">
                                                            FILE NO : <?=$reservationDatas['file_number']?>
                                                        </div>
                                                        
                                                        <div style="border: 1px solid;">
                                                            <div class="col-md-12">
                                                            From : <?=$reservationDatas['arrival_date']?>
                                                            </div>
                                                            <div class="col-md-12" >
                                                            To : <?=$reservationDatas['departure_date']?>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                            <hr>
                                            <div style="text-align: center;">
                                                Thank you for your business
                                            </div>
                                            <table class="table border-primary mb-4" style="direction: ltr;">

                                            <!-- <table style="text-align: center;direction: ltr;"> -->
                                            <thead class="table-primary">
                                                <tr>
                                                    <td style="text-align: center;font-size: 16px;">
                                                        NO. OF PAX
                                                    </td>
                                                    <td style="text-align: center;font-size: 16px;">
                                                        DESCRIPTION
                                                    </td>
                                                    <td style="text-align: center;font-size: 16px;">
                                                        RATE P./P.
                                                    </td>
                                                    <td style="text-align: center;font-size: 16px;">
                                                        TOTAL 
                                                    </td>
                                                </tr>
                                                </thead>
                                                <tbody class="table-borderless">
                                                <?php
                                                $total_cost_invice = 0;
                                                if (is_array($InvoicingLines)) {
                                                    foreach ($InvoicingLines as $key => $value) {
                                                        $total_cost_invice += $value['total_invoice'];
                                                        if(!empty($value['no_CH'])){
                                                            $CHD = ''.$value['no_CH'].' CHD';
                                                        } else {
                                                            $CHD = '';
                                                        }
                                                        echo '<tr>';
                                                        echo '<td style="text-align: center;font-size: 16px;">';
                                                        ?>
                                                        <div>
                                                            <a href="#modal_<?php echo $value['ID'] ?>" class="btn" role="button" data-bs-toggle="modal" title="تعديل">
                                                                <?php
                                                                echo $value['no_of'].' Pax';
                                                                ?>
                                                            </a>
                                                        </div>
                                                        <div>
                                                        <!-- Modal -->
                                                            <div class="modal fade" id="modal_<?php echo $value['ID']?>" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
                                                                <div class="modal-dialog modal-xl">
                                                                    <div class="modal-content">
                                                                    <div class="modal-header">
                                                                        <h1 class="modal-title fs-5" id="staticBackdropLabel">تعديل سطر فى الفاتورة</h1>
                                                                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                                                    </div>
                                                                    <form action="?do=insert_invoices_line" method="post">
                                                                        <div class="modal-body" style="direction: rtl;">
                                                                            <input type="hidden" name="reservation_id" value="<?php echo $reservation_id; ?>" <?=$chek_disabled?> >
                                                                            <input type="hidden" name="id_invoice" value="<?php echo $id_invoice; ?>" <?=$chek_disabled?> >
                                                                            <input type="hidden" name="id_invoices_line" value="<?=$value['ID']?>" <?=$chek_disabled?> >
                                                                            <input type="hidden" name="back_invoice" value="1">
                                                                            <div class="row">
                                                                                <div class="col-md-2 mb-3">
                                                                                    <div class="form-floating">
                                                                                        <input type="text" name="number" class="form-control" placeholder="عدد الافراد" value="<?=$value['no_of']?>" required <?=$chek_disabled?> >
                                                                                        <label for="number" class="form-label">عدد الافراد</label>
                                                                                    </div>
                                                                                </div>
                                                                                <div class="col-md-2 mb-3">
                                                                                    <div class="form-floating">
                                                                                        <input type="text" name="payan" class="form-control" placeholder="البيان" value="<?=$value['disc']?>" required <?=$chek_disabled?> >
                                                                                        <label for="payan" class="form-label">البيان</label>
                                                                                    </div>
                                                                                </div>
                                                                                <div class="col-md-2 mb-3">
                                                                                    <div class="form-floating">
                                                                                        <input type="text" name="cost" class="form-control" placeholder="السعر للفرد" value="<?=$value['rate_pp']?>" required <?=$chek_disabled?> >
                                                                                        <label for="cost" class="form-label">السعر للفرد</label>
                                                                                    </div>
                                                                                </div>
                                                                                <!-- <div class="col-md-2 mb-3">
                                                                                    <div class="form-floating">
                                                                                        <input type="text" name="cost_child" class="form-control" placeholder="السعر للطفل" value="<?=$value['rate_CH']?>" <?=$chek_disabled?> >
                                                                                        <label for="cost_child" class="form-label">السعر للطفل</label>
                                                                                    </div>
                                                                                </div>
                                                                                <div class="col-md-2 mb-3">
                                                                                    <div class="form-floating">
                                                                                        <input type="text" name="num_child" class="form-control" placeholder="عدد الاطفال" value="<?=$value['no_CH']?>" <?=$chek_disabled?> >
                                                                                        <label for="num_child" class="form-label">عدد الاطفال</label>
                                                                                    </div>
                                                                                </div> -->
                                                                                <!-- <div class="col-md-2 mb-3">
                                                                                    <div class="form-floating">
                                                                                        <input type="text" name="nights" class="form-control" placeholder="عدد الليالى" value="<?=$value['nights']?>" <?=$chek_disabled?> required>
                                                                                        <label for="nights" class="form-label">عدد الليالى</label>
                                                                                    </div>
                                                                                </div> -->
                                                                                <div class="col-md-2 mb-3">
                                                                                    <br>
                                                                                    <!-- <button type="submit" class="btn btn-primary" name="add_line"<?=$chek_disabled?>>Edit Line</button> -->
                                                                                </div>
                                                                            </div>
                                                                        
                                                                    </div>
                                                                    <div class="modal-footer">
                                                                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                                                                        <button type="submit" class="btn btn-primary" name="add_line" <?=$chek_disabled?>>حفظ التعديل</button>
                                                                        <input type="hidden" name="msgcon" id="msgcon" value="هل أنت متأكد من الحذف">
                                                                        <button type="submit" class="btn btn-danger confirm" name="delete_line" <?=$chek_disabled?>>Delete</button>
                                                                    </div>
                                                                </form>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        <?php
                                                        echo '</div> </td>' ;
                                                        echo '
                                                            <td style="text-align: left;font-size: 16px;">
                                                                <div> - '.$value['disc'].'.</div>
                                                                <div></div>
                                                            </td>
                                                            <td style="text-align: center;font-size: 16px;">
                                                                <div>'.$value['rate_pp'] .' $</div>
                                                                <div> </div>
                                                            </td>
                                                            <td style="text-align: center;font-size: 16px;">
                                                                <div>'.$value['total_invoice'].' $</div>
                                                                <div> </div>
                                                            </td>
                                                        </tr>';
                                                    }
                                                }
                                                ?>
                                                </tbody>
                                                <tfoot>
                                                <tr>
                                                    <td style=" text-align: center;font-size: 16px;">
                                                        Total
                                                    </td>
                                                    <td colspan="2" style=" text-align: center;font-size: 17px;">
                                                        <?php
                                                        $formatted_total_cost_invice = number_format($total_cost_invice, 2, '.', '');
                                                        $explode_total_cost_invice = explode('.', $formatted_total_cost_invice);
                                                        ?>
                                                        <?=NumberToWords::transformNumber('en', $explode_total_cost_invice[0])?> dollars
                                                        <?php
                                                        if (isset($explode_total_cost_invice[1]) && $explode_total_cost_invice[1] > 0) {
                                                            echo ' And '.NumberToWords::transformNumber('en', $explode_total_cost_invice[1]) . ' cent';
                                                        }
                                                        ?>
                                                    </td>
                                                    <td style=" text-align: center;font-size: 17px;">
                                                        <?php echo $total_cost_invice?> $
                                                    </td>
                                                </tr>
                                                </tfoot>
                                            </table>

                                            <div class="col-md-12 mt-lg-5 mb-lg-5">
                                                <hr>
                                            </div>
                                            <div class="col-md-12 mt-lg-3" >
                                            <div style="position: relative;">
                                                <p class="m-3" style="text-align: left;direction: ltr; font-weight: 700;">
                                                    Account Manager
                                                </p>
                                                <p class="m-3" style="text-align: left;direction: ltr; font-weight: 700;">
                                                    Mohamed Sanad
                                                </p>
                                                <p class="m-3" style="text-align: left;direction: ltr; font-weight: 700;">
                                                    <img src="img/nasa.png" style="position: absolute;top: 15px;left: 20%;width: 140px;" />
                                                </p>
                                            </div>
                                            </div>
                                            <?php 
                                            if ($id_management != 1) {
                                                ?>
                                                <div class="col-md-12 mt-lg-5 mb-lg-5">
                                                    <hr>
                                                </div>
                                                <div class="m-3" style="font-size: 11px;">
                                                    <p class="m-3" style="text-align: left;direction: ltr; font-weight: 700;text-decoration: underline;">
                                                        Payment Method :-
                                                    </p>
                                                    <p class="m-0" style="text-align: left;direction: ltr; font-weight: 700;">
                                                        Arab African International Bank
                                                    </p>
                                                    <p class="m-0" style="text-align: left;direction: ltr; font-weight: 300;">
                                                        B.A USD : 1163963510010101
                                                    </p>
                                                    <p class="m-0" style="text-align: left;direction: ltr; font-weight: 300;">
                                                        IBAN USD : EG090057000801163963510010101
                                                    </p>
                                                    <p class="m-0" style="text-align: left;direction: ltr; font-weight: 300;">
                                                        B.A EUR : 1163963510010301
                                                    </p>
                                                    <p class="m-0" style="text-align: left;direction: ltr; font-weight: 300;">
                                                        IBAN EUR : EG410057000801163963510010301
                                                    </p>
                                                </div>
                                                <?php
                                            }
                                            ?>
                                            <hr>
                                        <div style=" position: absolute; bottom: 0; left: 5px; font-size: 14px;">
                                            <div class="row m-0 p-0" style="direction: ltr;">
                                                <div class="col-md-3" >
                                                    <p class=" m-0 p-0" style="text-align: right;direction: ltr; font-weight: 300;  font-size: 14px;">
                                                    0224177613
                                                    </p>
                                                </div>
                                                <div class="col-md-9 m-0 p-0" >
                                                    <p class="m-0 p-0" style="text-align: center;direction: ltr; font-weight: 300; font-size: 12px;">
                                                    explorenasatraveleg.com
                                                    </p>
                                                </div>
                                                <div class="col-md-3 m-0 p-0" >
                                                    <p class=" m-0 p-0" style="text-align: right;direction: ltr; font-weight: 300; font-size: 14px;">
                                                    01228885470
                                                    </p>
                                                </div>
                                                <div class="col-md-9 m-0 p-0" >
                                                    <p class=" m-0 p-0" style="text-align: center;direction: ltr; font-weight: 300; font-size: 12px;">
                                                    info@explorenasatraveleg.com
                                                    </p>
                                                </div>
                                                <div class="col-md-12 m-0 p-0" >
                                                    <p class="m-0 p-0" style="text-align: center;direction: ltr; font-weight: 500; font-size: 12px;">
                                                21 Qait Bay ST. Port of Omar Ibn EL Khatab, Ismailia Square, Heliopolis Cairo - EGYPT                                            </p>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <script>
                                $(function () {

                                        'use strict';

                                        /**
                                        * Generating PDF from HTML using jQuery
                                        */
                                        $(document).on('click', '#invoice_download_btn', function () {
                                            var contentWidth = $("#invoice_wrapper").width();
                                            var contentHeight = $("#invoice_wrapper").height();
                                            var topLeftMargin = 20;
                                            var pdfWidth = contentWidth + (topLeftMargin * 2);
                                            var pdfHeight = (pdfWidth * 1.5) + (topLeftMargin * 2);
                                            var canvasImageWidth = contentWidth;
                                            var canvasImageHeight = contentHeight;
                                            var totalPDFPages = Math.ceil(contentHeight / pdfHeight) - 1;

                                            html2canvas($("#invoice_wrapper")[0], {allowTaint: true}).then(function (canvas) {
                                                canvas.getContext('2d');
                                                var imgData = canvas.toDataURL("image/jpeg", 1.0);
                                                var pdf = new jsPDF('p', 'pt', [pdfWidth, pdfHeight]);
                                                pdf.addImage(imgData, 'JPG', topLeftMargin, topLeftMargin, canvasImageWidth, canvasImageHeight);
                                                for (var i = 1; i <= totalPDFPages; i++) {
                                                    pdf.addPage(pdfWidth, pdfHeight);
                                                    pdf.addImage(imgData, 'JPG', topLeftMargin, -(pdfHeight * i) + (topLeftMargin * 4), canvasImageWidth, canvasImageHeight);
                                                }
                                                pdf.save("sample-invoice.pdf");
                                            });
                                        });
                                        })
                            </script>
                            <!-- ///////////////////////////////////////////////////////////////////////////////////////////////////////////// -->
                            <hr>
                            <div id="section2" class="container" >
                                <div id="invoice_wrapper">
                                <div id="card-body" style="position: relative;padding-bottom: 95px;min-height: 29.7cm;padding: 8px;" >
                                    <div class="container">
                                        <div class="row" style="direction: ltr;">
                                            <div class="col-md-6 pt-3" style="text-align: center;width: 50%;">
                                                <img src="img/logo.png" width="120"  />
                                            </div>
                                            <div class="col-md-6 align-self-center pt-3" style="font-size: 18px; font-weight: 700; text-align: center;width: 50%;">
                                            Explore Nasa Travel
                                            </div>
                                        
                                        </div>
                                    </div>
                                <div class="" >
                                <h2 style="text-align: center;">Confirmation Hotel</h2>
                                <div></div>
                                <div class="row" style="direction: ltr;">
                                    <div class="col-md-6 " style="text-align: left;width: 50%;">
                                        <div class="alert alert-primary p-1" style="text-align: left;border: 1px solid;">
                                                Agent :  
                                                <?=$agent_name?>
                                        </div>
                                    </div>
                                    <div class="col-md-6" style="width: 50%;">
                                        <div class="">
                                            <div class="p-1 alert alert-primary" style="border: 1px solid;">
                                                FILE NO : <?=$reservationDatas['file_number']?>
                                            </div>
                                            <div style="border: 1px solid;">
                                                <div class="col-md-12">
                                                From : <?=$reservationDatas['arrival_date']?>
                                                </div>
                                                <div class="col-md-12" >
                                                To : <?=$reservationDatas['departure_date']?>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="row" style="text-align: left;direction: ltr;">
                                    <div class="col-md-12" style=" font-weight: 700; text-decoration: underline;">
                                    Please provide/arrange for the following passengers:
                                    </div>

                                    <div class="col-md-12 pt-3" >
                                        <p class="pb-0" style=" font-weight: 700; text-decoration: underline;">
                                        Name Of The Guest :-
                                    </p>
                                        <hr>
                                        MR. <?=$clients_name?>
                                        <hr>
                                    </div>
                                    <!-- <div class="col-md-12" >
                                        <h1>Hotel : <?=$id_hotel?></h1>
                                    </div> -->
                                </div>
                                <table class="table border-primary mb-4"  style="direction: ltr;">
                                    <thead class="table-primary">
                                    <tr>
                                        <td style="text-align: center;">
                                        Check In
                                        </td>
                                        <td style="text-align: center;">
                                        Check Out
                                        </td>
                                        <td style="text-align: center;">
                                            Nights
                                        </td>
                                        <td style="text-align: center;">
                                        Meals Plan   
                                        </td>
                                        <td style="text-align: center;">
                                            Rooms 
                                        </td>
                                    </tr>
                                    </thead>
                                    <?php
                                    if (is_array($getBookingFileById)) {
                                        foreach ($getBookingFileById as $key => $value) {
                                            $check_in_date = getName("hotel_bookings", "ID", $value['id_line_booking'],"check_in_date");
                                            $check_out_date = getName("hotel_bookings", "ID", $value['id_line_booking'],"check_out_date");
                                            $id_room_prices = getName("hotel_bookings", "ID", $value['id_line_booking'],"id_room_prices");
                                            $rooms_number = getName("hotel_bookings", "ID", $value['id_line_booking'],"rooms_number");
                                            $id_meal_system = getId("room_prices", "ID", $id_room_prices,"id_meal_system");
                                            $id_room_type = getId("room_prices", "ID", $id_room_prices,"id_room_type");
                                            $room_disc = getId("room_prices", "ID", $id_room_prices,"room_disc");
                                            $code_1 = getId("room_type", "ID", $id_room_type,"code_1");
                                            $short_name = getName("meal_system", "ID", $id_meal_system,"short_name");
                                            $calculatedates = $reservationsManager->calculateNightAndDayCount($check_in_date, $check_out_date);
                                            echo '
                                            <tr>
                                                <td style="text-align: center;">
                                                    <div>'.$check_in_date.'</div>
                                                </td>
                                                <td style="text-align: center;">
                                                    <div>'.$check_out_date.'</div>
                                                </td>
                                                <td style="text-align: center;">
                                                    <div>'.$calculatedates['number_of_nights'] .'</div>
                                                </td>
                                                <td style="text-align: center;">
                                                    <div>'.$short_name.' - '.$room_disc.'</div>
                                                </td>
                                                <td style="text-align: center;">
                                                    <div>'.$rooms_number.' ' . $code_1. ' </div>
                                                </td>
                                            </tr>';
                                        }
                                    }
                                    ?>
                                </table>

                                <div class="col-md-9 mt-lg-5">
                                    
                                </div>
                                <div class="col-md-12 mt-lg-5">
                                    <p>
                                    <p style="text-align: left;direction: ltr; font-weight: 700; text-decoration: underline;">
                                    Arrival & Departure Policy:-
                                    </p>
                                    </p>
                                    <p style="text-align: left;direction: ltr; font-weight: 300; ">
                                    -Check- in  : 14.00 Hrs
                                    <br>
                                    -Check- out: 13.00 Hrs
                                    </p>
                                    <p style="text-align: left;direction: ltr ; font-weight: 700;font-size: 12px; ">
                                    -Early check-in is subject to availability. For guaranteed early check-in, room to be reserved from the previous night. Rooms are held until 4pm on day of arrival unless guaranteed by a credit card or deposit.
                                    </p>
                                    <p class="m-3" style="text-align: left;direction: ltr; font-weight: 700;">
                                        Chairman
                                    </p>
                                    <p class="m-3" style="text-align: left;direction: ltr; font-weight: 700;">
                                        Mohamed Sanad
                                    </p>
                                </div>
                                <script>
                                    $(document).ready(function () {
                                        var datahtml = <?php echo json_encode($html); ?>;
                                        var htmlvo = <?php echo json_encode($htmlvo); ?>;
                                        var htmlBank = <?php echo json_encode($htmlBank); ?>;

                                        $("#downloadFormPDF").submit(function (event) {
                                            event.preventDefault();
                                            var dataString = JSON.stringify(datahtml);
                                            var htmlvoString = JSON.stringify(htmlvo);
                                            var htmlBankString = JSON.stringify(htmlBank);
                                            console.log(htmlBankString);
                                            $("#dataPDF").val(dataString);
                                            $("#datavoPDF").val(htmlvoString);
                                            $("#dataBankPDF").val(htmlBankString);
                                            $("#successMessage").show();
                                            this.submit();
                                        });
                                        $("#downloadFormPDFP").submit(function (event) {
                                            event.preventDefault();
                                            var dataString = JSON.stringify(datahtml);
                                            var htmlvoString = JSON.stringify(htmlvo);
                                            var htmlBankString = JSON.stringify(htmlBank);
                                            console.log(htmlBankString);
                                            $("#dataPDFP").val(dataString);
                                            $("#datavoPDFP").val(htmlvoString);
                                            $("#dataBankPDFP").val(htmlBankString);
                                            $("#successMessage").show();
                                            this.submit();
                                        });
                                    });
                                </script>
                            </div>
                        </div>
                            </div>
                            </div>
                        </div>
                    </div>
                </div>
                <?php
            } else {
                // رسالة خطأ أو إعادة توجيه إلى صفحة خطأ
                echo "خطأ: يجب تحديد رقم الحجز.";
                exit;
            }
        } else {
            echo '<div class="alert alert-danger">ليس لديك صلاحية الدخول الى هذا القسم</div>';
        }
    } elseif ($do === 'invoicess_vo') {
        $id_file = isset($_GET['id']) && is_numeric($_GET['id']) ? intval($_GET['id']) : 0;

        $countmanagement = 0;
        $id_management = getId("reservations","id",$id_file,"id_tourism_management");
        if ($id_management > 0) {
            $tourism_management = $con->prepare("SELECT * FROM tourism_management where ID = $id_management");
            $tourism_management->execute();
            $managements = $tourism_management->fetch(PDO::FETCH_ASSOC);
            $count = $tourism_management->rowCount();
            if ($count > 0) {
                $department_id = $managements['department_id'];
                $name_management = $managements['name_management'];
                $id_user = $_SESSION['admin'];
                if (checkadmin($id_user, $department_id, 2) == 1 ) {
                    $countmanagement += 1;
                }
            } else {
                $countmanagement = 0;
            }
        } else {
            $countmanagement = 0;
        }
        if ($countmanagement > 0 && $id_file > 0) {
            if (isset($_GET['id_invoice']) && is_numeric($_GET['id_invoice'])) {
                $id_invoice = $_GET['id_invoice'];
                $reservationsManager = new ReservationsManager($con);
                $reservation_id = $id_file;
                $reservationDatas = $reservationsManager->getReservationById($reservation_id);
                $invoicingDatas = $reservationsManager->getInvoicingById($id_invoice);
                $InvoicingLines = $reservationsManager->getInvoicingDataById($id_invoice);
                
                $getBookingFileById = $reservationsManager->getBookingFileById($reservation_id, 1);

                $sumInvoicingLine = $reservationsManager->sumInvoicingLineById($id_invoice);
                $file_number = explode("/", $reservationDatas['file_number']);
                $invoicing_no = getName("invoicing", "ID", $id_invoice,"invoicing_no");
                $invoice_status = getName("invoicing", "ID", $id_invoice,"invoice_status");
                $agent_name = getName("agents", "ID", $reservationDatas['agent_id'],"agent_name");
                // $agent_name = getName("hotels", "ID", $reservationDatas['agent_id'],"hotel_name");
                $clients_name = getName("clients", "ID", $reservationDatas['client_id'],"client_name");

                if (is_array($getBookingFileById)) {
                    foreach ($getBookingFileById as $key => $value) {
                        $id_room_prices = getName("hotel_bookings", "ID", $value['id_line_booking'],"id_room_prices");
                        $hotel_id = getId("room_prices", "ID", $id_room_prices,"hotel_id");
                        $hotel_name = getName("hotels", "ID", $hotel_id,"hotel_name");
                    }
                }
                // $id_hotel = getName("hotel_bookings", "ID", $getBookingFileById['id_line_booking'],"id_hotel");
                
                $nationality_id = getId('clients','ID',$reservationDatas['client_id'], 'id_nationality');
                $nationality_name_en = getId('nationality','ID',$nationality_id, 'nationality_name_en');

                $NumberIndividuals = $reservationsManager->getNumberIndividualsReservationById($reservation_id);

                $all_Individuals = 0;

                $sumInvoicingLine_float = (float) $sumInvoicingLine['cash'];

                // تحويل القيمة إلى نوع "int" (إذا كان ذلك ضرورياً)
                $sumInvoicingLine_int = (int) $sumInvoicingLine_float;
                $rate = 0;
                if (!empty($NumberIndividuals)) {
                    foreach ($NumberIndividuals as $value) {
                        $all_Individuals += $value['number'];
                    }
                    if ($sumInvoicingLine_int != 0) {
                        $rate = $sumInvoicingLine_int / $all_Individuals;
                    }
                } else {
                    $all_Individuals = 0;
                }
                echo "<h1 class='input-group-text text-center'><a href='?do=all_file'>عرض ملفات </a>: <a href='?do=all_file&id_management={$id_management}'>{$name_management}</a> / <a href='?do=all_data_file&id=" . $reservation_id . "'> ملف رقم : {$file_number[0]} / {$file_number[1]} </a> فاتورة رقم {$invoicing_no}</h1>";
                $head = '';
                $html = '';
                $html .= '';
                $htmlvo = '';
                $htmlvo .='';
                $htmlBank = '';

                ?>
                <div class="container mt-5" >
                    <!-- <form action="?do=insert_invoices_line" method="post">
                        <input type="hidden" name="reservation_id" value="<?php echo $reservation_id; ?>">
                        <input type="hidden" name="id_invoice" value="<?php echo $id_invoice; ?>">
                        <div class="row">
                            <div class="col-md-2 mb-3">
                                <br>
                                <button type="submit" class="btn btn-primary" name="invoce_ok">تأكيد الفاتورة</button>
                            </div>
                        </div>
                    </form> -->
                    <?php
                    if ($invoice_status == 1) {
                        $chek_disabled = 'disabled';
                    } else {
                        $chek_disabled = '';
                    }
                    ?>
                    <form action="?do=insert_invoices_line" method="post">
                        <input type="hidden" name="reservation_id" value="<?php echo $reservation_id; ?>" <?=$chek_disabled?> >
                        <input type="hidden" name="id_invoice" value="<?php echo $id_invoice; ?>" <?=$chek_disabled?> >
                        <div class="row">
                            <div class="col-md-2 mb-3">
                                <div class="form-floating">
                                    <input type="text" name="number" class="form-control" placeholder="عدد الافراد" required <?=$chek_disabled?> >
                                    <label for="number" class="form-label">عدد الافراد</label>
                                </div>
                            </div>
                            <div class="col-md-2 mb-3">
                                <div class="form-floating">
                                    <select name="id_hotels" class="form-select getsearch" required <?=$chek_disabled?>>
                                        <?php
                                        // Query to retrieve agents from the agents table
                                        $personsQuery = "SELECT * FROM hotels";
                                        $personsResult = $con->query($personsQuery);
                                        echo "<option value=''>الفندق</option>";
                                        while ($persons = $personsResult->fetch(PDO::FETCH_ASSOC)) {
                                            echo "<option value='{$persons['ID']}'>{$persons['hotel_name']}</option>";
                                        }
                                        ?>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-2 mb-3">
                                <div class="form-floating">
                                    <input type="text" name="payan" class="form-control" placeholder="البيان" required <?=$chek_disabled?> >
                                    <label for="payan" class="form-label">البيان</label>
                                </div>
                            </div>
                            <div class="col-md-2 mb-3">
                                <div class="form-floating">
                                    <input type="text" name="cost" class="form-control" placeholder="السعر للفرد" required <?=$chek_disabled?> >
                                    <label for="cost" class="form-label">السعر للفرد</label>
                                </div>
                            </div>
                            <div class="col-md-2 mb-3">
                                <div class="form-floating">
                                    <input type="text" name="cost_child" class="form-control" placeholder="السعر للطفل" <?=$chek_disabled?> >
                                    <label for="cost_child" class="form-label">السعر للطفل</label>
                                </div>
                            </div>
                            <div class="col-md-2 mb-3">
                                <div class="form-floating">
                                    <input type="text" name="num_child" class="form-control" placeholder="عدد الاطفال" <?=$chek_disabled?> >
                                    <label for="num_child" class="form-label">عدد الاطفال</label>
                                </div>
                            </div>
                            <div class="col-md-2 mb-3">
                                <div class="form-floating">
                                    <input type="text" name="nights" class="form-control" placeholder="عدد الليالى" <?=$chek_disabled?> required>
                                    <label for="nights" class="form-label">عدد الليالى</label>
                                </div>
                            </div>
                            <div class="col-md-2 mb-3">
                                <br>
                                <button type="submit" class="btn btn-primary" name="add_line"<?=$chek_disabled?>>Add Line</button>
                            </div>
                        </div>
                    </form>
                    <div class="card " style="width: 21cm;direction: ltr;">
                        <div class="card-header">
                            <div class="row">
                                <div class="col-sm-2">
                                    <button id="invoice_download_btn" class="btn form-control" style="font-size: 12px;color: white;">PDF <i class="fa-solid fa-download"></i></button>
                                </div>
                                <div class="col-sm-2">
                                    <button class="btn form-control" onclick="printSpecificSection('section1')" style="font-size: 10px;color: white;">طباعة الفاتورة <i class="fa-solid fa-print fa-xl"></i></button>
                                </div>
                                <div class="col-sm-2">
                                    <!-- <button class="btn form-control" onclick="printSpecificSectionclassName('sectionvo')" style="font-size: 10px;color: white;">طباعة الفوتشر <i class="fa-solid fa-print fa-xl"></i></button> -->
                                    <button class="btn form-control" onclick="printSpecificSection('section2')" style="font-size: 10px;color: white;">طباعة الفوتشر <i class="fa-solid fa-print fa-xl"></i></button>
                                </div>
                                <div class="col-sm-3">
                                    <?php
                                    if($invoice_status == 1){
                                        ?>
                                        <a href="" class="btn btn-success disabled">فاتورة مؤكدة</a>
                                    <?php } else {
                                        ?>
                                        <a href="?do=confirm_invoice&id=<?php echo $reservation_id; ?>&id_invoice=<?php echo $id_invoice; ?>" class="btn btn-success confirm">تأكيد الفاتورة</a>
                                        <input type="hidden" name="msgcon" id="msgcon" value="هل أنت متأكد من تنفيذ هذا الأجراء">
                                        
                                    <?php }
                                    ?>
                                </div>
                                <div class="col-sm-3">
                                    <h3 class="card-title"> فاتورة رقم <?=$invoicing_no?> <i class="fa-solid fa-file-invoice-dollar"></i></h3>
                                </div>
                            </div>
                        </div>
                        <div id="sectionAll" class="" >
                            <div id="section1" class="container" >
                                <div id="invoice_wrapper">
                                    <div id="card-body" style="position: relative;padding-bottom: 95px;min-height: 29.7cm;padding: 8px;" >
                                        <div class="container">
                                        <div class="row" style="direction: ltr;">
                                            <div class="col-md-6 pt-3" style="text-align: center;width: 50%;">
                                                <img src="img/logo.png" width="120"  />
                                            </div>
                                            <div class="col-md-6 align-self-center pt-3" style="font-size: 18px; font-weight: 700; text-align: center;width: 50%;">
                                            Explore Nasa Travel
                                            </div>
                                        
                                        </div>
                                        </div>
                                        <div></div>
                                            <div class="row" style="direction: ltr;">
                                                <div class="col-md-6 " style="text-align: left;width: 50%;">
                                                    <div class="p-1 alert alert-primary" style="border: 1px solid;">
                                                            invoice NO : <?=$invoicing_no?>
                                                    </div>
                                                    <!-- <div class="alert alert-primary p-1" style="text-align: left;border: 1px solid;">
                                                        Hotel Name :  
                                                            <?=$hotel_name?>
                                                    </div> -->
                                                    <div class="alert alert-primary p-1" style="text-align: left;border: 1px solid;">
                                                            Agent :  
                                                            <?=$agent_name?>
                                                    </div>
                                                    <div class="p-1 alert alert-primary" style="text-align: left;border: 1px solid;">
                                                            Nationality: <?=$nationality_name_en?>
                                                    </div>
                                                </div>
                                                <div class="col-md-6" style="width: 50%;">
                                                    <div class="">
                                                        <div class="p-1 alert alert-primary" style="border: 1px solid;">
                                                            FILE NO : <?=$reservationDatas['file_number']?>
                                                        </div>
                                                        <div style="border: 1px solid;">
                                                            <div class="col-md-12">
                                                            From : <?=$reservationDatas['arrival_date']?>
                                                            </div>
                                                            <div class="col-md-12" >
                                                            To : <?=$reservationDatas['departure_date']?>
                                                            </div>
                                                        </div>
                                                        <div class="mt-1 p-1 alert alert-primary" style="border: 1px solid;">
                                                        Client Name : <?=$clients_name?>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                            <hr>
                                            <div style="text-align: center;">
                                                Thank you for your business
                                            </div>
                                            <table class="table border-primary mb-4" style="direction: ltr;">

                                            <!-- <table style="text-align: center;direction: ltr;"> -->
                                            <thead class="table-primary">
                                                <tr>
                                                    <td style="text-align: center;font-size: 16px;">
                                                        NO. OF PAX
                                                    </td>
                                                    <td style="text-align: center;font-size: 16px;">
                                                        NO. OF CHD
                                                    </td>
                                                    <td style="text-align: center;font-size: 16px;">
                                                    Hotel Name
                                                    </td>
                                                    <td style="text-align: center;font-size: 16px;">
                                                        DESCRIPTION
                                                    </td>
                                                    <td style="text-align: center;font-size: 16px;">
                                                        RATE P./P.
                                                    </td>
                                                    <td style="text-align: center;font-size: 16px;">
                                                        RATE P./CHD 
                                                    </td>
                                                    <td style="text-align: center;font-size: 16px;">
                                                        Nights
                                                    </td>
                                                    <td style="text-align: center;font-size: 16px;">
                                                        TOTAL 
                                                    </td>
                                                </tr>
                                                </thead>
                                                <tbody class="table-borderless">
                                                <?php
                                                $total_cost_invice = 0;
                                                if (is_array($InvoicingLines)) {
                                                    foreach ($InvoicingLines as $key => $value) {
                                                        $hotel_id = $value['id_line_booking']; 
                                                        $hotel_name = getId('hotels','ID', $hotel_id, 'hotel_name');
                                                        $total_cost_invice += $value['total_invoice'];
                                                        if(!empty($value['no_CH'])){
                                                            $CHD = ''.$value['no_CH'].' CHD';
                                                        } else {
                                                            $CHD = '';
                                                        }
                                                        echo '<tr>';
                                                        echo '<td style="text-align: center;font-size: 16px;">';
                                                        ?>
                                                        <div>
                                                            <a href="#modal_<?php echo $value['ID'] ?>" class="btn" role="button" data-bs-toggle="modal" title="تعديل">
                                                                <?php
                                                                echo $value['no_of'].' Pax';
                                                                ?>
                                                            </a>
                                                        </div>
                                                        <div>
                                                            <!-- <style>
                                                                .select2-container{
                                                                    z-index: 9999 !important;
                                                                }
                                                            </style> -->
                                                        <!-- Modal -->
                                                            <div class="modal fade" id="modal_<?php echo $value['ID']?>" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
                                                                <div class="modal-dialog modal-xl">
                                                                    <div class="modal-content">
                                                                    <div class="modal-header">
                                                                        <h1 class="modal-title fs-5" id="staticBackdropLabel">تعديل سطر فى الفاتورة</h1>
                                                                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                                                    </div>
                                                                    <form action="?do=insert_invoices_line" method="post">
                                                                        <div class="modal-body" style="direction: rtl;">
                                                                            <input type="hidden" name="reservation_id" value="<?php echo $reservation_id; ?>" <?=$chek_disabled?> >
                                                                            <input type="hidden" name="id_invoice" value="<?php echo $id_invoice; ?>" <?=$chek_disabled?> >
                                                                            <input type="hidden" name="id_invoices_line" value="<?=$value['ID']?>" <?=$chek_disabled?> >
                                                                            <div class="row">
                                                                                <div class="col-md-2 mb-3">
                                                                                    <div class="form-floating">
                                                                                        <input type="text" name="number" class="form-control" placeholder="عدد الافراد" value="<?=$value['no_of']?>" required <?=$chek_disabled?> >
                                                                                        <label for="number" class="form-label">عدد الافراد</label>
                                                                                    </div>
                                                                                </div>
                                                                                <div class="col-md-2 mb-3">
                                                                                    <div class="form-floating">
                                                                                        <select name="id_hotels" class="form-select " required>
                                                                                            <?php
                                                                                            // Query to retrieve agents from the agents table
                                                                                            $id_hotel = $value['id_line_booking'];
                                                                                            if (empty($id_hotel)) {
                                                                                                echo "<option value=''>حدد الفندق</option>";
                                                                                            }
                                                                                            $personsQuery = "SELECT * FROM hotels where ID = $id_hotel";
                                                                                            $personsResult = $con->query($personsQuery);
                                                                                            while ($persons = $personsResult->fetch(PDO::FETCH_ASSOC)) {
                                                                                                echo "<option value='{$persons['ID']}'>{$persons['hotel_name']}</option>";
                                                                                            }
                                                                                            ?>
                                                                                            <?php
                                                                                            // Query to retrieve agents from the agents table
                                                                                            $personsQuery = "SELECT * FROM hotels where ID != $id_hotel";
                                                                                            $personsResult = $con->query($personsQuery);
                                                                                            while ($persons = $personsResult->fetch(PDO::FETCH_ASSOC)) {
                                                                                                echo "<option value='{$persons['ID']}'>{$persons['hotel_name']}</option>";
                                                                                            }
                                                                                            ?>
                                                                                        </select>
                                                                                    </div>
                                                                                </div>
                                                                                <div class="col-md-2 mb-3">
                                                                                    <div class="form-floating">
                                                                                        <input type="text" name="payan" class="form-control" placeholder="البيان" value="<?=$value['disc']?>" required <?=$chek_disabled?> >
                                                                                        <label for="payan" class="form-label">البيان</label>
                                                                                    </div>
                                                                                </div>
                                                                                <div class="col-md-2 mb-3">
                                                                                    <div class="form-floating">
                                                                                        <input type="text" name="cost" class="form-control" placeholder="السعر للفرد" value="<?=$value['rate_pp']?>" required <?=$chek_disabled?> >
                                                                                        <label for="cost" class="form-label">السعر للفرد</label>
                                                                                    </div>
                                                                                </div>
                                                                                <div class="col-md-2 mb-3">
                                                                                    <div class="form-floating">
                                                                                        <input type="text" name="cost_child" class="form-control" placeholder="السعر للطفل" value="<?=$value['rate_CH']?>" <?=$chek_disabled?> >
                                                                                        <label for="cost_child" class="form-label">السعر للطفل</label>
                                                                                    </div>
                                                                                </div>
                                                                                <div class="col-md-2 mb-3">
                                                                                    <div class="form-floating">
                                                                                        <input type="text" name="num_child" class="form-control" placeholder="عدد الاطفال" value="<?=$value['no_CH']?>" <?=$chek_disabled?> >
                                                                                        <label for="num_child" class="form-label">عدد الاطفال</label>
                                                                                    </div>
                                                                                </div>
                                                                                <div class="col-md-2 mb-3">
                                                                                    <div class="form-floating">
                                                                                        <input type="text" name="nights" class="form-control" placeholder="عدد الليالى" value="<?=$value['nights']?>" <?=$chek_disabled?> required>
                                                                                        <label for="nights" class="form-label">عدد الليالى</label>
                                                                                    </div>
                                                                                </div>
                                                                                <div class="col-md-2 mb-3">
                                                                                    <br>
                                                                                    <!-- <button type="submit" class="btn btn-primary" name="add_line"<?=$chek_disabled?>>Edit Line</button> -->
                                                                                </div>
                                                                            </div>
                                                                        
                                                                    </div>
                                                                    <div class="modal-footer">
                                                                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                                                                        <button type="submit" class="btn btn-primary" name="add_line" <?=$chek_disabled?>>حفظ التعديل</button>
                                                                        <input type="hidden" name="msgcon" id="msgcon" value="هل أنت متأكد من الحذف">
                                                                        <button type="submit" class="btn btn-danger confirm" name="delete_line" <?=$chek_disabled?>>Delete</button>
                                                                    </div>
                                                                </form>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        <?php
                                                        echo '</div> </td>' ;
                                                        echo '
                                                            <td style="text-align: left;font-size: 16px;">
                                                                <div>'.$CHD.'.</div>
                                                                <div></div>
                                                            </td>
                                                            <td style="text-align: left;font-size: 16px;">
                                                                <div>'.$hotel_name.'.</div>
                                                                <div></div>
                                                            </td>
                                                            <td style="text-align: left;font-size: 16px;">
                                                                <div> - '.$value['disc'].'.</div>
                                                                <div></div>
                                                            </td>
                                                            <td style="text-align: center;font-size: 16px;">
                                                                <div>'.$value['rate_pp'] .' $</div>
                                                                <div> </div>
                                                            </td>
                                                            <td style="text-align: center;font-size: 16px;">
                                                                <div>'.$value['rate_CH'] .' $</div>
                                                                <div> </div>
                                                            </td>
                                                            <td style="text-align: center;font-size: 16px;">
                                                                <div>'.$value['nights'] .'</div>
                                                                <div> </div>
                                                            </td>
                                                            <td style="text-align: center;font-size: 16px;">
                                                                <div>'.$value['total_invoice'].' $</div>
                                                                <div> </div>
                                                            </td>
                                                        </tr>';
                                                    }
                                                }
                                                ?>
                                                </tbody>
                                                <tfoot>
                                                <tr>
                                                    <td style=" text-align: center;font-size: 16px;">
                                                        Total
                                                    </td>
                                                    <td colspan="6" style=" text-align: center;font-size: 17px;">
                                                        <?php
                                                        $formatted_total_cost_invice = number_format($total_cost_invice, 2, '.', '');
                                                        $explode_total_cost_invice = explode('.', $formatted_total_cost_invice);
                                                        ?>
                                                        <?=NumberToWords::transformNumber('en', $explode_total_cost_invice[0])?> dollars
                                                        <?php
                                                        if (isset($explode_total_cost_invice[1]) && $explode_total_cost_invice[1] > 0) {
                                                            echo ' And '.NumberToWords::transformNumber('en', $explode_total_cost_invice[1]) . ' cent';
                                                        }
                                                        ?>
                                                    </td>
                                                    <td style=" text-align: center;font-size: 17px;">
                                                        <?php echo $total_cost_invice?> $
                                                    </td>
                                                </tr>
                                                </tfoot>
                                            </table>

                                            <div class="col-md-12 mt-lg-5 mb-lg-5">
                                                <hr>
                                            </div>
                                            <div class="col-md-12 mt-lg-3" >
                                            <div style="position: relative;">
                                                <p class="m-3" style="text-align: left;direction: ltr; font-weight: 700;">
                                                    Account Manager
                                                </p>
                                                <p class="m-3" style="text-align: left;direction: ltr; font-weight: 700;">
                                                    Mohamed Sanad
                                                </p>
                                                <p class="m-3" style="text-align: left;direction: ltr; font-weight: 700;">
                                                    <img src="img/nasa.png" style="position: absolute;top: 15px;left: 20%;width: 140px;" />
                                                </p>
                                            </div>
                                            </div>
                                            <?php 
                                            if ($id_management != 1) {
                                                ?>
                                                <div class="col-md-12 mt-lg-5 mb-lg-5">
                                                    <hr>
                                                </div>
                                                <div class="m-3" style="font-size: 11px;">
                                                    <p class="m-3" style="text-align: left;direction: ltr; font-weight: 700;text-decoration: underline;">
                                                        Payment Method :-
                                                    </p>
                                                    <p class="m-0" style="text-align: left;direction: ltr; font-weight: 700;">
                                                        Arab African International Bank
                                                    </p>
                                                    <p class="m-0" style="text-align: left;direction: ltr; font-weight: 300;">
                                                        B.A USD : 1163963510010101
                                                    </p>
                                                    <p class="m-0" style="text-align: left;direction: ltr; font-weight: 300;">
                                                        IBAN USD : EG090057000801163963510010101
                                                    </p>
                                                    <p class="m-0" style="text-align: left;direction: ltr; font-weight: 300;">
                                                        B.A EUR : 1163963510010301
                                                    </p>
                                                    <p class="m-0" style="text-align: left;direction: ltr; font-weight: 300;">
                                                        IBAN EUR : EG410057000801163963510010301
                                                    </p>
                                                </div>
                                                <?php
                                            }
                                            ?>
                                            <hr>
                                        <div style=" position: absolute; bottom: 0; left: 5px; font-size: 14px;">
                                            <div class="row m-0 p-0" style="direction: ltr;">
                                                <div class="col-md-3" >
                                                    <p class=" m-0 p-0" style="text-align: right;direction: ltr; font-weight: 300;  font-size: 14px;">
                                                    0224177613
                                                    </p>
                                                </div>
                                                <div class="col-md-9 m-0 p-0" >
                                                    <p class="m-0 p-0" style="text-align: center;direction: ltr; font-weight: 300; font-size: 12px;">
                                                    explorenasatraveleg.com
                                                    </p>
                                                </div>
                                                <div class="col-md-3 m-0 p-0" >
                                                    <p class=" m-0 p-0" style="text-align: right;direction: ltr; font-weight: 300; font-size: 14px;">
                                                    01228885470
                                                    </p>
                                                </div>
                                                <div class="col-md-9 m-0 p-0" >
                                                    <p class=" m-0 p-0" style="text-align: center;direction: ltr; font-weight: 300; font-size: 12px;">
                                                    info@explorenasatraveleg.com
                                                    </p>
                                                </div>
                                                <div class="col-md-12 m-0 p-0" >
                                                    <p class="m-0 p-0" style="text-align: center;direction: ltr; font-weight: 500; font-size: 12px;">
                                                21 Qait Bay ST. Port of Omar Ibn EL Khatab, Ismailia Square, Heliopolis Cairo - EGYPT                                            </p>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <script>
                                $(function () {
                                        'use strict';
                                        /**
                                        * Generating PDF from HTML using jQuery
                                        */
                                        $(document).on('click', '#invoice_download_btn', function () {
                                            var contentWidth = $("#invoice_wrapper").width();
                                            var contentHeight = $("#invoice_wrapper").height();
                                            var topLeftMargin = 20;
                                            var pdfWidth = contentWidth + (topLeftMargin * 2);
                                            var pdfHeight = (pdfWidth * 1.5) + (topLeftMargin * 2);
                                            var canvasImageWidth = contentWidth;
                                            var canvasImageHeight = contentHeight;
                                            var totalPDFPages = Math.ceil(contentHeight / pdfHeight) - 1;

                                            html2canvas($("#invoice_wrapper")[0], {allowTaint: true}).then(function (canvas) {
                                                canvas.getContext('2d');
                                                var imgData = canvas.toDataURL("image/jpeg", 1.0);
                                                var pdf = new jsPDF('p', 'pt', [pdfWidth, pdfHeight]);
                                                pdf.addImage(imgData, 'JPG', topLeftMargin, topLeftMargin, canvasImageWidth, canvasImageHeight);
                                                for (var i = 1; i <= totalPDFPages; i++) {
                                                    pdf.addPage(pdfWidth, pdfHeight);
                                                    pdf.addImage(imgData, 'JPG', topLeftMargin, -(pdfHeight * i) + (topLeftMargin * 4), canvasImageWidth, canvasImageHeight);
                                                }
                                                pdf.save("sample-invoice.pdf");
                                            });
                                        });
                                        })
                            </script>
                            <!-- ///////////////////////////////////////////////////////////////////////////////////////////////////////////// -->
                            <hr>
                            <div id="section2" class="sectionvo container" >
                                <!-- ///////////////////////////////////////////////////////////////////////////////////////////////////////////// -->
                                <?php
                                // استعلام SQL لاسترداد بيانات الحجز مع تجميعها حسب فندق الحجز
                                $sql = "SELECT id_hotel, GROUP_CONCAT(ID) AS booking_ids FROM hotel_bookings WHERE id_reservation = $reservation_id GROUP BY id_hotel";
                                $stmt = $con->query($sql);
                                $bookingsByHotel = $stmt->fetchAll(PDO::FETCH_ASSOC);
                                foreach ($bookingsByHotel as $booking) {
                                    $hotelId = $booking['id_hotel'];
                                    $bookingIds = explode(',', $booking['booking_ids']);
                                    $hotel_name = getId("hotels", "ID", $hotelId,"hotel_name");
                                    ?>
                                <div id="invoice_wrapper">
                                    <div id="card-body" style="position: relative;padding-bottom: 95px;min-height: 29.7cm;padding: 8px;" >
                                        <div class="container">
                                            <div class="row" style="direction: ltr;">
                                                <div class="col-md-6 pt-3" style="text-align: center;width: 50%;">
                                                    <img src="img/logo.png" width="120"  />
                                                </div>
                                                <div class="col-md-6 align-self-center pt-3" style="font-size: 18px; font-weight: 700; text-align: center;width: 50%;">
                                                Explore Nasa Travel
                                                </div>
                                            
                                            </div>
                                        </div>
                                        <div class="" >
                                        <h2 style="text-align: center;">Confirmation Hotel</h2>
                                        <div></div>
                                        <div class="row" style="direction: ltr;">
                                            <div class="col-md-6 " style="text-align: left;width: 50%;">
                                                <div class="alert alert-primary p-1" style="text-align: left;border: 1px solid;">
                                                        Agent :  
                                                        <?=$agent_name?>
                                                </div>
                                                <div class="alert alert-primary p-1" style="text-align: left;border: 1px solid;">
                                                        Hotel :  
                                                        <?=$hotel_name?>
                                                </div>
                                            </div>
                                            <div class="col-md-6" style="width: 50%;">
                                                <div class="">
                                                    <div class="p-1 alert alert-primary" style="border: 1px solid;">
                                                        FILE NO : <?=$reservationDatas['file_number']?>
                                                    </div>
                                                    <div style="border: 1px solid;">
                                                        <div class="col-md-12">
                                                        From : <?=$reservationDatas['arrival_date']?>
                                                        </div>
                                                        <div class="col-md-12" >
                                                        To : <?=$reservationDatas['departure_date']?>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="row" style="text-align: left;direction: ltr;">
                                            <div class="col-md-12" style=" font-weight: 700; text-decoration: underline;">
                                            Please provide/arrange for the following passengers:
                                            </div>

                                            <div class="col-md-12 pt-3" >
                                                <p class="pb-0" style=" font-weight: 700; text-decoration: underline;">
                                                Name Of The Guest :-
                                            </p>
                                                <hr>
                                                MR. <?=$clients_name?>
                                                <hr>
                                            </div>
                                            <!-- <div class="col-md-12" >
                                                <h1>Hotel : <?=$id_hotel?></h1>
                                            </div> -->
                                        </div>
                                        <table class="table border-primary mb-4"  style="direction: ltr;">
                                            <thead class="table-primary">
                                            <tr>
                                                <td style="text-align: center;">
                                                Check In
                                                </td>
                                                <td style="text-align: center;">
                                                Check Out
                                                </td>
                                                <td style="text-align: center;">
                                                    Nights
                                                </td>
                                                <td style="text-align: center;">
                                                Meals Plan   
                                                </td>
                                                <td style="text-align: center;">
                                                    Rooms 
                                                </td>
                                            </tr>
                                            </thead>
                                            <?php
                                                foreach ($bookingIds as $key => $value) {

                                                    $sql = "SELECT * FROM hotel_bookings WHERE ID = :booking_id";
                                                    $stmt = $conn->prepare($sql);
                                                    $stmt->bindParam(':booking_id', $value);
                                                    $stmt->execute();
                                                    $bookingData = $stmt->fetch(PDO::FETCH_ASSOC);
                                                    
                                                    $check_in_date = $bookingData['check_in_date'];
                                                    $check_out_date = $bookingData['check_out_date'];
                                                    $id_room_prices = $bookingData['id_room_prices'];
                                                    $rooms_number = $bookingData['rooms_number'];
                                                    $id_hotel = $bookingData['id_hotel'];

                                                    $id_meal_system = getId("room_prices", "ID", $id_room_prices,"id_meal_system");
                                                    $id_room_type = getId("room_prices", "ID", $id_room_prices,"id_room_type");
                                                    $room_disc = getId("room_prices", "ID", $id_room_prices,"room_disc");
                                                    $code_1 = getId("room_type", "ID", $id_room_type,"code_1");
                                                    $short_name = getName("meal_system", "ID", $id_meal_system,"short_name");

                                                    /* $check_in_date = getName("hotel_bookings", "ID", $value['id_line_booking'],"check_in_date");
                                                    $check_out_date = getName("hotel_bookings", "ID", $value['id_line_booking'],"check_out_date");
                                                    $id_room_prices = getName("hotel_bookings", "ID", $value['id_line_booking'],"id_room_prices");
                                                    $rooms_number = getName("hotel_bookings", "ID", $value['id_line_booking'],"rooms_number");
                                                    $id_meal_system = getId("room_prices", "ID", $id_room_prices,"id_meal_system");
                                                    $id_room_type = getId("room_prices", "ID", $id_room_prices,"id_room_type");
                                                    $room_disc = getId("room_prices", "ID", $id_room_prices,"room_disc");
                                                    $code_1 = getId("room_type", "ID", $id_room_type,"code_1");
                                                    $short_name = getName("meal_system", "ID", $id_meal_system,"short_name"); */

                                                    $calculatedates = $reservationsManager->calculateNightAndDayCount($check_in_date, $check_out_date);
                                                    echo '
                                                    <tr>
                                                        <td style="text-align: center;">
                                                            <div>'.$check_in_date.'</div>
                                                        </td>
                                                        <td style="text-align: center;">
                                                            <div>'.$check_out_date.'</div>
                                                        </td>
                                                        <td style="text-align: center;">
                                                            <div>'.$calculatedates['number_of_nights'] .'</div>
                                                        </td>
                                                        <td style="text-align: center;">
                                                            <div>'.$short_name.' - '.$room_disc.'</div>
                                                        </td>
                                                        <td style="text-align: center;">
                                                            <div>'.$rooms_number.' ' . $code_1. ' </div>
                                                        </td>
                                                    </tr>';
                                                }
                                                
                                            ?>
                                        </table>

                                        <div class="col-md-9 mt-lg-5">
                                        
                                        </div>
                                        <div class="col-md-12 mt-lg-5">
                                        <p>
                                        <p style="text-align: left;direction: ltr; font-weight: 700; text-decoration: underline;">
                                        Arrival & Departure Policy:-
                                        </p>
                                        </p>
                                        <p style="text-align: left;direction: ltr; font-weight: 300; ">
                                        -Check- in  : 14.00 Hrs
                                        <br>
                                        -Check- out: 13.00 Hrs
                                        </p>
                                        <p style="text-align: left;direction: ltr ; font-weight: 700;font-size: 12px; ">
                                        -Early check-in is subject to availability. For guaranteed early check-in, room to be reserved from the previous night. Rooms are held until 4pm on day of arrival unless guaranteed by a credit card or deposit.
                                        </p>
                                        <p class="m-3" style="text-align: left;direction: ltr; font-weight: 700;">
                                            Chairman
                                        </p>
                                        <p class="m-3" style="text-align: left;direction: ltr; font-weight: 700;">
                                            Mohamed Sanad
                                        </p>
                                        </div>
                                        <script>
                                            $(document).ready(function () {
                                                var datahtml = <?php echo json_encode($html); ?>;
                                                var htmlvo = <?php echo json_encode($htmlvo); ?>;
                                                var htmlBank = <?php echo json_encode($htmlBank); ?>;

                                                $("#downloadFormPDF").submit(function (event) {
                                                    event.preventDefault();
                                                    var dataString = JSON.stringify(datahtml);
                                                    var htmlvoString = JSON.stringify(htmlvo);
                                                    var htmlBankString = JSON.stringify(htmlBank);
                                                    console.log(htmlBankString);
                                                    $("#dataPDF").val(dataString);
                                                    $("#datavoPDF").val(htmlvoString);
                                                    $("#dataBankPDF").val(htmlBankString);
                                                    $("#successMessage").show();
                                                    this.submit();
                                                });
                                                $("#downloadFormPDFP").submit(function (event) {
                                                    event.preventDefault();
                                                    var dataString = JSON.stringify(datahtml);
                                                    var htmlvoString = JSON.stringify(htmlvo);
                                                    var htmlBankString = JSON.stringify(htmlBank);
                                                    console.log(htmlBankString);
                                                    $("#dataPDFP").val(dataString);
                                                    $("#datavoPDFP").val(htmlvoString);
                                                    $("#dataBankPDFP").val(htmlBankString);
                                                    $("#successMessage").show();
                                                    this.submit();
                                                });
                                            });
                                        </script>
                                        </div>
                                    </div>
                                </div>
                                <?php
                                }
                                ?>
                                <!-- ///////////////////////////////////////////////////////////////////////////////////////////////////////////// -->
                            </div>
                        </div>
                    </div>
                <?php
            } else {
                // رسالة خطأ أو إعادة توجيه إلى صفحة خطأ
                echo "خطأ: يجب تحديد رقم الحجز.";
                exit;
            }
        } else {
            echo '<div class="alert alert-danger">ليس لديك صلاحية الدخول الى هذا القسم</div>';
        }
    } elseif ($do === 'exchange_request') {
        $id_file = isset($_GET['id']) && is_numeric($_GET['id']) ? intval($_GET['id']) : 0;
        $countmanagement = 0;
        $id_management = getId("reservations","id",$id_file,"id_tourism_management");
        if ($id_management > 0) {
            $tourism_management = $con->prepare("SELECT * FROM tourism_management where ID = $id_management");
            $tourism_management->execute();
            $managements = $tourism_management->fetch(PDO::FETCH_ASSOC);
            $count = $tourism_management->rowCount();
            if ($count > 0) {
                $department_id = $managements['department_id'];
                $name_management = $managements['name_management'];
                $id_user = $_SESSION['admin'];
                if (checkadmin($id_user, $department_id, 2) == 1 ) {
                    $countmanagement += 1;
                }
            } else {
                $countmanagement = 0;
            }
        } else {
            $countmanagement = 0;
        }
        
        if ($countmanagement > 0 && $id_file > 0) {
            if (isset($_GET['id_invoice']) && is_numeric($_GET['id_invoice'])) {
                $id_invoice = $_GET['id_invoice'];
                $reservationsManager = new ReservationsManager($con);
                $reservation_id = $id_file;
                $reservationDatas = $reservationsManager->getReservationById($reservation_id);
                $invoicingDatas = $reservationsManager->getInvoicingById($id_invoice);
                $InvoicingLines = $reservationsManager->getInvoicingLinesById($id_invoice, 1);
                // var_dump($InvoicingLines);

                $sumInvoicingLine = $reservationsManager->sumInvoicingLineById($id_invoice, 1);

                $file_number = explode("/", $reservationDatas['file_number']);
                $invoicing_no = getName("invoicing", "ID", $id_invoice,"invoicing_no");
                $agent_name = getName("agents", "ID", $reservationDatas['agent_id'],"agent_name");
                $nationality_id = getId('clients','ID',$reservationDatas['client_id'], 'id_nationality');
                $nationality_name_en = getId('nationality','ID',$nationality_id, 'nationality_name_en');

                $NumberIndividuals = $reservationsManager->getNumberIndividualsReservationById($reservation_id);

                $all_Individuals = 0;
                $rate = 0;

                $sumInvoicingLine_float = (float) $sumInvoicingLine['cash'];

                // تحويل القيمة إلى نوع "int" (إذا كان ذلك ضرورياً)
                $sumInvoicingLine_int = (int) $sumInvoicingLine_float;
                if (!empty($NumberIndividuals)) {
                    foreach ($NumberIndividuals as $value) {
                        $all_Individuals += $value['number'];
                    }
                    if ($sumInvoicingLine_int != 0) {
                        $rate = $sumInvoicingLine_int / $all_Individuals;
                    }
                } else {
                    $all_Individuals = 0;
                }
                echo "<h1 class='input-group-text text-center'><a href='?do=all_file'>عرض ملفات </a>: <a href='?do=all_file&id_management={$id_management}'>{$name_management}</a> / <a href='?do=all_data_file&id=" . $reservation_id . "'> ملف رقم : {$file_number[0]} / {$file_number[1]} </a>فوتشر إتفاقية إقامة {$invoicing_no}</h1>";

                $head = '<table>
                <tr>
                    <td>
                        <img src="img/logo.png" width="100"  />
                    </td>
                    <td>
                    إكسبلور ناسا ترافل
                    </td>
                </tr>
            </table>
            <div></div>';
            $htmlvo = '<div class="row" style="position: relative;width: 21cm;padding-bottom: 95px;" >
                
                <table class="table table-bordered" style="border: 1px solid #000;text-align: left;width: 250px;">
                <tr>
                    <td>
                        invoice NO. '.$invoicing_no.'
                    </td>
                </tr>
                     <tr>
                        <td>
                        FILE NO : '.$reservationDatas['file_number'].'
                        </td>
                     </tr>
                </table>

                <div></div>

                <table style="border: 1px solid #000; text-align: left;width: 250px;">
                <tr>
                    <td style="border: 1px solid #000; text-align: left;">
                        TO :  
                    </td>
                    <td colspan="4" style="border: 1px solid #000; text-align: left;">
                        '.$agent_name.'
                    </td>
                    </tr>
                </table>

                <br>
                <hr>
                <table>
                    <tr>
                        <td style="border: 1px solid #000;border-bottom: none;text-align: center;">
                            From
                        </td>
                        <td style="border: 1px solid #000;border-bottom: none;text-align: center;">
                            To
                        </td>
                        <td style="border: 1px solid #000;border-bottom: none;text-align: center;">
                            Nights
                        </td>
                        <td style="border: 1px solid #000;border-bottom: none;text-align: center;">
                            meal_system  
                        </td>
                        <td style="border: 1px solid #000;border-bottom: none;text-align: center;">
                            Rooms 
                        </td>
                    </tr>';
                    foreach ($InvoicingLines as $key => $value) {
                        $check_in_date = getName("hotel_bookings", "ID", $value['id_line_booking'],"check_in_date");
                        $check_out_date = getName("hotel_bookings", "ID", $value['id_line_booking'],"check_out_date");
                        $id_room_prices = getName("hotel_bookings", "ID", $value['id_line_booking'],"id_room_prices");
                        $rooms_number = getName("hotel_bookings", "ID", $value['id_line_booking'],"rooms_number");
                        $id_meal_system = getId("room_prices", "ID", $id_room_prices,"id_meal_system");
                        $id_room_type = getId("room_prices", "ID", $id_room_prices,"id_room_type");
                        $code_1 = getId("room_type", "ID", $id_room_type,"code_1");
                        $id_room_prices = getName("meal_system", "ID", $id_meal_system,"short_name");
                        $calculatedates = $reservationsManager->calculateNightAndDayCount($check_in_date, $check_out_date);
                        $htmlvo .='
                        <tr>
                            <td style="border: 1px solid #000;border-bottom: none;text-align: center;">
                                <div>'.$check_in_date.'</div>
                            </td>
                            <td style="border: 1px solid #000;border-bottom: none;text-align: left;">
                                <div>'.$check_out_date.'</div>
                            </td>
                            <td style="border: 1px solid #000;border-bottom: none;text-align: center;">
                                <div>'.$calculatedates['number_of_nights'] .'</div>
                            </td>
                            <td style="border: 1px solid #000;border-bottom: none;text-align: center;">
                                <div>'.$id_room_prices.'</div>
                            </td>
                            <td style="border: 1px solid #000;border-bottom: none;text-align: center;">
                                <div>'.$rooms_number.' ' . $code_1. ' </div>
                            </td>
                        </tr>';
                    }
                    $htmlvo .='
                        </table>

                        <div class="col-md-9 mt-lg-5">
                            
                        </div>
                        <div class="col-md-3 mt-lg-5">
                            Account Manager
                        </div>';
            $htmlBank = <<<EOD
            Account Manager
        EOD;
        //////////////////////////////////////////////////////////////////////////////////////////////////////////

                ?>
                <table>
                    <tr>
                        <td rowspan="" table-bordered='0'>
                        </td>
                    </tr>
                </table>
                <div class="container mt-5">
                    <div class="card  table-responsive" style="width: 21cm;">
                        <div class="card-header">
                            <div class="row">
                                <div class="col-sm-9">
                                <h3 class="card-title"><i class="fa-solid fa-file-invoice-dollar"></i> فوتشر إقامة </h3>
                                </div>
                                <div class="col-sm-1">
                                    <form class="form-inline" id="downloadFormPDF" action="generate_file.php" method="post" target="_blank">
                                        <input type="hidden" name="data" id="dataPDF">
                                        <input type="hidden" name="dataBankPDFP" id="dataBankPDF">
                                        <input type="hidden" name="downloadType" value="invoicepdf">
                                        <input type="hidden" name="namereport" value="invoice NO. <?=$invoicing_no?>">
                                        <button type="submit" class="btn form-control generate">PDF <i class="fa-solid fa-download"></i></button>
                                    </form>
                                </div>
                                <div class="col-sm-1">
                                    <form class="form-inline" id="downloadFormPDFP" action="generate_file.php" method="post" target="_blank">
                                        <input type="hidden" name="data" id="dataPDFP">
                                        <input type="hidden" name="dataBankPDFP" id="dataBankPDFP">
                                        <input type="hidden" name="downloadType" value="invoicepdfP">
                                        <input type="hidden" name="namereport" value="invoice NO. <?=$invoicing_no?>">
                                        <button type="submit" class="btn form-control generate">Print <i class="fa-solid fa-print fa-xl"></i></button>
                                    </form>
                                </div>
                            </div>
                        </div>
                        <?=$head?>
                        <?=$html?>
                        <?=$htmlBank?>
                        <script>
                        $(document).ready(function () {
                            var datahtml = <?php echo json_encode($html); ?>;
                            var htmlBank = <?php echo json_encode($htmlBank); ?>;

                            $("#downloadFormPDF").submit(function (event) {
                                event.preventDefault();
                                var dataString = JSON.stringify(datahtml);
                                var htmlBankString = JSON.stringify(htmlBank);
                                console.log(htmlBankString);
                                $("#dataPDF").val(dataString);
                                $("#dataBankPDF").val(htmlBankString);
                                $("#successMessage").show();
                                this.submit();
                            });
                            $("#downloadFormPDFP").submit(function (event) {
                                event.preventDefault();
                                var dataString = JSON.stringify(datahtml);
                                var htmlBankString = JSON.stringify(htmlBank);
                                console.log(htmlBankString);
                                $("#dataPDFP").val(dataString);
                                $("#dataBankPDFP").val(htmlBankString);
                                $("#successMessage").show();
                                this.submit();
                            });
                        });
                    </script>
                    </div>
                </div>
                <?php
            } else {
                // رسالة خطأ أو إعادة توجيه إلى صفحة خطأ
                echo "خطأ: يجب تحديد رقم الحجز.";
                exit;
            }
        } else {
            echo '<div class="alert alert-danger">ليس لديك صلاحية الدخول الى هذا القسم</div>';
        }
    } elseif ($do === 'add_invoices') {
        // عرض نموذج إضافة حجز جديد
        // include 'add_reservation_form.php';
        $id_file = isset($_GET['id']) && is_numeric($_GET['id']) ? intval($_GET['id']) : 0;
        $countmanagement = 0;
        $id_management = getId("reservations","id",$id_file,"id_tourism_management");
        if ($id_management > 0) {
            $tourism_management = $con->prepare("SELECT * FROM tourism_management where ID = $id_management");
            $tourism_management->execute();
            $managements = $tourism_management->fetch(PDO::FETCH_ASSOC);
            $count = $tourism_management->rowCount();
            if ($count > 0) {
                $department_id = $managements['department_id'];
                $name_management = $managements['name_management'];
                $id_user = $_SESSION['admin'];
                if (checkadmin($id_user, $department_id, 2) == 1 ) {
                    $countmanagement += 1;
                }
            } else {
                $countmanagement = 0;
            }
        } else {
            $countmanagement = 0;
        }
        
        if ($countmanagement > 0) {
            if (isset($id_file) ) {
                $reservation_id = $_GET['id'];
                ?>
                <div class="container mt-5">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">إنشاء فاتورة <i class="fa-solid fa-folder-plus fa-sm"></i></h3>
                        </div>
                        <div class="card-body">
                            <form action="?do=insert_invoices" method="post">
                                <div class="row">
                                <div class="form-group">
                <label for="id_invoice_type">نوع الفاتورة:</label>
                <input type="text" id="id_invoice_type" name="id_invoice_type" required>
            </div>

            <div class="form-group">
                <label for="id_yomya">معرِّف اليومية:</label>
                <input type="number" id="id_yomya" name="id_yomya">
            </div>

            <div class="form-group">
                <label for="invoicing_no">رقم الفاتورة:</label>
                <input type="text" id="invoicing_no" name="invoicing_no" required>
            </div>

            <div class="form-group">
                <label for="id_reservation">معرِّف الحجز:</label>
                <input type="number" id="id_reservation" name="id_reservation">
            </div>

            <div class="form-group">
                <label for="file_no">رقم الملف:</label>
                <input type="text" id="file_no" name="file_no">
            </div>

            <div class="form-group">
                <label for="id_agent">معرِّف الوكيل:</label>
                <input type="number" id="id_agent" name="id_agent">
            </div>

            <div class="form-group">
                <label for="arrival_date">تاريخ الوصول:</label>
                <input type="date" id="arrival_date" name="arrival_date">
            </div>

            <div class="form-group">
                <label for="departure_date">تاريخ المغادرة:</label>
                <input type="date" id="departure_date" name="departure_date">
            </div>

            <div class="form-group">
                <label for="id_nationality">جنسية العميل:</label>
                <input type="number" id="id_nationality" name="id_nationality">
            </div>

            <div class="form-group">
                <label for="account_manager">مدير الحساب:</label>
                <input type="text" id="account_manager" name="account_manager">
            </div>

            <div class="form-group">
                <label for="invoice_status">حالة الفاتورة:</label>
                <input type="number" id="invoice_status" name="invoice_status">
            </div>

            <div class="form-group">
                <label for="id_receipt_voucher">معرِّف إيصال السداد:</label>
                <input type="number" id="id_receipt_voucher" name="id_receipt_voucher">
            </div>

            <div class="form-group">
                <label for="user_id_insert">معرِّف المستخدم الذي أدخل البيانات:</label>
                <input type="number" id="user_id_insert" name="user_id_insert">
            </div>

            <div class="form-group">
                <label for="user_id_update">معرِّف المستخدم الذي حدث البيانات:</label>
                <input type="number" id="user_id_update" name="user_id_update">
            </div>

            <button type="submit">إضافة الفاتورة</button>

                                </div>
                            </form>
                        </div>
                    </div>
                </div>
                <?php
            } else {
                // رسالة خطأ أو إعادة توجيه إلى صفحة خطأ
                echo "خطأ: يجب تحديد رقم الحجز.";
                exit;
            }
        } else {
            echo '<div class="alert alert-danger">ليس لديك صلاحية الدخول الى هذا القسم</div>';
        }
    } elseif ($do === 'insert_invoices') {
        if ($_SERVER["REQUEST_METHOD"] === 'POST' && isset($_POST['add_invoices'])) {
            $reservationsManager = new ReservationsManager($con);
            // استلام البيانات من الفورم
            $tourism_management = $_POST['tourism_management'];
            $cost_centers_id = $_POST['cost_centers_id'];
            $agent_id = $_POST['agent_id'];
            $client_id = ($_POST['client_id'] === 'new') ? null : $_POST['client_id'];
            $new_client_name = ($_POST['client_id'] === 'new') ? $_POST['client_name'] : null;
            $nationality_id = ($_POST['client_id'] === 'new') ? $_POST['nationality_id'] : null;
            $arrival_date = $_POST['arrival_date'];
            $departure_date = $_POST['departure_date'];
            $remarks = $_POST['remarks'];
            // يمكنك إجراء عمليات التحقق هنا
            $formErrors = array();
            if (empty($tourism_management)) {
                $formErrors[] = 'برجاء إختر إدارة السياحة<strong>فارغ</strong>';
            }
            if (empty($cost_centers_id)) {
                $formErrors[] = 'لا يجب أن يكون مركز التكلفة  <strong>فارغ</strong>';
            }
            if (empty($agent_id)) {
                $formErrors[] = 'لا يجب أن يكون إسم الوكيل  <strong>فارغ</strong>';
            }
            if (empty($arrival_date)) {
                $formErrors[] = 'لا يجب أن يكون تاريخ الوصول <strong>فارغ</strong>';
            }
            if (empty($departure_date)) {
                $formErrors[] = 'لا يجب أن يكون تاريخ المغادرة <strong>فارغ</strong>';
            }
            if ($_POST['client_id'] === 'new') {
                if (empty($new_client_name)) {
                    $formErrors[] = 'لا يجب أن يكون اسم العميل <strong>فارغ</strong>';
                }
                if (empty($nationality_id)) {
                    $formErrors[] = 'برجاء إختر جنسية العميل <strong></strong>';
                }
            }
            // Loop Into Errors Array And Echo It
            foreach ($formErrors as $error) {
                echo '<div class="alert alert-danger">' . $error . '</div>';
            }
            if (empty($formErrors)) {
                try {
                    $FileNumber = $reservationsManager->generateFileNumber($departure_date);
                    // بدء عملية إضافة العميل إذا كان تم اختيار "اضافة عميل جديد"
                    if ($_POST['client_id'] === 'new') {
                        $client_id = $reservationsManager->addNewClient($new_client_name, $nationality_id);
                    }
                    
                    $lv1 = getName("cost_centers", "ID", $cost_centers_id, "cost_center_code");
                    $new_cost_center_id = getNextCostCenterCode($con, $lv1, $cost_centers_id, $FileNumber);
                    
                    // $result = $reservationsManager->addReservation($tourism_management, $new_cost_center_id, $FileNumber, $agent_id, $client_id, $arrival_date, $departure_date, $remarks);

                    if ($result) {
                            $id_addReservation = $result;
                        
                        $theMsg = "تمت إضافة الحجز بنجاح!";
                        redirectlink($theMsg, $url = "reservations?do=all_data_file&id=".$id_addReservation."", $name = "عرض الملفات", $seconds = 0);
                    } else {
                        echo "حدث خطأ أثناء إضافة الحجز.";
                    }
                } catch (PDOException $e) {
                    echo "حدث خطأ أثناء إضافة الحجز: " . $e->getMessage();
                }
            }
        }
    } elseif ($do === 'insert_invoices_line') {
        if ($_SERVER["REQUEST_METHOD"] === 'POST' && isset($_POST['add_line'])) {
            $id_invoices_line = $_POST['id_invoices_line'] ?? null;
            $reservationsManager = new ReservationsManager($con);
            // استلام البيانات من الفورم
            $reservation_id = $_POST['reservation_id'];
            $id_invoice = $_POST['id_invoice'];
            $number = $_POST['number'];
            $payan = $_POST['payan'];
            $cost = $_POST['cost'];
            $id_hotels = $_POST['id_hotels'];
            $cost_child = $_POST['cost_child'];
            $num_child = $_POST['num_child'];
            $nights = $_POST['nights'];
            $back_invoice = isset($_POST['back_invoice']) ? $_POST['back_invoice'] : '';
            // يمكنك إجراء عمليات التحقق هنا
            $formErrors = array();
            if (empty($number)) {
                $formErrors[] = 'برجاء إدخل عدد الافراد<strong>فارغ</strong>';
            }
            if (empty($payan)) {
                $formErrors[] = 'لا يجب أن يكون البيان  <strong>فارغ</strong>';
            }
            if (empty($cost)) {
                $formErrors[] = 'لا يجب أن يكون حقل تكلفة الفرد  <strong>فارغ</strong>';
            }
            if (empty($nights)) {
                $nights = '';
            }
            if (empty($cost_child)) {
                $cost_child = '';
            }
            if (empty($num_child)) {
                $num_child = '';
            }
            if (!empty($back_invoice) && $back_invoice == 1) {
                $back_invoice = 'invoicess';
            } else {
                $back_invoice = 'invoicess_vo';
            }
            // Loop Into Errors Array And Echo It
            foreach ($formErrors as $error) {
                echo '<div class="alert alert-danger">' . $error . '</div>';
            }
            if (empty($formErrors)) {
                try {
                    if (empty($id_invoices_line)) {
                        $addInvoicingLine = $reservationsManager->addInvoicingLine($id_hotels, $id_invoice, $cost, $cost_child, $num_child, $nights, $sessionUser, $number, '', $payan);
                        if ($addInvoicingLine) {
                                // $id_addReservation = $result;
                            $theMsg = "تمت إضافة البيان بنجاح!";
                            redirectlink($theMsg, $url = "reservations?do=".$back_invoice."&id=".$reservation_id."&id_invoice=".$id_invoice, $name = "عرض الفاتورة", $seconds = 0);
                        } else {
                            echo "حدث خطأ أثناء إضافة البيان.";
                        }
                    } else {
                        $addInvoicingLine = $reservationsManager->updateInvoicingLine($id_invoices_line, $id_hotels, $id_invoice, $cost, $cost_child, $num_child, $nights, $sessionUser, $number, '', $payan);
                        if ($addInvoicingLine) {
                                // $id_addReservation = $result;
                            $theMsg = "تم تعديل البيان بنجاح!";
                            redirectlink($theMsg, $url = "reservations?do=".$back_invoice."&id=".$reservation_id."&id_invoice=".$id_invoice, $name = "عرض الفاتورة", $seconds = 0);
                        } else {
                            echo "حدث خطأ أثناء تعديل البيان.";
                        }
                    }
                } catch (PDOException $e) {
                    echo "حدث خطأ أثناء فى السيرفر أثناء تنفيذ الأمر: " . $e->getMessage();
                }
            }
        } elseif ($_SERVER["REQUEST_METHOD"] === 'POST' && isset($_POST['delete_line'])) {
            $id_invoices_line = $_POST['id_invoices_line'] ?? null;
            $reservation_id = $_POST['reservation_id'];
            $id_invoice = $_POST['id_invoice'];
            $back_invoice = $_POST['back_invoice'];
            if (!empty($back_invoice) && $back_invoice == 1) {
                $back_invoice = 'invoicess';
            } else {
                $back_invoice = 'invoicess_vo';
            }
            if (!empty($id_invoices_line)) {
                $sql = "DELETE FROM invoicing_line WHERE ID = :id_line";
                $stmt = $con->prepare($sql);
                $stmt->bindParam(':id_line', $id_invoices_line);
                $deleteInvoicingLine = $stmt->execute();
                if ($deleteInvoicingLine) {
                    // $id_addReservation = $result;
                $theMsg = "تم حذف البيان بنجاح!";
                redirectlink($theMsg, $url = "reservations?do=".$back_invoice."&id=".$reservation_id."&id_invoice=".$id_invoice, $name = "عرض الفاتورة", $seconds = 0);
                } else {
                    echo "حدث خطأ أثناء حذف البيان.";
                }
            } else {
                echo "حدث خطأ فى السيرفر أثناء حذف البيان.";
            }
            
        }
    } elseif ($do === 'confirm_invoice') {
        $id_file = isset($_GET['id']) && is_numeric($_GET['id']) ? intval($_GET['id']) : 0;

        $countmanagement = 0;
        $id_management = getId("reservations","id",$id_file,"id_tourism_management");
        if ($id_management > 0) {
            $tourism_management = $con->prepare("SELECT * FROM tourism_management where ID = $id_management");
            $tourism_management->execute();
            $managements = $tourism_management->fetch(PDO::FETCH_ASSOC);
            $count = $tourism_management->rowCount();
            if ($count > 0) {
                $department_id = $managements['department_id'];
                $name_management = $managements['name_management'];
                $id_user = $_SESSION['admin'];
                if (checkadmin($id_user, $department_id, 2) == 1 ) {
                    $countmanagement += 1;
                }
            } else {
                $countmanagement = 0;
            }
        } else {
            $countmanagement = 0;
        }

        if ($countmanagement > 0 && $id_file > 0) {
            if (isset($_GET['id_invoice']) && is_numeric($_GET['id_invoice'])) {
                $id_invoice = $_GET['id_invoice'];

                $reservationsManager = new ReservationsManager($con);
                $reservation_id = $id_file;
                $reservationDatas = $reservationsManager->getReservationById($id_file);
                // $invoicingDatas = $reservationsManager->getInvoicingById($id_invoice);
                $InvoicingLines = $reservationsManager->getInvoicingDataById($id_invoice);

                $invoicing_no = getName("invoicing", "ID", $id_invoice,"invoicing_no");
                $total_cost_invice = 0;
                if (is_array($InvoicingLines)) {
                    foreach ($InvoicingLines as $key => $value) {
                        $total_cost_invice += $value['total_invoice'];
                    }
                }

                $id_cost_center_reservation = getId('reservations', 'id', $id_file, 'id_cost_center');
                $check_in_date = getId('reservations', 'id', $id_file, 'arrival_date');
                $id_hotel_bookings = getId('hotel_bookings', 'id_reservation', $id_file, 'ID');
                $id_tourism_management = $reservationDatas['id_tourism_management'];

                // $id_lv_exp = getId('tourism_management', 'ID', $id_tourism_management, 'lv_exp');
                $id_lv_eradat = getId('tourism_management', 'ID', $id_tourism_management, 'lv_eradat');

                $currencyExchangeRate = getId('currency', 'ID', 2, 'currencyExchangeRate');
                
                $id_lv_maden = getId('agents', 'ID', $reservationDatas['agent_id'], 'id_level_acc');
                // $id_lv_daen = getId('hotels', 'ID', $value['id_hotel'], 'id_level_acc');
                // $id_lv_daen = 25;

                $price = $total_cost_invice;

                $mydate = date('Y-m-d');

                $transaction = new YomyaTransaction($con);

                try {
                    $addyomya1 = $transaction->insertTransaction($mydate, $price, "قيمة فاتورة رقم ". $invoicing_no . " لملف رقم ". $reservationDatas['file_number'], $sessionUser, array($price), array($id_lv_maden), array($price), array($id_lv_eradat), 2, $currencyExchangeRate, NULL, array($id_cost_center_reservation));
                    
                    $hotel_conditions = "INSERT INTO hotel_booking_pay_arr (id_type, id_reservation, id_hotel_booking, date_go, cash) 
                                                        VALUES (2, :id_reservation, :id_hotel_booking, :date_go, '')";
                    $hotel_conditionsStmt = $con->prepare($hotel_conditions);
                    $hotel_conditionsStmt->bindParam(':id_reservation', $id_file);
                    $hotel_conditionsStmt->bindParam(':id_hotel_booking', $id_hotel_bookings);
                    $hotel_conditionsStmt->bindParam(':date_go', $check_in_date);
                    $stmtret = $hotel_conditionsStmt->execute();
                    

                    $sql = "UPDATE invoicing SET invoice_status	 = 1 WHERE ID = $id_invoice";
                    $result = $con->exec($sql);
                    

                    if ($result) {
                        // $id_addReservation = $result;
                    $theMsg = "تمت تأكيد الفاتورة بنجاح!";
                    redirectlink($theMsg, $url = "reservations?do=invoicess_vo&id=".$id_file."&id_invoice=".$id_invoice, $name = "عرض الملف", $seconds = 0);
                } else {
                    echo "حدث خطأ أثناء تأكيد الفاتورة.";
                }
                } catch (PDOException $e) {
                    echo "حدث خطأ أثناء فى السيرفر تأكيد الفاتورة: " . $e->getMessage();
                }
            } else {
                // رسالة خطأ أو إعادة توجيه إلى صفحة خطأ
                echo "خطأ: يجب تحديد رقم الحجز.";
                exit;
            }
        }
    } else {
        $theMsg = '<div class="alert alert-danger">ليس لديك صلاحية الدخول الى هذا القسم</div>';
        redirectHome($theMsg);
    }
} else {
    echo '<div class="alert alert-danger">ليس لديك صلاحية الدخول</div>';
}
include $tpl . 'footer.php';
ob_end_flush();
?>