<?php
require_once __DIR__ . '/../magic/auth.php';

$auth = bdr_require_privilege(6, '../logout.php');
$user = $auth['user_id'];
$father = $auth['user_id'];
$branch = $auth['branch'];
$conn = $auth['conn'];
$db = $auth['conn'];

// Start session securely
if (session_status() === PHP_SESSION_NONE) {
    session_start([
        'cookie_httponly' => true,
        'cookie_samesite' => 'Lax'
    ]);
}

// Check if user is authenticated
if (empty($_SESSION["user_id"])) {
    header("HTTP/1.1 401 Unauthorized");
    exit("Unauthorized access");
}

$cust_id = (int)$_REQUEST['id'];


// get customer data
require_once("../magic/Customers.php");
    $table = "customers";
    $customer = new Customers($dataBase, $table);
    $cust = $customer->singleCust($cust_id);
if (!$cust) {
    echo "لا يوجد مستأجر بهذا الرقم";
    exit;
}
?>
<!DOCTYPE html>
<html dir="rtl" lang="ar">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>تعديل بيانات عميل</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.rtl.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
    <link rel="stylesheet" href="./../css25/myCar.css" />
    <link rel="stylesheet" href="./../css25/drop.css" />
    <link rel="icon" href="./../images/perfect.ico">
</head>

