<?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'];

if (!isset($_SESSION)) {
}



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


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(247, 233, 233);
            border-color: rgb(185, 26, 26);
        }

        label {
            float: left;
        }

        .red_text {
            color: rgb(160, 29, 29);

        }
    </style>
    <div class="container-full">
        <div class="card shadow bg-dark-subtle ">
            <div class="card-header bg-primary-subtle text-black">
                <h3>تعديل بيانات شركة</h3>
            </div>
            <br />
            <br />
            <div class="card-body">
                <input type="hidden" id="expire" value="<?= $cust['id_Expire'] ?>">
                <input type="hidden" id="cust_photo" value="<?= $cust['cust_photo'] ?>">
                <input type="hidden" id="cust_id" value="<?= $cust['cust_id'] ?>">
                <form id="companyForm" method="PATCH" enctype="multipart/form-data">
                    <div class="row">
                        <div class="text-center" id="msg"></div>
                    </div>
                    <div class="row">
                        <div class="col-md-8 mb-6">
                            <div class="row">
                                <div class="col-md-2 mb-3">
                                    <label for="idSA" class="form-label">رقم السجل التجاري</label>
                                </div>
                                <div class="col-md-3 mb-3">
                                    <input type="number" class="form-control req bold_num " id="idSA" name="idSA" pattern="\d{10}" placeholder="رقم السجل التجاري" value="<?= $cust['idSA'] ?>" required>
                                    <div class="red_text" id="idSA_msg"></div>
                                </div>
                                <div class="col-md-4 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>
                            </div>
                            <div class="row">
                                <div class="col-md-2 mb-3">
                                    <label for="cust_name" class="form-label">اسم الشركة</label>
                                </div>
                                <div class="col-md-5 mb-3">
                                    <input type="text" class="form-control bold_num req" id="cust_name" name="cust_name" value="<?= $cust['cust_name'] ?>" required>
                                    <div class="red_text" id="cust_name_msg"></div>
                                </div>
                                <div class="col-md-2 mb-3">
                                    <label for="cust_vat" class="form-label">الرقم الضريبي</label>
                                </div>
                                <div class="col-md-3 mb-3">
                                    <input type="number" class="form-control bold_num req" id="cust_vat" name="cust_vat" value="<?= $cust['cust_vat'] ?>" pattern="\d{15}" required>
                                    <div class="red_text" id="cust_vat_msg"></div>
                                </div>
                            </div>

                            <div class="row">
                                <div class="col-md-2 mb-3">
                                    <label for="CityName" class="form-label">المدينة</label>
                                </div>
                                <div class="col-md-5 mb-3">
                                    <input type="text" class="form-control bold_num req" id="CityName" name="CityName" value="<?= $cust['CityName'] ?>" required>
                                    <div class="red_text" id="CityName_msg"></div>
                                </div>
                                <div class="col-md-2 mb-3">
                                    <label for="SubDivisionName" class="form-label">الحي</label>
                                </div>
                                <div class="col-md-3 mb-3">
                                    <input type="text" class="form-control bold_num req" id="SubDivisionName" name="SubDivisionName" value="<?= $cust['SubDivisionName'] ?>" required>
                                    <div class="red_text" id="SubDivisionName_msg"></div>
                                </div>
                            </div>

                            <div class="row">
                                <div class="col-md-2 mb-3">
                                    <label for="StreetName" class="form-label">اسم الشارع</label>
                                </div>
                                <div class="col-md-5 mb-3">
                                    <input type="text" class="form-control bold_num req" id="StreetName" name="StreetName" value="<?= $cust['StreetName'] ?>" required placeholder="اسم الشارع">
                                    <div class="red_text" id="StreetName_msg"></div>
                                </div>
                                <div class="col-md-2 mb-3">
                                    <label for="BuildingNumber" class="form-label">رقم المبنى</label>
                                </div>
                                <div class="col-md-3 mb-3">
                                    <input type="text" class="form-control bold_num req" id="BuildingNumber" name="BuildingNumber" value="<?= $cust['BuildingNumber'] ?>" required placeholder="0000">
                                    <div class="red_text" id="BuildingNumber_msg"></div>
                                </div>
                            </div>

                            <div class="row">
                                <div class="col-md-2 mb-3">
                                    <label for="PlotIdentification" class="form-label">رقم الوحدة</label>
                                </div>
                                <div class="col-md-2 mb-3">
                                    <input type="text" class="form-control bold_num req" id="PlotIdentification" name="PlotIdentification" value="<?= $cust['PlotIdentification'] ?>" placeholder="رقم الوحدة داخل العقار" required>
                                    <div class="red_text" id="PlotIdentification_msg"></div>
                                </div>
                                <div class="col-md-5 mb-3">
                                    <label for="PostalNumber" class="form-label">الرقم البريدي</label>
                                </div>
                                <div class="col-md-3 mb-3">
                                    <input type="number" class="form-control bold_num req" id="PostalNumber" name="PostalNumber" value="<?= $cust['PostalNumber'] ?>" required placeholder="00000">
                                    <div class="red_text" id="PostalNumber_msg"></div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4 mb-6">
                            <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="phone" style="float: left;" class="form-label">تليفون الشركة</label>
                                </div>
                                <div class="col-md-5 mb-3">
                                    <input type="number" class="form-control bold_num  req" id="phone" name="phone" value="<?= $cust['phone'] ?>" placeholder="رقم تليفون الشركة">
                                    <div class="red_text" id="phone_msg"></div>
                                </div>
                                <div class="col-md-5 mb-3">
                                    <input type="number" class="form-control bold_num" id="phone2" name="phone2" value="<?= $cust['phone2'] ?>" placeholder=" تليفون 2 ">
                                    <div class="red_text" id="phone2_msg"></div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-2 mb-3">
                                    <label for="dgree" class="form-label">الدرجة</label>
                                </div>
                                <div class="col-md-3 mb-3">
                                    <input type="number" class="form-control bold_num" id="dgree" name="dgree" max="100" min="1" value="<?= $cust['dgree'] ?>" placeholder="تقييم">
                                    <div class="red_text" id="dgree_msg"></div>
                                </div>
                            </div>
                            <br />
                            <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" value="<?= $cust['working_woner'] ?>" placeholder="اسم الشخص المسؤول">
                                </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" value="<?= $cust['w_phone'] ?>" placeholder="جوال المسؤول">
                                    <div class="red_text" id="w_phone_msg"></div>
                                </div>
                                <div class="col-md-5 mb-3">
                                    <input type="number" class="form-control bold_num " id="w_phone2" name="w_phone2" value="<?= $cust['w_phone2'] ?>" placeholder="جوال المسؤول">
                                    <div class="red_text" 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 class="row">
                                <div class="col-md-12 mb-3">
                                    <button type="submit" class="btn btn-primary w-100" id="save_btn" name="save_btn">حفظ البيانات</button>
                                </div>
                            </div>

                        </div>
                        </form>
                        <div class="col-md-4 mb-3">
                        <form id="fileUpload" method="POST" enctype="multipart/form-data">
                        
                            <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" id="file_msg"></div>
                                </div>
                                <div class="row">
                <div class="col-md-12 mb-3">
                    <button type="button" class="btn btn-primary w-100" id="file_btn" name="file_btn">حفظ الملف</button>
                </div>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
    </div>

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

        // Show fileview
        fileView.innerHTML = '';

        if ((cust_photo.endsWith("jpg") || (cust_photo.endsWith("jpeg")))) {
            const img = document.createElement('img');
            img.src = "../photo/customers/" + cust_photo;
            img.alt = "جاري التحميل ...";
            img.height = 260;
            fileView.appendChild(img);
        } else 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);
        }

        // 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) {
            ([...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;
        }
        // save data
        document.getElementById('companyForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            // Get form elements
            const msg = document.getElementById('msg');
            const cust_id = document.getElementById('cust_id').value;
            const idSA = document.getElementById('idSA').value;
            const id_Expire = document.getElementById('id_Expire').value;
            const cust_name = document.getElementById('cust_name').value;
            const dgree = document.getElementById('dgree').value;
            const cust_vat = document.getElementById('cust_vat').value;
            const phone = document.getElementById('phone').value;
            const phone2 = document.getElementById('phone2').value;
            const CityName = document.getElementById('CityName').value;
            const SubDivisionName = document.getElementById('SubDivisionName').value;
            const StreetName = document.getElementById('StreetName').value;
            const BuildingNumber = document.getElementById('BuildingNumber').value;
            const PlotIdentification = document.getElementById('PlotIdentification').value;
            const PostalNumber = document.getElementById('PostalNumber').value;
            const working_woner = document.getElementById('working_woner').value;
            const w_phone = document.getElementById('w_phone').value;
            const w_phone2 = document.getElementById('w_phone2').value;
            const comm = document.getElementById('comm').value;
            // message
            const idSA_msg = document.getElementById('idSA_msg');
            const cust_name_msg = document.getElementById('cust_name_msg');
            const cust_vat_msg = document.getElementById('cust_vat_msg');
            const phone_msg = document.getElementById('phone_msg');
            const phone2_msg = document.getElementById('phone2_msg');
            const w_phone_msg = document.getElementById('w_phone_msg');
            const w_phone2_msg = document.getElementById('w_phone2_msg');
            const CityName_msg = document.getElementById('CityName_msg');
            const SubDivisionName_msg = document.getElementById('SubDivisionName_msg');
            const StreetName_msg = document.getElementById('StreetName_msg');
            const BuildingNumber_msg = document.getElementById('BuildingNumber_msg');
            const PlotIdentification_msg = document.getElementById('PlotIdentification_msg');
            const PostalNumber_msg = document.getElementById('PostalNumber_msg');
            const file_msg = document.getElementById('file_msg');

            function validate() {
                var err = 0;
                idSA_msg.textContent = "";
                cust_name_msg.textContent = "";
                cust_vat_msg.textContent = "";
                phone_msg.textContent = "";
                phone2_msg.textContent = "";
                w_phone_msg.textContent = "";
                w_phone2_msg.textContent = "";
                CityName_msg.textContent = "";
                SubDivisionName_msg.textContent = "";
                StreetName_msg.textContent = "";
                BuildingNumber_msg.textContent = "";
                PlotIdentification_msg.textContent = "";
                PostalNumber_msg.textContent = "";


                if (idSA.length < 10) {
                    idSA_msg.textContent = 'فضلا تأكد من رقم الهوية';
                    err++;
                }
                if (cust_name.length < 5) {
                    cust_name_msg.textContent = 'فضلا تأكد من إسم المستأجر';
                    err++;
                }
                if (cust_vat.length != 15) {
                    cust_vat_msg.textContent = 'فضلا تأكد الرقم الضريبي';
                    err++;
                }
                if (phone.length != 10) {
                    phone_msg.textContent = 'فضلا سجل رقم الجوال 10 أرقام';
                    err++;
                }
                if (phone2 != "") {
                    if (phone2.length != 10) {
                        phone2_msg.textContent = 'فضلا سجل رقم الجوال 10 أرقام';
                        err++;
                    }
                }
                if (w_phone != "") {
                    if (w_phone.length != 10) {
                        w_phone_msg.textContent = 'فضلا سجل رقم الجوال 10 أرقام';
                        err++;
                    }
                }
                if (w_phone2 != "") {
                    if (w_phone2.length != 10) {
                        w_phone2_msg.textContent = 'فضلا سجل رقم الجوال 10 أرقام';
                        err++;
                    }
                }

                if (CityName.length < 3) {
                    CityName_msg.textContent = 'فضلا تأكد من اسم المدينة';
                    err++;
                }
                if (SubDivisionName.length < 3) {
                    SubDivisionName_msg.textContent = 'فضلا تأكد من اسم الحي';
                    err++;
                }
                if (StreetName.length < 3) {
                    StreetName_msg.textContent = 'فضلا تأكد من اسم الشارع';
                    err++;
                }
                if (BuildingNumber.length != 4) {
                    BuildingNumber_msg.textContent = 'رقم العقار';
                    err++;
                }
                if (PlotIdentification.length < 1) {
                    PlotIdentification_msg.textContent = 'تأكد من رقم الوحدة داخل العقار';
                    err++;
                }
                if (PostalNumber.length != 5) {
                    PostalNumber_msg.textContent = 'فضلا تأكد من الرقم البريدي';
                    err++;
                }

                return err;

            }

            if (validate() > 0) {
                // alert(err);
                exit();
            }

            const patchData = {};
            if (idSA) patchData.idSA = idSA;
            if (id_Expire) patchData.id_Expire = id_Expire;
            if (cust_name) patchData.cust_name = cust_name;
            if (dgree) patchData.dgree = dgree;
            if (cust_vat) patchData.cust_vat = cust_vat;
            if (phone) patchData.phone = phone;
            if (phone2) patchData.phone2 = phone2;
            if (CityName) patchData.CityName = CityName;
            if (SubDivisionName) patchData.SubDivisionName = SubDivisionName;

            if (StreetName) patchData.StreetName = StreetName;
            if (BuildingNumber) patchData.BuildingNumber = BuildingNumber;
            if (PlotIdentification) patchData.PlotIdentification = PlotIdentification;
            if (PostalNumber) patchData.PostalNumber = PostalNumber;
            if (working_woner) patchData.working_woner = working_woner;
            if (w_phone) patchData.w_phone = w_phone;
            if (w_phone2) patchData.w_phone2 = w_phone2;
            if (comm) patchData.comm = comm;
            patchData.cust_id = cust_id;

            fetch('companyControl.php', {
                    method: 'PATCH',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        ...patchData
                    })
                })
                .then(response => response.json())
                .then(data => {
                        var result = JSON.stringify(data);
                        var result = JSON.parse(result);
                        msg.innerHTML = result.save_msg;
                        idSA_msg.textContent = result.idSA_msg;
                        cust_name_msg.textContent = result.cust_name_msg;
                        cust_vat_msg.textContent = result.cust_vat_msg;
                        phone_msg.textContent = result.phone_msg;
                        phone2_msg.textContent = result.phone2_msg;
                        w_phone_msg.textContent = result.w_phone_msg;
                        w_phone2_msg.textContent = result.w_phone2_msg;
                        CityName_msg.textContent = result.CityName_msg;
                        SubDivisionName_msg.textContent = result.SubDivisionName_msg;
                        StreetName_msg.textContent = result.StreetName_msg;
                        BuildingNumber_msg.textContent = result.BuildingNumber_msg;
                        PlotIdentification_msg.textContent = result.PlotIdentification_msg;
                        PostalNumber_msg.textContent = result.PostalNumber_msg;
                    }
                )
                    .catch(error => {
                        // document.getElementById('responseMessage').innerText = 'Error: ' + error.message;
                        // console.log(data.cust_id);
                        console.log(error.message);
                        // var db = JSON.stringify(error);
                        // var db = JSON.parse(db);
                        // console.log(db);
                    }
                );
                
                    setTimeout(function() {
                var alertElement = document.getElementById("successAlert");
                var alert = new bootstrap.Alert(alertElement);
                alert.close();
                }, 3000);
          
        });
  
        

document.getElementById('file_btn').addEventListener('click', async (e) => {
            e.preventDefault();
            const cust_id = document.getElementById('cust_id').value;
            const formData = new FormData();

            formData.append('file', fileInput.files[0]);

            formData.append('cust_id', cust_id);
            formData.append('action', 'upload');
            // try {
            const response = await fetch('custFile.php', {
                method: 'POST',
                body: formData,
            });
            const result = await response.json();
            if (result.success) {
                // alert(result.save_msg);
                msg.textContent = result.save_msg ;
                window.location.href = 'success.html';
            } else {
                msg.textContent = result.save_msg ;
            }
        // }
        //  catch (error) {
        //     console.error('Error:', error);
        //     alert('An error occurred while uploading the file.');
        // }
        });

        // }
    </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>
        const today = new Date();

        // Calculate the date 5 years from today
        const fiveYearsFromNow = new Date(today);
        fiveYearsFromNow.setFullYear(today.getFullYear() + 5);
        const expire = new Date(today);
        expire.setMonth(today.getMonth() + 3)
        // const expire = document.getElementById('expire').value;
        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: fiveYearsFromNow, // Set maximum selectable date
        });
    </script>

</body>

</html>
<?php
ob_end_flush();
?>