class Sales{
    items = []
    total = []

    services = [];
async getDataService(){
    await $.ajax({
        url:"model/sales.php",
        type:"POST",
        dataType:"JSON",
        data:{
            type:"getAllService"
        },
        success:function(data){
            sales.services = data
        }
    });
}
async  drawSales() {
    sales.items = [];
    sales.total = [];
    sales.getDataService()
    await $('.mainBody').html(`
        <div class="container-fluid khedma-page sales-page" dir="rtl">
            <div class="row g-3">

                <!-- الفاتورة -->
                <div class="col-xl-4">
                    <div class="card shadow-sm border-0 bill-box">

                        <div class="card-header bg-white border-0 d-flex justify-content-between align-items-center">
                            <div>
                                <h5 class="mb-1 fw-bold">الفاتورة</h5>
                                <small class="text-muted">
                                    عدد الخدمات:
                                    <span class="text-primary countSales">0</span>
                                </small>
                            </div>
                        </div>

                        <div class="card-body">

                            <!-- قائمة الخدمات -->
                            <div class="sale-items-wrapper mb-3">
                                <div class="sale-items-box bodyListService">
                                    <!-- يتم ملؤها من sales.addItem -->
                                </div>
                            </div>

                            <!-- الخصم -->
                            <div class="mb-3">
                                <label class="form-label fw-bold small">خصم</label>
                                <input
                                    type="number"
                                    id="discount_sales"
                                    class="form-control form-control-sm"
                                    placeholder="قيمة الخصم"
                                    oninput="sales.discount()"
                                >
                            </div>

                            <!-- الإجمالي -->
                            <hr>
                            <div class="d-flex justify-content-between align-items-center mb-3 sale-total-line">
                                <span class="fw-bold">الإجمالي:</span>
                                <span class="total_sales fw-bold">
                                    0 EGP
                                </span>
                            </div>

                            <!-- بيانات العميل -->
                            <div class="mb-2">
                                <label class="form-label fw-bold small">بيانات العميل</label>
                                <div class="row g-2">
                                    <div class="col-6">
                                        <label class="form-label fw-bold small mb-1">الاسم</label>
                                        <input
                                            id="name_cus"
                                            type="text"
                                            class="form-control form-control-sm"
                                            placeholder=" "
                                        >
                                        <input id="id_cus" type="hidden" value="">
                                    </div>
                                    <div class="col-6">
                                        <label class="form-label fw-bold small mb-1">رقم الهاتف</label>
                                        <input
                                            id="phone_cus"
                                            type="text"
                                            class="form-control form-control-sm"
                                            placeholder=" "
                                            onchange="sales.searchCusByPhone()"
                                        >
                                    </div>
                                </div>
                            </div>

                            <!-- طرق الدفع -->
                            <div class="mb-2">
                                <label class="form-label fw-bold small mb-1">طرق الدفع</label>
                                <select id="type_paids" class="form-control form-control-sm"></select>
                            </div>

                            <!-- الملاحظات -->
                            <div class="mb-3">
                                <label class="form-label fw-bold small mb-1">الملاحظات</label>
                                <textarea id="info_paids" class="form-control form-control-sm" rows="2"></textarea>
                            </div>

                            <!-- الأزرار -->
                            <div class="mt-3 d-grid gap-2">
                                <button onclick="sales.endPay()" class="btn btn-success btn-sm">
                                    إتمام الدفع
                                </button>
                                <button onclick="sales.endSales()" class="btn btn-danger btn-sm">
                                    إلغاء
                                </button>
                            </div>

                        </div>
                    </div>
                </div>

                <!-- الأقسام + الخدمات -->
                <div class="col-xl-8">

                    <!-- الأقسام -->
                    <div class="card shadow-sm border-0 mb-3">
                        <div class="card-body">
                            <div class="d-flex justify-content-between align-items-center mb-2">
                                <h6 class="fw-bold mb-0">الأقسام</h6>
                            </div>
                            <div class="d-flex gap-2 flex-wrap bodyCat">
                                <!-- يتم ملؤها من drawCat -->
                            </div>
                        </div>
                    </div>

                    <!-- الخدمات -->
                    <div class="card shadow-sm border-0">
                        <div class="card-body">
                            <div class="row g-3 bodyService">
                                <!-- يتم ملؤها من drawService -->
                            </div>
                        </div>
                    </div>

                </div>

            </div>
        </div>
    `);

    await sales.drawCat();
    await sales.drawService(0);
    await sales.addTypeSales();
}