<body class="bg-dark">
    <style>
        input[type="text"]:focus,
        input[type="date"]:focus,
        input[type="number"]:focus,
        input[type="tel"]:focus,
        textarea:focus {
            background-color: rgb(147, 227, 225);
            /* Light blue background */
            border-color: #4CAF50;
            /* Green border */
        }

        .bold_num {
            font-size: 15px;
            font-weight: 700;
        }

        .req {
            background-color: rgb(242, 204, 186);
        }

        label {
            float: left;
        }

        .red_text {
            color: rgb(116, 8, 8);
        }

        .star {
            color: rgb(194, 9, 9);
            font-size: 15px;
            font-weight: bold;
        }

        .valid-input {
            border-color: green;

        }

        .invalid-input {
            border-color: red;
        }

        .error-message {
            font-size: 0.85rem;
        }
    </style>
    <div class="container-full">
        <div class="card shadow  bg-secondary bg-gradient">
            <div class="card-header bg-info text-white">
                <h3 class="text-center">تعديل بيانات مستأجر</h3>
            </div>
            <br />
            <div class="card-body">
                <form id="customerForm" method="PATCH" enctype="multipart/form-data">
                     <input type="hidden" id="cust_id" name="cust_id" value="<?= $cust['cust_id'] ?>">
                     <input type="hidden" id="cust_photo" name="cust_photo" value="<?= $cust['cust_photo'] ?>">
                    <div class="row">
                        <div class="col-md-12 text-center">
                            <div id="msg"></div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-8">
                    <div class="row">
                        <div class="col-md-2 mb-3">
                            <label for="idSA" class="form-label">رقم الهوية <span class="star"> * </span></label>
                        </div>
                        <div class="col-md-3 mb-3">
                            <input type="number" class="form-control bold_num" id="idSA" name="idSA" value="<?= $cust['idSA'] ?>" placeholder="رقم الهوية">
                            <div class="red_text error-message" id="idSA_msg"></div>
                        </div>
                        <div class="col-md-1 mb-3">
                            <label for="xn" class="form-label">نسخة<span class="star"> * </span></label>
                        </div>
                        <div class="col-md-1 mb-3">
                            <input type="number" class="form-control bold_num " onchange="enforceMinValue('xn', minValue = 1)" id="xn" name="xn" value="<?= $cust['xn'] ?>">
                            <div class="red_text error-message" id="xn_msg"></div>
                        </div>
                        <div class="col-md-2 mb-3">
                            <label for="id_Expire" class="form-label">تاريخ الانتهاء</label>
                        </div>
                        <div class="col-md-3 mb-3">
                            <input type="text" class="form-control bold_num " id="id_Expire" name="id_Expire" value="<?= $cust['id_Expire'] ?>">
                            <div class="red_text error-message" id="id_Expire_msg"></div>
                        </div>

                    </div>

                    <div class="row">
                        <div class="col-md-2 mb-3">
                            <label for="cust_name" class="form-label">اسم المستأجر <span class="star"> * </span></label>
                        </div>
                        <div class="col-md-4 mb-3">
                            <input type="text" class="form-control bold_num" id="cust_name" name="cust_name" value="<?= $cust['cust_name'] ?>">
                            <div class="red_text error-message" id="cust_name_msg"></div>
                        </div>
                        <div class="col-md-2 mb-3">
                            <label for="nation" class="form-label">الجنسية<span class="star"> * </span></label>
                        </div>
                        <div class="col-md-4 mb-3">
                            <input type="text" class="form-control bold_num" id="nation" name="nation" value="<?= $cust['nation'] ?>">
                            <div class="red_text error-message" id="nation_msg"></div>
                        </div>
                    </div>
                    <!-- // -->
                    <div class="row">
                        <div class="col-md-2 mb-3">
                            <label for="phone" class="control-label ">رقم الجوال<span class="star"> * </span></label>
                        </div>
                        <div class="col-md-3 mb-3">
                            <input type="number" class="form-control" id="phone" name="phone" placeholder="رقم الجوال" value="<?= $cust['phone'] ?>" />
                            <div class="red_text error-message" id="phone_msg"></div>
                        </div>
                        <div class="col-md-2 mb-3">
                            <label for="phone2" class="control-label">جوال2</label>
                        </div>

                        <div class="col-md-3 mb-3">
                            <input type="number" class="form-control" id="phone2" name="phone2" placeholder="رقم جوال2" value="<?= $cust['phone2'] ?>" />
                            <div class="red_text error-message" id="phone2_msg"></div>
                        </div>
                        <div class="col-md-1 mb-3"></div>
                        <div class="col-md-1 mb-3">
                            <input type="number" class="form-control bold_num" id="dgree" name="dgree" max="100" min="1" value="65" placeholder="تقييم" value="<?= $cust['dgree'] ?>" >
                            <div class="red_text error-message" id="dgree_msg"></div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-2 mb-3">
                            <label for="address" class="form-label">العنوان <span class="star"> * </span></label>
                        </div>
                        <div class="col-md-10 mb-3">
                            <input type="text" class="form-control bold_num" id="address" name="address" value="جدة" value="<?= $cust['address'] ?>" />
                            <div class="red_text error-message" id="address_msg"></div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-3">
                            <label for="birth_hijri" id="hijri_label" class="control-label" style="float:left;">تاريخ الميلاد14401205</label>
                        </div>
                        <div class="col-md-2">
                            <input type="number" class="form-control  bold_num" id="birth_hijri" name="birth_hijri" value="<?= $cust['birth_hijri'] ?>" >
                            <div class="red_text error-message" id="birth_hijri_msg"></div>
                        </div>
                        <div class="col-md-2">
                            <label class="control-label text-center" id="minDate"></label>
                        </div>
                        <div class="col-md-3">
                            <label for="birth" id="birth_label" class="control-label">تاريخ الميلاد ميلادي<span class="star"> * </span></label>
                        </div>
                        <div class="col-md-2">
                            <input type="text" class="form-control bold_num" id="birth" name="birth" readonly value="<?= $cust['birth'] ?>">
                            <div class="red_text error-message" id="birth_msg"></div>
                            <script>
                                // Wait for DOM to be ready
                                document.addEventListener("DOMContentLoaded", function() {
                                    const idInput = document.getElementById("idSA");
                                    const licenseInput = document.getElementById("license");
                                    const nation = document.getElementById("nation");

                                    const birth = document.getElementById("birth");
                                    const birth_hijri = document.getElementById("birth_hijri");
                                    const hijri_label = document.getElementById("hijri_label");
                                    const birth_label = document.getElementById("birth_label");

                                    // When user leaves (exits) the idSA field, copy its value to license
                                    // idInput.addEventListener("blur", function() {
                                        const currentValue = idInput.value.trim(); // Get and trim whitespace
                                        if (currentValue) {
                                            licenseInput.value = currentValue; // Set license field
                                            const firstDigit = parseInt(currentValue[0], 10);
                                            if (firstDigit === 1) {
                                                nation.value = "سعودي";
                                                birth.style.display = 'none';
                                                birth_label.style.display = 'none';
                                                birth_hijri.style.display = 'block';
                                                hijri_label.style.display = 'block';
                                            } else {
                                                // nation.value = "";
                                                birth.style.display = 'block';
                                                birth_label.style.display = 'block';
                                                birth_hijri.style.display = 'none';
                                                birth_hijri.value = "";
                                                hijri_label.style.display = 'none';
                                            }
                                        }
                                    // });
                                    // birth_hijri.addEventListener("blur",validateHijri);
                                    nation.addEventListener("blur", function() {
                                        const value = this.value.trim();
                                        const options = ["سعودي", "مصري", "يمني", "هندي", "باكستاني", "صومالي", "سوداني", "اماراتي", "اردني", "بنجلاديش","سوريا","اندونيسي", "لبناني"];

                                        // Auto-correct minor typos or suggest closest (simple version)
                                        const matched = options.find(opt => opt.startsWith(value));
                                        if (matched && value !== matched) {
                                            const confirmChange = confirm(`هل تقصد: ${matched}؟`);
                                            if (confirmChange) {
                                            this.value = matched;
                                            }
                                        }
                                    });
                                });
                            </script>
                        </div>
                    </div>
                            </div>
                        <div class="col-md-4">
                            <div class="file-view mt-3"></div>
                        </div>
                        </div>
                    <hr />
                    <div class="row">
                        <div class="col-md-8 mb-3">
                            <br />
                            <div class="row">
                                <div class="col-md-2 mb-3">
                                    <label for="license" class="form-label">رقم الرخصة <span class="star"> * </span></label>
                                </div>
                                <div class="col-md-4 mb-3">
                                    <input type="number" class="form-control bold_num" id="license" name="license" placeholder="رقم الرخصة" value="<?= $cust['license'] ?>" readonly>
                                    <div class="red_text error-message " id="license_msg"></div>
                                </div>
                                <div class="col-md-2 mb-3">
                                    <label for="lic_expire" class="form-label">تاريخ الانتهاء<span class="star"> * </span></label>
                                </div>
                                <div class="col-md-4 mb-3">
                                    <input type="text" class="form-control bold_num " id="lic_expire" name="lic_expire" value="<?= $cust['lic_expire'] ?>">
                                    <div class="red_text error-message" id="lic_expire_msg"></div>
                                </div>

                            </div>
                            <!-- // -->

                            <div class="row">
                                <div class="col-md-2 mb-3">
                                    <label for="working_woner" class="form-label">جهة العمل</label>
                                </div>
                                <div class="col-md-10 mb-3">
                                    <input type="text" class="form-control" id="working_woner" name="working_woner" placeholder="اسم الشركة" value="<?= $cust['working_woner'] ?>">
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-2 mb-3">
                                    <label for="w_phone" class="form-label">جوال العمل</label>
                                </div>
                                <div class="col-md-5 mb-3">
                                    <input type="number" class="form-control bold_num " id="w_phone" name="w_phone" placeholder="جوال جهة العمل" value="<?= $cust['w_phone'] ?>">
                                    <div class="red_text error-message" id="w_phone_msg"></div>
                                </div>
                                <div class="col-md-4 mb-3">
                                    <input type="number" class="form-control bold_num " id="w_phone2" name="w_phone2" placeholder="جوال جهة العمل 2" value="<?= $cust['w_phone2'] ?>">
                                    <div class="red_text error-message" id="w_phone2_msg"></div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-12 mb-3">
                                    <label for="comm" style="float: right;" class="form-label">ملاحظات</label>
                                    <textarea class="form-control" id="comm" name="comm" rows="2"><?= $cust['comm'] ?></textarea>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4 mb-3">
                            <div class="row">
                                <div class="col-md-12 mb-3 ">
                                    <div class="drop-area" id="dropArea" style="height:330px;">
                                        سحب وافلات هنا ..<small class="text-muted">(الملفات المدعومة: JPG, PDF)</small>
                                        <div class="file-preview mt-3"></div>
                                    </div>
                                    <input type="file" name="file" id="fileInput" hidden accept=".jpg,.jpeg,.pdf">
                                    <div class="red_text error-message" id="file_msg"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <!-- </div> -->
                    <br />
                    <button type="submit" class="btn btn-primary w-100">حفظ التعديلات</button>
                </form>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        const fileView = document.querySelector('.file-view');
        const cust_item = document.getElementById('cust_photo');
        var cust_photo = cust_item.value;
        // const idSA = document.getElementById('idSA');

        // Show fileview
        fileView.innerHTML = '';
    if (cust_photo.endsWith("pdf")) {
            const iframe = document.createElement('iframe');
            iframe.src = "../photo/customers/" + cust_photo;
            iframe.className = 'pdf-preview';
            iframe.height = 260;
            fileView.appendChild(iframe);
        }
        // if ((cust_photo.endsWith("jpg") || (cust_photo.endsWith("jpeg"))))
        else  {
            const img = document.createElement('img');
            img.src = "../photo/customers/" + cust_photo;
            img.alt = "جاري التحميل ...";
            img.height = 260;
            fileView.appendChild(img);
        }  
    </script>
    <script>
        function enforceMinValue(inputId, minValue = 1) {
            const input = document.getElementById(inputId);

            if (!input) {
                console.error(`Element with id "${inputId}" not found.`);
                return;
            }

            // Ensure the input is of type "number"
            if (input.type !== "number") {
                console.warn(`Input with id "${inputId}" is not a number input.`);
            }

            // Set the min attribute (for form validation)
            input.setAttribute("min", minValue);

            // Listen for any input changes
            input.addEventListener("input", function() {
                const value = parseFloat(this.value);

                // If valid number and below minimum, correct it
                if (!isNaN(value) && value < minValue) {
                    this.value = minValue;
                }
            });

            // Optional: Handle paste events to prevent invalid pasted values
            input.addEventListener("paste", function() {
                // Delay slightly to get pasted value
                setTimeout(() => {
                    const value = parseFloat(this.value);
                    if (!isNaN(value) && value < minValue) {
                        this.value = minValue;
                    }
                }, 10);
            });
        }
    </script>
    <script>
        function validatePhoneNumber(phone) {
            return /^05\d{8}$/.test(phone); // Saudi phone number format
        }

        function ifPhone(phone) {
            if (phone) {
                return /^05\d{8}$/.test(phone);
                // Saudi phone number format
            }
            return true;

        }

        function validateHijri(input) {
            if (input) {
                return /^1\d{7}$/.test(input);
            }
            const idInput = document.getElementById("idSA");
            const birthInput = document.getElementById("birth_hijri");

            const idValue = idInput.value.trim();
            const birthValue = birthInput.value.trim();

            // // Check if ID is empty
            if (idValue === "") {
                return false;
            }

            // Get the first digit of the ID
            const firstDigit = parseInt(idValue[0], 10);

            // Check if first character is a valid number
            if (isNaN(firstDigit)) {
                // console.warn("First character of ID is not a number");
                return false;
            }

            // Example logic:
            // If first digit is 1: citizen → require birth date?
            // If first digit is 2: non-citizen → maybe skip birth check?
            if (firstDigit === 1 && birthValue.length < 3) {
                // Maybe you want to prevent birth input if id starts with 2?
                return false;
            } else {
                return true; // valid
            }

            // Default: invalid case
            return false;
        }


        function birthCheck() {
            const idInput = document.getElementById("idSA");
            const birthInput = document.getElementById("birth");

            const idValue = idInput.value.trim();
            const birthValue = birthInput.value.trim();

            // // Check if ID is empty
            if (idValue === "") {
                return false;
            }

            // Get the first digit of the ID
            const firstDigit = parseInt(idValue[0], 10);

            // Check if first character is a valid number
            if (isNaN(firstDigit)) {
                // console.warn("First character of ID is not a number");
                return false;
            }

            // Example logic:
            // If first digit is 1: citizen → require birth date?
            // If first digit is 2: non-citizen → maybe skip birth check?
            if (firstDigit === 2 && birthValue.length < 3) {
                // Maybe you want to prevent birth input if id starts with 2?
                return false;
            } else {
                return true; // valid
            }

            // Default: invalid case
            return false;
        }

        function validateSAID(id) {
            return /^[12]\d{9}$/.test(id);
        }

        const dropArea = document.getElementById('dropArea');
        const fileInput = document.getElementById('fileInput');
        const filePreview = document.querySelector('.file-preview');

        const idSA = document.getElementById('idSA');
        const id_Expire = document.getElementById('id_Expire');
        const cust_name = document.getElementById('cust_name');
        const dgree = document.getElementById('dgree');
        const phone = document.getElementById('phone');
        const phone2 = document.getElementById('phone2');
        const working_woner = document.getElementById('working_woner');
        const w_phone = document.getElementById('w_phone');
        const w_phone2 = document.getElementById('w_phone2');
        const comm = document.getElementById('comm');


        idSA.addEventListener('input', function() {
            if (validateSAID(this.value)) {
                this.classList.remove('invalid-input', 'req');
                this.classList.add('valid-input');
            } else {
                this.classList.remove('valid-input');
                this.classList.add('invalid-input', 'req');
            }
        });
        cust_name.addEventListener('input', function() {
            if (this.value.length > 2) {
                this.classList.remove('invalid-input', 'req');
                this.classList.add('valid-input');
            } else {
                this.classList.remove('valid-input');
                this.classList.add('invalid-input', 'req');
            }
        });
        phone.addEventListener('input', function() {
            if (validatePhoneNumber(this.value)) {
                this.classList.remove('invalid-input', 'req');
                this.classList.add('valid-input');
            } else {
                this.classList.remove('valid-input');
                this.classList.add('invalid-input', 'req');
            }
        });


        // Highlight drop area when dragging over it
        ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
            dropArea.addEventListener(eventName, preventDefaults, false);
        });

        function preventDefaults(e) {
            e.preventDefault();
            e.stopPropagation();
        }

        ['dragenter', 'dragover'].forEach(eventName => {
            dropArea.addEventListener(eventName, () => dropArea.classList.add('active'), false);
        });

        ['dragleave', 'drop'].forEach(eventName => {
            dropArea.addEventListener(eventName, () => dropArea.classList.remove('active'), false);
        });

        // Handle dropped files
        dropArea.addEventListener('drop', handleDrop, false);

        function handleDrop(e) {
            const dt = e.dataTransfer;
            const files = dt.files;

            handleFiles(files);
        }

        // Open file dialog when clicking on the drop area
        dropArea.addEventListener('click', () => fileInput.click());

        // Handle file input change
        fileInput.addEventListener('change', () => {
            handleFiles(fileInput.files);
        });

        function handleFiles(files) {
            if (files.length > 1) {
                alert('يرجى اختيار ملف واحد فقط');
                return;
            }
            const file = files[0];
            const maxSize = 2 * 1024 * 1024; // 5MB

            // Validate file type and size
            if (!['image/jpeg', 'application/pdf'].includes(file.type)) {
                alert('نوع الملف غير مدعوم. يرجى اختار صورة (JPG) أو ملف PDF');
                return;
            }

            if (file.size > maxSize) {
                alert('حجم الملف كبير جداً. الحد الأقصى 5MB');
                return;
            }
            ([...files]).forEach(uploadFile);
        }

        function uploadFile(file) {
            // Validate file type
            if (!['image/jpeg', 'application/pdf'].includes(file.type)) {
                alert('فضلا اختار صور او ملفات pdf شكرا');
                return;
            }

            // Show file preview
            filePreview.innerHTML = ''; // Clear previous preview

            if (file.type.startsWith('image/')) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    const img = document.createElement('img');
                    img.src = e.target.result;
                    filePreview.appendChild(img);
                };
                reader.readAsDataURL(file);
            } else if (file.type === 'application/pdf') {
                const reader = new FileReader();
                reader.onload = function(e) {
                    const iframe = document.createElement('iframe');
                    iframe.src = e.target.result;
                    iframe.className = 'pdf-preview';
                    iframe.height = 260;
                    filePreview.appendChild(iframe);
                };
                reader.readAsDataURL(file);
            }

            // Store file in input field
            const dataTransfer = new DataTransfer();
            dataTransfer.items.add(file);
            fileInput.files = dataTransfer.files;
        }
        //validation
        function validateForm() {
            let isValid = true;
            document.querySelectorAll('.error-message').forEach(el => el.textContent = '');

            // Validate required fields
            const fields = [{
                    id: 'idSA',
                    validator: validateSAID,
                    msg: 'يجب أن يتكون رقم الهوية من 10 أرقام'
                },
                {
                    id: 'cust_name',
                    validator: v => v.length >= 9,
                    msg: 'الاسم يجب أن يكون 9 أحرف على الأقل'
                },
                {
                    id: 'nation',
                    validator: v => v.length >= 2,
                    msg: 'يجب إدخال الجنسية'
                },
                {
                    id: 'xn',
                    validator: v => v.length > 0,
                    msg: 'نسخة رقم ؟'
                },
                {
                    id: 'address',
                    validator: v => v.length >= 3,
                    msg: 'يجب إدخال العنوان'
                },
                {
                    id: 'license',
                    validator: validateSAID,
                    msg: 'رقم الرخصة يجب أن يكون بين 10 رقماً'
                },
                {
                    id: 'birth_hijri',
                    validator: validateHijri,
                    msg: 'التاريخ الهجري 14220101 علي نفس الشكل '
                },
                {
                    id: 'birth',
                    validator: birthCheck,
                    msg: 'فضلا اختار تاريخ الميلاد'
                },
                {
                    id: 'phone',
                    validator: validatePhoneNumber,
                    msg: 'رقم الجوال 10 ارقام يبدأ برقم 05'
                },
                {
                    id: 'phone2',
                    validator: ifPhone,
                    msg: 'رقم الجوال اختياري 10 ارقام يبدأ برقم 05'
                },
                {
                    id: 'w_phone',
                    validator: ifPhone,
                    msg: 'رقم الجوال اختياري 10 ارقام يبدأ برقم 05'
                },
                {
                    id: 'w_phone2',
                    validator: ifPhone,
                    msg: 'رقم الجوال اختياري 10 ارقام يبدأ برقم 05'
                },
                {
                    id: 'lic_expire',
                    validator: v => v.length >= 3,
                    msg: 'سجل تاريخ انتهاء رخصة القيادة'
                }
            ];

            fields.forEach(field => {
                const element = document.getElementById(field.id);
                const value = element.value.trim();

                if (!field.validator(value)) {
                    document.getElementById(`${field.id}_msg`).textContent = field.msg;
                    element.classList.add('is-invalid');
                    isValid = false;
                } else {
                    element.classList.remove('is-invalid');
                }
            });
            return isValid;
        }

        // Form Submission
        document.getElementById('customerForm').addEventListener('submit', async (e) => {
            e.preventDefault();

            if (!validateForm()) return;
            const form = e.target;
            // console.log(form) ;
            const submitBtn = form.querySelector('button[type="submit"]');
            const originalText = submitBtn.innerHTML;
            const msgContainer = document.getElementById('msg');

            submitBtn.disabled = true;
            submitBtn.innerHTML = `
                <span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
                جاري الحفظ...
            `;

            try {
                const formData = new FormData(form);
                console.log(formData);
                formData.append('action', 'update');
                // alert(formData);
                // console.log(formData);

                const response = await fetch('customerController.php', {
                    method: 'PATCH',
                    body: formData
                });

                const result = await response.json();

                if (result.success) {
                    // window.location.href = 'customerFlow.php';
                } else {
                    msgContainer.textContent = result.save_msg || 'حدث خطأ أثناء المعالجة';
                    handleServerErrors(result);
                }
            } catch (error) {
                // console.error('Submission error:', error);
                // document.getElementById('msg').textContent = 'فشل في الإتصال بالخادم';
            } finally {
                submitBtn.disabled = false;
                submitBtn.innerHTML = originalText;
            }
        });

        // deep
        function handleServerErrors(result) {
            const errorFields = [
                'idSA_msg', 'phone_msg'
            ];

            errorFields.forEach(field => {
                const errorElement = document.getElementById(field);
                if (errorElement && result[field]) {
                    errorElement.textContent = result[field];
                }
            });
        }
    </script>

    <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
    <!-- Include Flatpickr Arabic Localization -->
    <script src="https://npmcdn.com/flatpickr/dist/l10n/ar.js"></script>
    <script>
        function timeFormat(input) {
            // const timestamp = 1092471216830;
            const date = new Date(input);

            // Extract local components
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');

            // const formattedDate = `${year}/${month}/${day}`;
            return `${year}/${month}/${day}`;
        }
        const today = new Date();

        // Calculate the date 5 years from today
        const current = new Date(today);
        current.setFullYear(today.getFullYear());
        const lice_ex = current.setFullYear(today.getFullYear() + 10);
        const birthstart = current.setFullYear(today.getFullYear() - 60);
        const birthend = current.setFullYear(today.getFullYear() - 21);
        const birthdefault = current.setFullYear(today.getFullYear() - 35);
        const expire = new Date(today);
        expire.setMonth(today.getMonth() + 3)

        flatpickr("#id_Expire", {
            dateFormat: "Y-m-d", // Display format: yyyy-mm-dd
            locale: "ar", // Use Arabic localization
            defaultDate: expire, // Set initial value to today's date
            minDate: today, // Set minimum selectable date
            maxDate: lice_ex, // Set maximum selectable date
        });
        flatpickr("#birth", {
            dateFormat: "Y-m-d", // Display format: yyyy-mm-dd
            locale: "ar", // Use Arabic localization
            // defaultDate: birthdefault, // Set initial value to today's date
            minDate: birthstart, // Set minimum selectable date 
            maxDate: birthend, // Set maximum selectable date
        });
        flatpickr("#lic_expire", {
            dateFormat: "Y-m-d", // Display format: yyyy-mm-dd
            locale: "ar", // Use Arabic localization
            // defaultDate: expire, // Set initial value to today's date
            minDate: expire, // Set minimum selectable date
            maxDate: lice_ex, // Set maximum selectable date
        });

        let minDate = document.getElementById("minDate");
        minDate.innerText = " أصغر ميلاد " + timeFormat(birthend);
    </script>


</body>

</html>