class Main{
    idTypePage = 0;
    dataResponse = [];
    url = "model/class.php";
    isSaving = false;
    dataCompany = []
    idEmp = 0;
    codeUser = "un";

    async chckLogin(){
        fetch("check_session.php")
        .then(res => res.text())
        .then(response => {
            if (response === "expired") {
                window.location.href = "login.php";
            }
        });
    }
    async getDateToday(){
        await $.ajax({
            url:main.url,
            type:"POST",
            dataType:"JSON",
            data:{
                type:"getDateToday",
                page:"getDateToday",
                dataArray:[0],
            },
            success:async function(data){
                rebort.start = await data.dateToday
                rebort.end = await data.dateToday
            }
        })
    }

    async getCount(type,page,dataArray){
        await $.ajax({
            url:main.url,
            type:"POST",
            dataType:"JSON",
            data:{
                type:type,
                page:page,
                dataArray:dataArray,
            },
            success:async function(data){
                main.dataResponse = await data
            }
        })
    }
    async getData(type,page,id = 0){
        await $.ajax({
            url:main.url,
            type:"POST",
            dataType:"JSON",
            data:{
                type:type,
                page:page,
                idTypePage:id,
            },
            success:async function(data){
                //alert("a")
                main.dataResponse = await data
            }
        })
    }

    async sendData(type,id,dataArray){
        $('#modalPage').modal('hide')
        if(main.isSaving){
            onsole.log("error : dublacter data")
            return
        }
        console.log("dataarray : ",dataArray)

        main.isSaving = true
        $.ajax({
            url:main.url,
            type:"POST",
            dataType:"JSON",
            data:{
                type:type,
                idTypePage:id,
                dataArray:dataArray
            },
            success:async function(data){
                main.isSaving = false
                //alert("a")
                console.log(data)
                main.updatePage()
            },
            // complete:function(data){
            //     console.log(data.a)
            // }
        })
    }
    async sendDataStudent(type,id,dataArray){
        $('#modalPage').modal('hide')
        if(main.isSaving){
            onsole.log("error : dublacter data")
            return
        }
        console.log("dataarray : ",dataArray)

        main.isSaving = true
        $.ajax({
            url:main.url,
            type:"POST",
            dataType:"JSON",
            data:{
                type:type,
                idTypePage:id,
                dataArray:dataArray
            },
            success:async function(data){
                main.isSaving = false
                //alert("a")
                console.log(data)
                // main.updatePage()
            },
            // complete:function(data){
            //     console.log(data.a)
            // }
        })
    }
async  drawTable(dataHead, urlData, addData, nameTable = "Data Table", addation = "", dataTableSend = []) {
    main.chckLogin()
    // زر الإضافة
    let btnAddHtml = "";
    if (addData && addData !== "") {
        btnAddHtml = `
            <button class="btn btn-primary btn-sm" type="button" onclick="${addData}">
                + إضافة ${nameTable}
            </button>
        `;
    }

    const txt = `
        <div class="container-fluid khedma-page" dir="rtl">

            <!-- عنوان الصفحة + زر إضافة -->
            <div class="d-flex justify-content-between align-items-center mb-3">
                <div>
                    <h5 class="page-title mb-1">${nameTable}</h5>
                    <p class="page-subtitle mb-0">إدارة ${nameTable} داخل النظام</p>
                </div>
                ${btnAddHtml}
            </div>

            <!-- كارت عدد السجلات -->
            <div class="row mb-3">
                <div class="col-md-3 ms-auto">
                    <div class="card stat-card shadow-sm border-0">
                        <div class="card-body d-flex justify-content-between align-items-center">
                            <div>
                                <div class="stat-label">عدد السجلات</div>
                                <div class="stat-value countStudent">0</div>
                            </div>
                            <div class="stat-icon">
                                <i class="fas fa-list-ul"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            ${addation || ""}

            <!-- الكارت الرئيسي للجدول -->
            <div class="card shadow-sm border-0 khedma-table-card">
                <div class="card-header bg-white border-0 pb-2">
                    <div class="d-flex justify-content-between align-items-center flex-wrap gap-2">
                        <div>
                            <h6 class="mb-1 table-title">قائمة ${nameTable}</h6>
                            <span class="small text-muted">يمكنك البحث والتصدير من الجدول بالأسفل</span>
                        </div>

                        <!-- هنا هننقل أدوات DataTables -->
                        <div class="d-flex align-items-center gap-3 flex-wrap khedma-dt-toolbar">
                            <div class="khedma-dt-buttons"></div>
                            <div class="khedma-dt-search"></div>
                        </div>
                    </div>
                </div>

                <div class="card-body pt-2">
                    <div class="table-responsive">
                        <table class="table table-hover align-middle" id="dataTable" width="100%" cellspacing="0">
                            <thead class="table-light">
                                <tr>
                                    ${dataHead}
                                </tr>
                            </thead>
                            <tbody></tbody>
                        </table>
                    </div>
                </div>
            </div>

        </div>
    `;

    $('.mainBody').html(txt);

    // تهيئة DataTable
    const dataTable = $('#dataTable').DataTable({

        columnDefs: [
            {
                className: 'mdl-data-table__cell--non-numeric'
            }
        ],

        processing: true,
        serverSide: true,
        order: [[0, "desc"]],

        ajax: {
            url: urlData,
            type: "post",
            dataType: "JSON",
            data: {
                dataTableSend: dataTableSend
            },
            error: function () {
                console.error("Error loading DataTable");
            }
        },

        // نخلي العناصر تتولد عادي وبعدين ننقلها للهيدر
        dom: 'Bfrtip',

buttons: [
    { extend: 'copy',  text: 'نسخ',   className: 'btn btn-sm khedma-dt-btn' },
    { extend: 'csv',   text: 'CSV',   className: 'btn btn-sm khedma-dt-btn' },
    { extend: 'excel', text: 'Excel', className: 'btn btn-sm khedma-dt-btn' },
    { extend: 'print', text: 'طباعة', className: 'btn btn-sm khedma-dt-btn' }
]
,

        language: {
            search: "بحث:",
            lengthMenu: "إظهار _MENU_ سجل",
            info: "إظهار _START_ إلى _END_ من أصل _TOTAL_ سجل",
            infoEmpty: "لا توجد سجلات",
            infoFiltered: "(مصفاة من إجمالي _MAX_ سجل)",
            paginate: {
                previous: "السابق",
                next: "التالي"
            },
            zeroRecords: "لا توجد نتائج مطابقة"
        },

        initComplete: function () {
            // ننقل أزرار التصدير لمكانها في هيدر الكارت
            const $wrapper = $('#dataTable').closest('.dataTables_wrapper');
            $wrapper.find('.dt-buttons').appendTo('.khedma-dt-buttons');
            $wrapper.find('.dataTables_filter').appendTo('.khedma-dt-search');

            // تعديل بسيط على search عشان يبقى شكله bootstrap
            const $filter = $wrapper.find('.dataTables_filter');
            $filter.addClass('mb-0');
            $filter.find('label').addClass('d-flex align-items-center gap-2 mb-0');
            $filter.find('input')
                .addClass('form-control form-control-sm')
                .attr('placeholder', 'ابحث في الجدول...');
        }
    });
    $('#dataTable').DataTable();
    dataTable.on('draw.dt', function () {
            var count = dataTable.rows({ search: 'applied' }).nodes().length;
            $('.countStudent').text(count);
     });

    // تقدر هنا بعد ما الداتا ترجع من السيرفر تحدث countStudent بعدد السجلات (لو عايز)
    // $('.countStudent').text(dataTable.data().count());
}