    async addTypeSales(){
        await $.ajax({
            url:"model/sales.php",
            type:"POST",
            dataType:"JSON",
            data:{
                type:"getTypePaids"
            },
            success:async function(data){
                if(data[0].id_type_paids == 0){
                console.log(data)

                    $('#type_paids').html(`<option value='0'>Cash</option>`)
                }else{
                    await $('#type_paids').html('')
                    for(var i = 0;i < data.length;i++){
                    await $('#type_paids').append(`
                            <option value="${data[i].id_type_paids}">${data[i].name_type_paids}</button>
                    `)
                }
                }
            }
        })
    }
async  drawCat() {
    await $.ajax({
        url: "model/sales.php",
        type: "POST",
        dataType: "JSON",
        data: { type: "getCat" },
        success: async function (data) {

            // زر "الكل" افتراضيًا Active
            await $('.bodyCat').html(`
                <button
                    class="btn btn-sm btn-primary rounded-pill sales-cat-btn active"
                    onclick="sales.drawService(0); $('.sales-cat-btn').removeClass('active'); $(this).addClass('active');"
                >
                    الكل
                </button>
            `);

            for (let i = 0; i < data.length; i++) {
                await $('.bodyCat').append(`
                    <button
                        class="btn btn-sm btn-outline-primary rounded-pill sales-cat-btn"
                        onclick="sales.drawService(${data[i].id_cat_service}); $('.sales-cat-btn').removeClass('active'); $(this).addClass('active');"
                    >
                        ${data[i].name_cat_service}
                    </button>
                `);
            }
        }
    });
}


async  drawService(id) {
    await $.ajax({
        url: "model/sales.php",
        type: "POST",
        dataType: "JSON",
        data: {
            type: "getService",
            id: id,
        },
        success: async function (data) {

            $('.bodyService').html(``);

            for (let i = 0; i < data.length; i++) {

                await $('.bodyService').append(`
                    <div class="col-md-4 col-sm-6">
                        <div class="card service-card h-100 p-3 shadow-sm">
                            <div class="service-card-header mb-2">
                                <h6 class="fw-bold mb-0 nameService_${data[i].id_service}">
                                    ${data[i].name_service}
                                </h6>
                            </div>

                            <div class="d-flex justify-content-between align-items-center">
                                <div class="d-flex align-items-center gap-2">
                                    <input type="hidden" id="priceItem_${data[i].id_service}" value="${data[i].price_service}" />
                                    <span class="badge price-badge">
                                        ${data[i].price_service} جنيه
                                    </span>
                                </div>

                                <button
                                    class="btn btn-sm btn-outline-success rounded-pill"
                                    onclick="sales.addItem(${data[i].id_service})"
                                >
                                    إضافة
                                </button>
                            </div>
                        </div>
                    </div>
                `);
            }
        }
    });
}

    
    async addItem(id){
        if(sales.items.includes(id)){
            sales.plusItem(id)
        }else{
            sales.items.push(id)
            $('.bodyListService').append(`
            <div class="item-row d-flex justify-content-between align-items-center item_${id}">
            <div>
              <div class="fw-bold">${$('.nameService_'+id).text()}</div>
              <div class="muted-small">${$('#priceItem_'+id).val()} جنيه </div>
            </div>
            <div class="d-flex gap-2 align-items-center">
              <button class="btn btn-sm btn-outline-primary" onclick="sales.plusItem(${id})">+</button>
              <input type="number" class="form-control form-control-sm countItem_${id}" style="width:60px" min="1" value="1" >
              <button class="btn btn-sm btn-outline-primary" onclick="sales.minItem(${id})">-</button>
              <button class="btn btn-sm btn-outline-danger" onclick="sales.deleteItem(${id})" >مسح</button>
            </div>
          </div>    
            `)

            await sales.getTotal()
        }
    }

    async plusItem(id){
        var countItem = Number($('.countItem_'+id).val())
        countItem++;
        await $('.countItem_'+id).val(countItem)
        await sales.getTotal()
    }
    async minItem(id){
        var countItem = Number($('.countItem_'+id).val())
        if(countItem > 1){
            countItem--;
            await $('.countItem_'+id).val(countItem)

            
        }else{
           await sales.deleteItem(id)
        }
        
        await sales.getTotal()
    }   

    async deleteItem(id){
        await $('.item_'+id).remove()
        let index = sales.items.indexOf(id);
        if (index !== -1) {
            await sales.items.splice(index, 1); 
        }

        await sales.getTotal()
    }
    async discount(){
        var discount_sales = Number($('#discount_sales').val())

        if(sales.getTotal() < discount_sales){
            $('#discount_sales').val(sales.getTotal())
        }

        sales.getTotal()
    }

    
    getTotal(){
        $('.countSales').text(sales.items.length);

        sales.total = 0;

        for (var i = 0; i < sales.items.length; i++) {

            let id = sales.items[i];
            let qty = Number($('.countItem_' + id).val());
            let price = sales.getPrice(id);

            sales.total += qty * price;
        }

        // قبل الخصم
        let saleTotal = sales.total;

        // الخصم
        let discount_sales = Number($('#discount_sales').val() || 0);

        sales.total = sales.total - discount_sales;

        $('.total_sales').text(sales.total + " EGP");

        return saleTotal;

    }

