<html lang="en">

<%- include('../partials/header.ejs'); %>

  <body>

    <div class="container-scroller" id="app">

      <%- include ('../partials/nav.ejs') %>


        <div class="container-fluid page-body-wrapper">

          <%- include ('../partials/theme-setting') %>


            <%- include('../partials/sidebar.ejs') %>

              <div class="main-panel">
                <div class="content-wrapper p-0">

                    <div class="welcome-message">
                        <div class="d-lg-flex justify-content-between align-items-center">
                            <div class="pl-4">
                                <h2 class="text-white font-weight-bold mb-1">RWP Report</h2>
                            </div>
                        </div>
                    </div>
                    
                    <!-- form -->
                    <div class="content-wrapper">
                        <div class="card">
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-12">
                                        <div class="row">
                                            <div class="col-md-4">
                                                <div class="form-group">
                                                    <label for="exampleFormControlSelect1">Select Shop</label>
                                                    <select class="form-control" id="exampleFormControlSelect1" v-model="selectedShop">
                                                        <option v-for="shop in shopList" :value="shop.id">
                                                          {{shop.name}}
                                                        </option>
                                                    </select>
                                                </div>
                                            </div>

                                            <div class="col-md-4">
                                                <div class="form-group">
                                                    <label for="exampleFormControlSelect1">Start Date</label>
                                                    <input type="date" class="form-control" placeholder="Select Start Date" v-model="startDate">
                                                </div>
                                            </div>

                                            <div class="col-md-4">
                                                <div class="form-group">
                                                    <label for="exampleFormControlSelect1">End Date</label>
                                                    <input type="date" class="form-control" placeholder="Select End Date" v-model="endDate">
                                                </div>
                                            </div>
                                            <div class="col-12">
                                                <button class="btn btn-primary" @click="getVouchers">Search</button>
                                            </div>

                                        </div>
                                    </div>
                                    <div class="col-12 text-lg-right">
                                        <button class="btn btn-primary" @click="downloadPDF" v-if="tblData?.length > 0">Download Report</button>
                                    </div>
                                    <div class="col-12">
                                        <div class="table-responsive">
                                            <table id="order-listing" class="table">
                                                <thead>
                                                    <tr>
                                                        <th>Invoice</th>
                                                        <th>Shop Name</th>
                                                        <th>RWP Date</th>
                                                        <th>Article Qty</th>
                                                        <th>RWP Qty</th>
                                                        <th>RWP Amount</th>
                                                        <!-- <th>NCA Amount</th> -->
                                                        <!-- <th>Discount</th> -->
                                                        <th>Sub. Total</th>
                                                        <th>Total</th>
                                                        <th>Actions</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <tr>
                                                       <tr v-for="item,index in tblData" :key="item.id">
                                                        <td>{{item.inv_no}}</td>
                                                        <td>{{item.shop_name}}</td>
                                                        <td>{{ moment(item.receiving_date).format('DD/MM/YYYY') }}</td>
                                                        <td>{{item.artical_qty}}</td>
                                                        <td>{{item.rwp}}</td>
                                                        <td>{{item.rwp_amount}}</td>
                                                        <!-- <td>{{item.nca_amount}}</td> -->
                                                        <!-- <td>{{item.discount}}</td> -->
                                                        <td>{{item.sub_total}}</td>
                                                        <td>{{item.total}}</td>
                                                        <td>
                                                            <button class="btn btn-primary" @click="getVoucher(item.invoice_id)">View</button>
                                                        </td>
                                                    </tr>
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                    
                                    <div class="col-12 mt-5"> 
                                        <div class="container-fluid mt-5 w-100" v-if="amount?.total">
                                            <p class="text-right">Total RWP Qty: {{amount.totalRwp}} </p> 
                                            <p class="text-right">Total RWP Amount: {{amount.totalRwpAmount}} TK </p> 
                                            <p class="text-right">Total quantity: {{amount?.quantity}} </p>
                                            <p class="text-right">Sub Total  : {{amount?.subTotal}} TK</p> 
                                            <h4 class="text-right mb-5">Total : {{amount?.total}} TK</h4> <hr>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
                <%- include ('../partials/footer.ejs'); %>

              </div>
        </div>
    </div>

    <%- include('../partials/footer_js.ejs'); %>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.12/dist/vue.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.12"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.1/axios.min.js"
      integrity="sha512-bZS47S7sPOxkjU/4Bt0zrhEtWx0y0CRkhEp8IckzK+ltifIIE9EMIMTuT/mEzoIMewUINruDBIR/jJnbguonqQ=="
      crossorigin="anonymous"></script>
    <script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.min.js"></script>
    <script src="https://unpkg.com/jspdf-autotable@3.5.14/dist/jspdf.plugin.autotable.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.0/moment.min.js"></script>
    <script>
      new Vue({
        el: '#app',
        data() {
          return {
            shopList: [],
            selectedShop: '',
            startDate: '',
            endDate: '',
            tblData: [],
            amount: {
                total : '',
                subTotal : '',
                quantity : '',
                totalRwp: 0,
                totalRwpAmount: 0,
            }
          }
        },
        mounted() {
        this.getData();
        },
        computed: {
        },
        methods: {
           
            getData(){
            // get data
            axios.get(`<%= url %>shop/listApiWthALLShop`)
            .then(response => {
                // console.log(response);
                    if(response?.data?.success === true){
                        this.shopList = response.data.data;

                        if(this.shopList.length > 0) {
                            this.selectedShop = this.shopList[0].id;
                        } 
                    } else {
                        this.shopList = [];
                    }
                }) 
            },
            getVouchers(){
               axios.post(`<%= url %>invoice/rwpReport`,
                {
                    shop_id: this.selectedShop,
                    from_date: this.startDate,
                    to_date: this.endDate
                })
                .then(response => {
                    if(response?.data?.success === true){
                        this.tblData = response.data.data;
                        this.amount.subTotal = response.data.cumulativeSubTotal
                        this.amount.total = response.data.cumulativeTotal
                        this.amount.quantity = response.data.quantity
                        this.amount.totalRwp = response.data.totalRwp;
                        this.amount.totalRwpAmount = response.data.totalRwpAmount;
                        if(response?.data?.data?.length === 0){
                                swal.fire({
                                    title: 'Error',
                                    text: "No data found",
                                    type: 'error',
                                    confirmButtonText: 'Ok'
                                })
                            }
                        }else{
                            this.tblData = [];
                             swal.fire({
                                    title: "Warning",
                                    text: response?.data?.message,
                                    type: 'warning',
                                    confirmButtonText: 'Ok'
                                })
                        }
                    })
                .catch(function (error) {
                    swal.fire(
                    'Error!',
                    'Something went wrong.',
                    'error'
                    )
                })
            },

            getVoucher(id){
                location.href = `<%= url %>invoice/details/${id}`;
            },

            downloadPDF() {

                let shopName = "For all shop.";
                let tableHight = 0;
                let tableMeta = null;

                if( this.selectedShop === 0){
                    shopName = "For all shop.";
                } else {
                    for(let i = 0 ; i < this.shopList.length; i++){
                        if(this.selectedShop === this.shopList[i].id ){
                            shopName = this.shopList[i].name;
                    }
                   }
                }


                if(this.tblData?.length > 0){
                    this.tblData.forEach(function(item,index){
                        item.receiving_date_modified = moment(item.receiving_date).format('DD MMMM, YYYY');
                    });
                    const columns = [
                        { title: "Invoice", dataKey: "inv_no" },
                        { title: "Shop Name", dataKey: "shop_name" },
                        { title: "RWP Date", dataKey: "receiving_date_modified" },
                        { title: "Artical Qty.", dataKey: "artical_qty" },
                        { title: "RWP QTY", dataKey: "rwp" },
                        { title: "RWP Amount", dataKey: "rwp_amount" },
                        { title: "Sub-Total", dataKey: "sub_total" },
                        { title: "Total", dataKey: "total" },
                    ];
                    
                var doc = new jsPDF('p', 'pt');

                var startingPage = doc.internal.getCurrentPageInfo().pageNumber;
                var pageHeight = doc.internal.pageSize.height || doc.internal.pageSize.getHeight();
                var pageWidth = doc.internal.pageSize.width || doc.internal.pageSize.getWidth();
             
                    doc.autoTable(columns, this.tblData, {
                        //showHeader: 'firstPage',
                        showHeader: 'everyPage',
                        styles: { fontSize: 10 },
                        avoidPageSplit: false,
                        margin: { top: 100 },
                        didDrawPage:function(data){
                            tableHight = data.cursor.y
                      }
                    });


                    let pageCount = doc.internal.getNumberOfPages();
                    for(var i = 1; i <= pageCount; i++) {
                    
                        doc.setPage(i);
                        doc.setFontSize(14);
                        doc.setTextColor(1);

                        doc.text("RWP Report", (pageWidth/2) - 20 , 50, { align: 'center' });
                        doc.setFontSize(9);
                        
                      doc.text(shopName, (pageWidth/2) - 5 , 65, { align: 'center' });
        
                      doc.text("Date range: " +  moment(this.startDate).format('DD MMMM, YYYY') + " to " +   moment(this.endDate).format('DD MMMM, YYYY'),
                       (pageWidth/2) - 70 , 80, { align: 'center' });
    
                      doc.setTextColor(100);
                      doc.setFontSize(10);

                      doc.text("Page " + i  + " of " +  pageCount, 50, pageHeight  - 10, {align: 'left'});
                      doc.text(Date(), pageWidth/2 - 30, pageHeight  - 10, {align: 'right'});
                  }

                  doc.setTextColor(1);
                  tableHight += 20;
               
                  doc.text(`Total RWP Qty: ${this.amount.totalRwp} `, 45, tableHight + 20);
                  doc.text(`Total RWP Amount: ${this.amount.totalRwpAmount} TK`, 45, tableHight + 35);
                  doc.text(`Total Qty: ${this.amount.quantity} `, 45, tableHight + 50);
                  doc.text(`Sub Total: ${this.amount.subTotal} TK`, 45, tableHight + 65, );
                  doc.text(`Total: ${this.amount.total} TK`, 45, tableHight + 80, );

                  doc.text(`---------------------------------`, 400, tableHight + 50, );
                  doc.text(`Signature`, 430, tableHight + 60, );

                  doc.save(`RWP Report.pdf`);
                }else {
                    alert("No data to download");
                }   
            },
        },
      })
    </script>
  </body>

</html>