    async updatePage(){
        $('.modal').modal('hide')
        $('#dataTable').DataTable().ajax.reload()
    }


    async deleteData(nameTable,idRow ){
        if(nameTable == "emp" || nameTable == "job"){
            const result = await powers.checkOpenPage("emp");
            if (!result) return;
        }
        if(nameTable == "exp" || 'inp'){
            const result = await powers.checkOpenPage("exp");
            if (!result) return;
        }
        if(nameTable == "pro" || nameTable == "cat"){
            const result = await powers.checkOpenPage("products");
            if (!result) return;
        }
        if(nameTable == "student"){
            const result = await powers.checkOpenPage("students");
            if (!result) return;
        }
        if(nameTable == "subscription"){
            const result = await powers.checkOpenPage("subscription");
            if (!result) return;
        }
        if(nameTable == "subject" || nameTable == "teacher" ||  nameTable == "year" ||  nameTable == "date_addation_subscription" ){
            const result = await powers.checkOpenPage("mainData");
            if (!result) return;
        }
        this.sendData("delete",idRow,nameTable)
    }


    async getDataCompany(){
        await main.getData("getDataCompany","",0);
        main.dataCompany =  main.dataResponse

        $('.nameCompany').text(main.dataResponse[0].name_company)


        if(main.dataCompany[0].is_logo == 1){
            $('#inv_logo').attr("src",main.dataCompany[0].logo_company)
        }else{
             $('#inv_logo').hide()
        }

        if(main.dataCompany[0].is_mail == 1){
            $('#mail').text(main.dataCompany[0].email_company)
        }else{
             $('.isMail').attr("display","none")
        }
        if(main.dataCompany[0].is_name == 1){
            $('#name').text(main.dataCompany[0].name_company)
        }else{
             $('.isName').attr("display","none")
        }
        if(main.dataCompany[0].is_address == 1){
            $('#address').text(main.dataCompany[0].name_company)
        }else{
             $('.isAddress').attr("display","none")
        }

        if(main.dataCompany[0].is_phone == 1){
            $('#phone').text(main.dataCompany[0].phone_company)
        }else{
             $('.isPhone').attr("display","none")
        }

        $('#textHeader').text(main.dataCompany[0].msg)
    }
}

// const url =
// "https://www.josms.net/SMSServices/Clients/Prof/SingleSMS3/SMSService.asmx/SendSMS";
// const headers = {
// "Content-Type": "application/x-www-form-urlencoded",
// "Authorization": "fZ1kC1kI7kV2cY2n" // Replace withactual token
// };
// const body = new URLSearchParams({
// "numbers": "00962775508327",
// "senderid": "Zalmaty.Co",
// "msgs": `<DocumentElement>
// <msg>
// <SMS_ID>1</SMS_ID>

// <SMS_BODY>TEST MESSAGE 1 نص

// عربي>/SMS_BODY>
// <MOBILE_PHONE>00962775508327</MOBILE_PHONE>
// <BULK_ID>1</BULK_ID>
// </msg>
// <msg>
// </DocumentElement>`
// });
// // Send the AJAX request
// fetch(url, {
// method: "POST",
// headers: headers,
// body: body

// }).then(response => response.text()) 

var main = new Main()