    async searchCusByPhone(){
        var phone = $('#phone_cus').val();
            await $.ajax({
            url:"model/sales.php",
            type:"POST",
            dataType:"JSON",
            data:{
                type:"getPhone",
                phone:phone
            },
            success:async function(data){
                if(data.num == 0){
                   new sweetAlert("العميل غير موجود","","error")
                   $('#name_cus').val('')
                }else{
                   new sweetAlert("العميل موجود","","success")
                    $('#name_cus').val(data.cus.name_cus)
                    $('#id_cus').val(data.cus.id_cus)
                }
            }
        })
    }

    async endPay(){
        if(sales.items.length == 0){
            new sweetAlert("يجب اضافة الخدمات","","")
            return 0;
        }

        sales.sendHeaderSales()

    }

    async sendHeaderSales(){
        await $.ajax({
            url:"model/sales.php",
            type:"POST",
            dataType:"JSON",
            data:{
                type:"sendHeader",
                id_cus:$('#id_cus').val(),
                name_cus:$('#name_cus').val(),
                phone_cus:$('#phone_cus').val(),
                total_befor_discount:parseFloat(sales.total + Number($('#discount_sales').val())),
                discount:Number($('#discount_sales').val()),
                total:sales.total,
                id_emp:main.idEmp,
                counts:sales.items.length,
                typePaid:$('#type_paids').val(),
                info:$('#info_paids').val()
            },
            success:async function (data) {
                sales.sendFooterSales(data.lastId)
            }
        })
    }

    async sendFooterSales(id_sales_header){
        var lastedArray = []
        for(var i = 0; i < sales.items.length;i++){
            var price = $('#priceItem_'+sales.items[i]).val()
            var id = sales.items[i];
            var count = $('.countItem_'+sales.items[i]).val()
            lastedArray.push([id,price,count])
        }

        await $.ajax({
            url:"model/sales.php",
            type:"POST",
            dataType:"JSON",
            data:{
                type:"sendFooter",
                id:id_sales_header,
                lastedArray:lastedArray
            },
            success:async function (data) {
                sales.pushInv(id_sales_header)
                sales.endSales()
            }
        })
    }


    async endSales(){
        new sweetAlert("تم ","","")
        sales.drawSales()
        sales.items = []
        sales.total = []
    }



    async pushInv(idInv){
        await $.ajax({
            url:"model/sales.php",
            type:"POST",
            dataType:"JSON",
            data:{
                type:"getInv",
                id:idInv,
            },
            success:async function (data) {
                console.log(data)
               $('#tbodyInv').html('')
               $('#nameCusInv').text(data[0].name_cus)
               $('#idInv').text(data[0].id_sales_header)
               $('#nameEmp').text(data[0].name_emp)
               $('#dateInv').text(data[0].time_add)
               $('#totalWithoutDiscountInv').text(data[0].total_befor_discount)
               $('#discountInv').text(parseFloat(Number(data[0].total_befor_discount) - Number(data[0].total)))
               $('#totalInv').text(data[0].total)

               for(var i = 0;i< data.length;i++){
                $('#tbodyInv').append(`
                    <tr>
                    <td>${i+1}</td>
                    <td>${data[i].name_service}</td>
                    <td>${data[i].count_pro}</td>
                    <td>${data[i].price_pro}</td>
                    <td>${data[i].count_pro * data[i].price_pro}</td>
                    </tr>
                `)

               }
               $('#tbodyInv').append(`
                            <tr class="total-row">
              <td colspan="4" class="text-right">الإجمالي قبل الخصم</td>
              <td id="totalWithoutDiscountInv">${data[0].total_befor_discount}</td>
            </tr>
            <tr class="total-row">
              <td colspan="4" class="text-right">الخصم</td>
              <td id="discountInv">${parseFloat(Number(data[0].total_befor_discount) - Number(data[0].total))}</td>
            </tr>
            <tr class="total-row">
              <td colspan="4" class="text-right">الإجمالي النهائي</td>
              <td id="totalInv">${data[0].total}</td>
            </tr>
                `)
                $('#invoiceModal').modal('show')

            }
        })
    }

    async deleteInv(id){
        var x = confirm("هل تريد الحذف")
        if(x){
            await $.ajax({
                url:"model/sales.php",
                type:"POST",
                dataType:"JSON",
                data:{
                    type:"deleteInv",
                    id:id,
                },
                success:async function (data) {
                    main.updatePage()
                }
            })
        }
    }
}
var sales = new Sales()

sales.getPrice = function(id) {
    id = String(id); 

    const item = sales.services.find(s => s.id_service == id);
    return item ? Number(item.price_service) : 0;
}
