<?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"])) {
    http_response_code(401);
    exit("Unauthorized access");
}

// Validate and sanitize input
if (!isset($_REQUEST['id']) || !is_numeric($_REQUEST['id'])) {
    http_response_code(400);
    exit("Invalid customer ID");
}
$cust_id = (int)$_REQUEST['id'];


// Check user privileges
try {
} catch (Exception $e) {
    error_log("Privilege check failed: " . $e->getMessage());
    header("Location: ../logout.php");
    exit();
}

// 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);
            border-color: #4CAF50;
        }

        .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;
            color: red;
        }

        .drop-area.active {
            border-color: #0d6efd;
            background-color: #f8f9fa;
        }

        .pdf-preview {
            width: 100%;
            border: none;
        }
    </style>

    <div class="container-fluid py-4">
        <div class="card shadow bg-secondary bg-gradient">
            <div class="card-header bg-info text-white">
                <h3 class="text-center">تعديل بيانات مستأجر</h3>
            </div>
            <div class="card-body">
                <!-- Use POST method; simulate PATCH via hidden action -->
                <form id="customerForm" method="POST" enctype="multipart/form-data">
                    <input type="hidden" name="action" value="update">
                    <input type="hidden" id="cust_id" name="cust_id" value="<?= htmlspecialchars($cust['cust_id']) ?>">
                    <input type="hidden" id="cust_photo" name="cust_photo" value="<?= htmlspecialchars($cust['cust_photo']) ?>">

                    <div class="row">
                        <div class="col-md-12 text-center">
                            <div id="msg" role="alert"></div>
                        </div>
                    </div>

                    <div class="row">
                        <!-- Left Column -->
                        <div class="col-md-8">
                            <!-- ID & Expiry -->
                            <div class="row mb-3">
                                <div class="col-md-2">
                                    <label for="idSA" class="form-label">رقم الهوية <span class="star">*</span></label>
                                </div>
                                <div class="col-md-3">
                                    <input type="number" class="form-control bold_num" id="idSA" name="idSA"
                                        value="<?= htmlspecialchars($cust['idSA']) ?>" placeholder="رقم الهوية">
                                    <div class="red_text error-message" id="idSA_msg"></div>
                                </div>
                                <div class="col-md-1">
                                    <label for="xn" class="form-label">نسخة<span class="star">*</span></label>
                                </div>
                                <div class="col-md-1">
                                    <input type="number" class="form-control bold_num" id="xn" name="xn"
                                        value="<?= htmlspecialchars($cust['xn']) ?>" min="1">
                                    <div class="red_text error-message" id="xn_msg"></div>
                                </div>
                                <div class="col-md-2">
                                    <label for="id_Expire" class="form-label">تاريخ الانتهاء</label>
                                </div>
                                <div class="col-md-3">
                                    <input type="text" class="form-control bold_num" id="id_Expire" name="id_Expire"
                                        value="<?= htmlspecialchars($cust['id_Expire']) ?>">
                                    <div class="red_text error-message" id="id_Expire_msg"></div>
                                </div>
                            </div>

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

                            <!-- Phone -->
                            <div class="row mb-3">
                                <div class="col-md-2">
                                    <label for="phone" class="form-label">رقم الجوال<span class="star">*</span></label>
                                </div>
                                <div class="col-md-3">
                                    <input type="tel" class="form-control" id="phone" name="phone"
                                        value="<?= htmlspecialchars($cust['phone']) ?>" placeholder="05XXXXXXXX">
                                    <div class="red_text error-message" id="phone_msg"></div>
                                </div>
                                <div class="col-md-2">
                                    <label for="phone2" class="form-label">جوال2</label>
                                </div>
                                <div class="col-md-3">
                                    <input type="tel" class="form-control" id="phone2" name="phone2"
                                        value="<?= htmlspecialchars($cust['phone2']) ?>" placeholder="05XXXXXXXX">
                                    <div class="red_text error-message" id="phone2_msg"></div>
                                </div>
                                <div class="col-md-1"></div>
                                <div class="col-md-1">
                                    <input type="number" class="form-control bold_num" id="dgree" name="dgree"
                                        min="1" max="100" value="<?= htmlspecialchars($cust['dgree']) ?>"
                                        placeholder="تقييم">
                                    <div class="red_text error-message" id="dgree_msg"></div>
                                </div>
                            </div>

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

                            <!-- Birth Date -->
                            <div class="row mb-3">
                                <div class="col-md-3">
                                    <label for="birth_hijri" id="hijri_label" class="control-label" style="float:left;">
                                        تاريخ الميلاد الهجري
                                    </label>
                                </div>
                                <div class="col-md-2">
                                    <input type="number" class="form-control bold_num" id="birth_hijri" name="birth_hijri"
                                        value="<?= htmlspecialchars($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="<?= htmlspecialchars($cust['birth']) ?>">
                                    <div class="red_text error-message" id="birth_msg"></div>
                                </div>
                            </div>

                            <!-- License -->
                            <div class="row mb-3">
                                <div class="col-md-2">
                                    <label for="license" class="form-label">رقم الرخصة <span class="star">*</span></label>
                                </div>
                                <div class="col-md-4">
                                    <input type="number" class="form-control bold_num" id="license" name="license"
                                        value="<?= htmlspecialchars($cust['license']) ?>" readonly>
                                    <div class="red_text error-message" id="license_msg"></div>
                                </div>
                                <div class="col-md-2">
                                    <label for="lic_expire" class="form-label">انتهاء الرخصة<span class="star">*</span></label>
                                </div>
                                <div class="col-md-4">
                                    <input type="text" class="form-control bold_num" id="lic_expire" name="lic_expire"
                                        value="<?= htmlspecialchars($cust['lic_expire']) ?>">
                                    <div class="red_text error-message" id="lic_expire_msg"></div>
                                </div>
                            </div>

                            <!-- Work Info -->
                            <div class="row mb-3">
                                <div class="col-md-2">
                                    <label for="working_woner" class="form-label">جهة العمل</label>
                                </div>
                                <div class="col-md-10">
                                    <input type="text" class="form-control" id="working_woner" name="working_woner"
                                        value="<?= htmlspecialchars($cust['working_woner']) ?>">
                                </div>
                            </div>

                            <div class="row mb-3">
                                <div class="col-md-2">
                                    <label for="w_phone" class="form-label">جوال العمل</label>
                                </div>
                                <div class="col-md-5">
                                    <input type="tel" class="form-control bold_num" id="w_phone" name="w_phone"
                                        value="<?= htmlspecialchars($cust['w_phone']) ?>">
                                    <div class="red_text error-message" id="w_phone_msg"></div>
                                </div>
                                <div class="col-md-4">
                                    <input type="tel" class="form-control bold_num" id="w_phone2" name="w_phone2"
                                        value="<?= htmlspecialchars($cust['w_phone2']) ?>">
                                    <div class="red_text error-message" id="w_phone2_msg"></div>
                                </div>
                            </div>

                            <div class="row mb-3">
                                <div class="col-md-12">
                                    <label for="comm" class="form-label" style="float: right;">ملاحظات</label>
                                    <textarea class="form-control" id="comm" name="comm" rows="2"><?= htmlspecialchars($cust['comm']) ?></textarea>
                                </div>
                            </div>
                        </div>

                        <!-- Right Column: File Upload -->
                        <div class="col-md-4">
                            <div class="file-view mt-3"></div>
                            <div class="drop-area mt-3" id="dropArea" style="height: 330px; border: 2px dashed #ccc; display: flex; align-items: center; justify-content: center; flex-direction: column;">
                                سحب وإفلات الملف هنا
                                <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>

                    <hr>
                    <button type="submit" class="btn btn-primary w-100">حفظ التعديلات</button>
                </form>
            </div>
        </div>
    </div>

    <!-- Scripts -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
    <script src="https://npmcdn.com/flatpickr/dist/l10n/ar.js"></script>

    <script>
        // DOM Ready
        document.addEventListener("DOMContentLoaded", function () {
            const idSA = document.getElementById("idSA");
            const license = 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");

            // Sync license with ID
            idSA.addEventListener("blur", function () {
                const val = this.value.trim();
                if (val) {
                    license.value = val;
                    const firstDigit = parseInt(val[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 {
                        birth.style.display = 'block';
                        birth_label.style.display = 'block';
                        birth_hijri.style.display = 'none';
                        hijri_label.style.display = 'none';
                        birth_hijri.value = "";
                    }
                }
            });

            // Auto-suggest nation
            nation.addEventListener("blur", function () {
                const value = this.value.trim();
                const options = ["سعودي", "مصري", "يمني", "هندي", "باكستاني", "صومالي", "سوداني", "اماراتي", "اردني", "بنجلاديش", "سوريا", "اندونيسي", "لبناني"];
                const matched = options.find(opt => opt.startsWith(value));
                if (matched && value !== matched) {
                    if (confirm(`هل تقصد: ${matched}؟`)) {
                        this.value = matched;
                    }
                }
            });
        });

        // Enforce min value
        function enforceMinValue(inputId, minValue = 1) {
            const input = document.getElementById(inputId);
            if (!input) return;
            input.setAttribute("min", minValue);
            input.addEventListener("input", function () {
                if (parseFloat(this.value) < minValue) this.value = minValue;
            });
        }
        enforceMinValue('xn', 1);

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

        function validatePhoneNumber(phone) {
            return /^05\d{8}$/.test(phone.trim());
        }

        function validateHijri(input) {
            return /^1\d{7}$/.test(input.trim());
        }

        function birthCheck() {
            const idValue = document.getElementById("idSA").value.trim();
            const birthValue = document.getElementById("birth").value.trim();
            const firstDigit = parseInt(idValue[0], 10);
            if (isNaN(firstDigit)) return false;
            return firstDigit !== 1 || birthValue.length >= 8;
        }

        function ifPhone(phone) {
            return !phone || validatePhoneNumber(phone);
        }

        // Input validation feedback
        document.getElementById("idSA").addEventListener("input", function () {
            this.classList.toggle("valid-input", validateSAID(this.value));
            this.classList.toggle("invalid-input", !validateSAID(this.value));
        });

        document.getElementById("cust_name").addEventListener("input", function () {
            this.classList.toggle("valid-input", this.value.length >= 9);
            this.classList.toggle("invalid-input", this.value.length < 9);
        });

        document.getElementById("phone").addEventListener("input", function () {
            this.classList.toggle("valid-input", validatePhoneNumber(this.value));
            this.classList.toggle("invalid-input", !validatePhoneNumber(this.value));
        });

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

        ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(e => {
            dropArea.addEventListener(e, e => e.preventDefault(), false);
        });

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

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

        dropArea.addEventListener('drop', e => {
            const files = e.dataTransfer.files;
            if (files.length > 1) return alert('اختر ملفًا واحدًا فقط');
            fileInput.files = files;
            handleFiles(files);
        });

        dropArea.addEventListener('click', () => fileInput.click());
        fileInput.addEventListener('change', () => handleFiles(fileInput.files));

        function handleFiles(files) {
            const file = files[0];
            const maxSize = 5 * 1024 * 1024;

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

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

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

        // Show existing file
        const fileView = document.querySelector('.file-view');
        const custPhoto = document.getElementById('cust_photo').value;
        if (custPhoto) {
            fileView.innerHTML = '';
            const img = document.createElement('img');
            img.src = "../photo/customers/" + custPhoto;
            img.alt = "الصورة الحالية";
            img.height = 260;
            img.style.maxWidth = "100%";
            fileView.appendChild(img);
        }

        // Validate form
        function validateForm() {
            let isValid = true;
            document.querySelectorAll('.error-message').forEach(el => el.textContent = '');

            const fields = [
                { id: 'idSA', validator: validateSAID, msg: 'رقم الهوية: 10 أرقام تبدأ بـ 1 أو 2' },
                { id: 'cust_name', validator: v => v.length >= 9, msg: 'الاسم يجب أن يكون 9 أحرف على الأقل' },
                { id: 'nation', validator: v => v.length >= 2, msg: 'الجنسية مطلوبة' },
                { id: 'xn', validator: v => v >= 1, msg: 'نسخة رقم 1 على الأقل' },
                { id: 'address', validator: v => v.length >= 3, msg: 'العنوان مطلوب' },
                { id: 'license', validator: validateSAID, msg: 'رقم الرخصة غير صحيح' },
                { id: 'birth_hijri', validator: v => !document.getElementById('birth_hijri').style.display || validateHijri(v), msg: 'التاريخ الهجري 14220101' },
                { id: 'birth', validator: v => !document.getElementById('birth').style.display || v.length >= 8, msg: 'اختر تاريخ الميلاد' },
                { id: 'phone', validator: validatePhoneNumber, msg: 'رقم الجوال 10 أرقام ويبدأ بـ 05' },
                { id: 'lic_expire', validator: v => v.length >= 8, msg: 'حدد تاريخ انتهاء الرخصة' }
            ];

            fields.forEach(f => {
                const el = document.getElementById(f.id);
                const val = el.value.trim();
                if (!f.validator(val)) {
                    document.getElementById(f.id + '_msg').textContent = f.msg;
                    el.classList.add('is-invalid');
                    isValid = false;
                } else {
                    el.classList.remove('is-invalid');
                }
            });

            return isValid;
        }

        // Submit form
        document.getElementById('customerForm').addEventListener('submit', async function (e) {
            e.preventDefault();
            if (!validateForm()) return;

            const form = this;
            const btn = form.querySelector('button[type="submit"]');
            const original = btn.innerHTML;
            const msg = document.getElementById('msg');

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

            const formData = new FormData(form);

            try {
                const res = await fetch('customerController.php', {
                    method: 'PATCH',
                    body: formData
                });
                const result = await res.json();

                if (result.success) {
                    msg.innerHTML = `<div class="alert alert-success">${result.save_msg}</div>`;
                    setTimeout(() => window.location.href = 'customerFlow.php', 1500);
                } else {
                    msg.innerHTML = `<div class="alert alert-danger">${result.save_msg || 'خطأ في الحفظ'}</div>`;
                    handleServerErrors(result);
                }
            } catch (err) {
                msg.innerHTML = `<div class="alert alert-danger">فشل الاتصال بالخادم</div>`;
            } finally {
                btn.disabled = false;
                btn.innerHTML = original;
            }
        });

        function handleServerErrors(result) {
            ['idSA_msg', 'phone_msg'].forEach(id => {
                if (result[id]) document.getElementById(id).textContent = result[id];
            });
        }

        // Flatpickr
        const today = new Date();
        const lice_ex = new Date(today.setFullYear(today.getFullYear() + 10));
        const birthend = new Date(today.setFullYear(today.getFullYear() - 21));
        const birthstart = new Date(today.setFullYear(today.getFullYear() - 60));

        flatpickr("#id_Expire", {
            dateFormat: "Y-m-d",
            locale: "ar",
            defaultDate: new Date(),
            minDate: "today",
            maxDate: lice_ex
        });

        flatpickr("#birth", {
            dateFormat: "Y-m-d",
            locale: "ar",
            minDate: birthstart,
            maxData: birthend
        });

        flatpickr("#lic_expire", {
            dateFormat: "Y-m-d",
            locale: "ar",
            minDate: "today",
            maxDate: lice_ex
        });

        document.getElementById("minDate").innerText = "أصغر عمر: " + birthend.toLocaleDateString('ar-SA');
    </script>
</body>
</html>
<?php ob_end_flush(); ?>