<template>
    <div>
        <div class="contrainer" v-if="invtemp==null && !loading">
            <div class="row">
                <div class="card col-md-4 my-3 mx-auto bg-secondary p-1">
                    <h4>Please select an Invoice Template:</h4>
                    <select v-model="invtemp" class="col-sm-12 col-md-6 form-select form-select-lg mb-3" aria-label=".form-select-lg example" @change.prevent="getInvoiceData()">
                        <option selected disabled>Open this select menu</option>
                        <option v-for="(temp,index) in ddHolder.invtemps" :key="index" :value="temp.id" :selected="temp.id==invtemp">{{ temp.name }}</option>            
                    </select>
                </div>


            </div>
        </div>
        <div class="container" v-else-if="invtemp!=null && !loading">

            <h1>Invoice Draft</h1>
            <div class="printblock border border-1 shadow p-3 mb-5 bg-white rounded mx-auto" >
                <div class="row g-0">
                    <!-- BILLER HEADER -->
                    <div class="col-12 py-0 bg-light px-1 rounded border border-1 shadow-sm mb-3">
                        <div class="container border-bottom border-1 mb-0">
                            <div class="row">
                                <img src="../assets/cds-logo.png" alt="logo" class="object-fit-contain col-4 pb-0" style="height: 2cm;">
                                <h3 class="col-8 pb-0 text-left">{{ invoice['biller.name'] }}</h3>
                            </div>
                        </div>
                        <!-- <div class="container border-bottom border-1 mb-0">
                            <h3 class="pb-0">{{ invoice['biller.name'] }}</h3>
                        </div> -->
                        <div class="row g-0">
                            <div class="col-8 p-1 border-end border-1">
                                <div class="d-flex flex-column align-items-start">
                                    <p class="m-0" style="text-align: justify;"><b>Address: </b>{{ invoice['biller.address']+', '+invoice['biller.contact_no']+', '+invoice['biller.email'] }},</p>
                                    <p class="mb-1 mt-0 mx-0 " style="text-align: justify;"><b>PAN: </b> {{  invoice['biller.pan'] }}, <b>GST: </b> {{ invoice['biller.gst']==null? 'N/A': invoice['biller.gst']}}</p>
                                    <p class="mb-1 mt-0 mx-0 " style="text-align: justify;"><b>Note: </b> {{ invoice['biller.tax_details']==null? '': invoice['biller.tax_details']}}</p>
                                    <hr class="hr">
                                </div>
                            </div>
                            <div class="col-4 d-xl-flex justify-content-xl-end align-items-xl-center px-3">
                                <div class="d-flex flex-column align-items-start">
                                <b>Invoice No:</b><input type="text" v-model="invoice.invoice_no"><b>Invoice Date:</b>{{getCurrentDate()}}
                                </div>
                            </div>
                        </div>
                    </div>
                    <!-- BILLER HEADER ENDS -->
                    <!-- PAYEE DETAILS -->
                    <div class="col-12 py-0 bg-light px-1 rounded border border-1 shadow-sm mb-3">
                        <div class="container border-bottom border-1 mb-0">
                            <h4 class="pb-0">Payee Details</h4>
                        </div>
                        <div class="row g-0">
                            <div class="col-12 p-1 ">
                                <div class="d-flex flex-column align-items-start">
                                    <p class="m-0" style="text-align: justify;"><b>Name: </b>{{ invoice['payee.name'] }}</p>
                                    <p class="m-0" style="text-align: justify;"><b>Address: </b>{{ invoice['payee.address']+', '+invoice['payee.contact_no']+', '+invoice['payee.email'] }},</p>
                                    <p class="mb-1 mt-0 mx-0 " style="text-align: justify;"><b>PAN: </b> {{  invoice['payee.pan'] }}, <b>GST: </b> {{ invoice['payee.gst']==null? 'N/A': invoice['biller.gst']}}</p>
                                    <p class="mb-1 mt-0 mx-0 " style="text-align: justify;"><b>Note: </b> {{ invoice['payee.tax_details']==null? '': invoice['payee.tax_details']}}</p>
                                    <hr class="hr">
                                </div>
                            </div>                            
                        </div>
                    </div>
                    <!-- PAYEE DETAILS END-->
                    <div class="col-12 px-1">
                        <!-- regular invoice table -->
                        <table class="table">
                          <thead>
                            <tr>
                              <th scope="col" class="text-start" style="width: 80px;">#</th>
                              <th scope="col" class="text-start">Billable</th>
                              <th scope="col" class="text-end" >Qty</th>
                              <th scope="col" class="text-end" >Cost</th>
                              <th scope="col" class="text-end" >Sub Total</th>
                            </tr>
                          </thead>
                          <tbody>
                            <tr v-for="(item,index) in invoice.billables" :key="index">                                
                              <th scope="row" class="text-start" style="width: 80px;">{{ index+1 }}</th>
                              <td>{{ item.name }}</td>
                              <td class="d-flex justify-content-end" >
                                <input class="text-end form-control" type="number" min="1" step="1" v-model="item.qty" @change.prevent="item.subTotal=item.qty*item.cost;setTotal();setTaxes();">
                              </td>
                              <td class="text-end" >
                                <b>{{ curr[currency].symbol }}</b><input class="text-end form-control float-end" type="number" min=".00" step=".01" v-model="item.cost" @change.prevent="item.subTotal=item.qty*item.cost;setTotal();setTaxes();">
                                
                              </td>
                              <td class="text-end" >{{ formatCurrency(item.subTotal) }}</td>                              
                            </tr>
                            <tr class="table-secondary text-white">
                                <td></td>
                              <th scope="row" class="text-start" colspan="3">Total before Taxes ===></th>
                              <td  class="text-end">

                                <b> {{ formatCurrency(total) }}</b>
                            </td>
                              
                            </tr>
                            <tr class="table-secondary text-white">
                                <td></td>
                              <th scope="row" class="text-start"  colspan="1"> Taxes ===></th>
                              <td class="text-end" colspan="4">

                                <p class="text-end" v-for="t,i in taxes" :key="i"> {{ t.name }}: {{ formatCurrency(t.val)}}</p>
                            </td>
                            </tr>
                            <tr class="table-secondary text-white">
                                <td></td>
                              <th scope="row" class="text-start"  colspan="3">Total With Taxes ===></th>
                              <td  class="text-end">

                                <b> {{ formatCurrency(getTotal) }}</b>
                              </td>
                            </tr>
                            <tr class="table-secondary text-white">
                                <td></td>
                                <td scope="row" class="text-start"  colspan="4">
                                    <b>In words: </b><i> {{ convertToWords(getTotal,currency) }}</i>
                              </td>
                            </tr>
                          </tbody>
                        </table>
                    </div>
                    <div class="col-12" >
                        <!-- <editor
                            api-key="kbkanx4ppai2u62smpu60i7k7xegfy894dl937j98vvcx060"
                            :init="{
                                height: 500,
                                menubar: true,
                                plugins: 'lists link image',
                                toolbar: 'undo redo | bold italic | alignleft aligncenter alignright | bullist numlist outdent indent',
                            }"
                            v-model="invoice.note"                             
                            /> -->
                        <termsinput v-if="invoice['terms']" :terms="invoice['terms']['delivery']" :title="'Terms Of Delivery'" @terms="invoice['terms']['delivery']"/>
                        <hr/>
                        <termsinput v-if="invoice['terms']" :terms="invoice['terms']['payment']" :title="'Terms Of Payment'" @terms="invoice['terms']['payment']"/>
                        <hr/>
                        <div class="input-group mb-3">
                          <span class="input-group-text" id="input1">Note</span>
                          <input
                            type="text"
                            class="form-control"
                            placeholder="Additional Note"
                            aria-label="Note"
                            aria-describedby="Additional Note"
                            v-model="invoice.note"
                          />
                        </div>
                    </div>
                    <!-- PAYEE SECTION -->
                    <div class="col-12 py-0 bg-light px-1 rounded border border-1 shadow-sm mb-3">
                        <div class="container border-bottom border-1 mb-0">
                            <h4 class="pb-0">Payment Option / Bank Details</h4>
                        </div>
                        <div class="row g-0">
                            <div class="col-12 p-1 ">
                                <div class="d-flex flex-column align-items-start">
                                    <p class="m-0 display-6" style="text-align: justify;font-size: initial;"><b>Bank Account </b></p>
                                    <p class="m-0" style="text-align: justify;"><b>Name on Account: </b>{{ invoice['bank_accounts.name'] }}</p>
                                    <p class="m-0" style="text-align: justify;"><b>Bank Name: </b>{{ invoice['bank_accounts.bank_branch.bank.name'] }},</p>
                                    <p class="m-0" style="text-align: justify;"><b>Account No.: </b>{{ invoice['bank_accounts.account_no'] }},</p>
                                    <p class="m-0" style="text-align: justify;"><b>IFSC Code: </b>{{ invoice['bank_accounts.bank_branch.ifsc'] }},</p>
                                    
                                    <hr class="hr">
                                </div>
                            </div>                            
                        </div>
                    </div>
                    <!-- PAYEE SECTION ENDS -->
                    <div class="col-12">
                        <img alt="Vue logo" src="../assets/cds-logo.png" class="img-fluid" style="width: 100px; height: 100px; float: right; margin: 10px;" />
                         <div class="btn-group" role="group" aria-label="Invoice Actions">
                           <button type="button" class="btn btn-primary" @click.prevent="saveInvoice()">Save</button>
                           <button type="button" class="btn btn-danger" @click.prevent="invtemp=null">Cancel</button>
                         </div>
                    </div>
                    
                </div>
                <!-- <div class="row" >
                    <div class="col-6">
                        
                        <p>Invoice for: {{ invoice.entity }}</p>
                        <p>Amount: {{ invoice.amount }}</p>
                        <p>Date: {{ invoice.date }}</p>
                    </div>
                    <div class="col-6">
                    </div> 
                </div> -->
            </div>
        </div>
    </div>
</template>
<script>
import { convertToWords } from '@/parts/numwords';
import { dropDownLinks,invoiceLinks } from '@/cd-links';
import termsinput from '@/parts/termsinput.vue';
/* import Editor from '@tinymce/tinymce-vue'; */
    export default {
        name: 'InvoiceView',
        components: {
            /* Editor, */ termsinput
        },
        data() {
            return {
                editor: null,
                invtemp: null,
                loading: false,
                invoice: {
                    entity: 'Jaxx Corebin',
                    amount: 100,
                    date: new Date().toLocaleDateString()
                },
                ddHolder: {
                    invtemps: [],
                    payee: [],
                    tax: [],
                    billables: [],
                    recurrence: [],
                    bank_accounts: [],
                },
                total:0,
                taxes:[],
                currency:'INR',
                curr:{
                    'INR': {
                        name: 'Indian Rupee',
                        code: 'INR',
                        symbol: '₹'
                    },
                    'USD': {
                        name: 'United States Dollar',
                        code: 'USD',
                        symbol: '$'
                    },
                    'EUR': {
                        name: 'Euro',
                        code: 'EUR',
                        symbol: '€'
                    },
                    'GBP': {
                        name: 'British Pound Sterling',
                        code: 'GBP',
                        symbol: '£'
                    },
                    'AUD': {
                        name: 'Australian Dollar',
                        code: 'AUD',
                        symbol: 'A$'
                    },
                    'CAD': {
                        name: 'Canadian Dollar',
                        code: 'CAD',
                        symbol: 'C$'
                    },
                    'CHF': {
                        name: 'Swiss Franc',
                        code: 'CHF',
                        symbol: 'CHF'
                    },
                    'CNY': {
                        name: 'Chinese Yuan',
                        code: 'CNY',
                        symbol: '¥'
                    },
                    'JPY': {
                        name: 'Japanese Yen',
                        code: 'JPY',
                        symbol: '¥'
                    },
                    'NZD': {
                        name: 'New Zealand Dollar',
                        code: 'NZD',
                        symbol: 'NZ$'
                    },
                    'SEK': {
                        name: 'Swedish Krona',
                        code: 'SEK',
                        symbol: 'kr'
                    },
                    'RUB': {
                        name: 'Russian Ruble',
                        code: 'RUB',
                        symbol: '₽'
                    }
                },
                content: `
                        <table class="table table-striped table-bordered table-sm">
                            <thead>
                                <tr>
                                    <th>Delivery Terms</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td>Cell 1</td>
                                </tr>
                                <tr>
                                    <td>Cell 3</td>
                                </tr>
                            </tbody>
                        </table>
                `,
            }
        },
        computed: {
            getEntity() {
                return this.$store.getters.getEntity;
            },
            getUser() {
                return this.$store.getters.getUser;
            },
            getTotal() {
                return Number (this.total) + Number (this.taxes.reduce((acc, t) => acc + t.val, 0));
            },            
        },
        methods: {

            setInvoiceNo(prefix,number) {
                const now = new Date();
                function getFY(){
                    return now.getFullYear() + "-" + (now.getFullYear()+1).toString().slice(-2);
                }
                function getFYQuarter(month) {
                    if (month >= 1 && month <= 3) return getFY() + "-Q4";
                    else if (month >= 4 && month <= 6) return getFY() + "-Q1";
                    else if (month >= 7 && month <= 9) return getFY() + "-Q2";
                    else return getFY() + "-Q3";
                }
                function getQuarter(month) {
                    if (month >= 1 && month <= 3) return getFY() + "-Q1";
                    else if (month >= 4 && month <= 6) return getFY() + "-Q2";
                    else if (month >= 7 && month <= 9) return getFY() + "-Q3";
                    else return getFY() + "-Q4";
                }
                if (prefix == null || prefix == undefined) prefix = "INV";
                switch (prefix) {
                    case '$FY':
                        this.invoice.invoice_no = getFY()+ "-" +String((number)).padStart(6,0);
                        break;
                    case '$CY':
                        this.invoice.invoice_no = now.getFullYear()+ "-" +String((number)).padStart(6,0);
                        break;
                    case '$CM':
                        this.invoice.invoice_no = String(now.getMonth()+1).padStart(2,0) + "-" + String((number)).padStart(6,0);
                        break;
                    case '$QTR':
                        this.invoice.invoice_no = getQuarter(now.getMonth()+1) + "-" + String((number)).padStart(6,0);
                        break;
                    case '$QTRFY':
                        this.invoice.invoice_no = getFYQuarter(now.getMonth()+1) + "-" + String((number)).padStart(6,0);
                        break;
                    default:
                        this.invoice.invoice_no = prefix+"-"+number;
                        break;
                }
                /* this.invoice.invoice_no = this.invoice['biller.invoice_prefix']+"-"+(this.invoice['biller.last_invoice_no']+1); */
            },
            formatCurrency(value) {
                        if (isNaN(value)) {
                            return "Invalid value";
                        }

                        const currencySymbol = this.curr[this.currency].symbol || "^"; // Default to ^ if currency not found
                        
                        // Formatting the value with commas
                        const formattedValue = this.currency!='INR'? value.toLocaleString("en-US",{ maximumFractionDigits: 2, minimumFractionDigits: 2 }) : value.toLocaleString("en-IN", { maximumFractionDigits: 2, minimumFractionDigits: 2 });
                        
                        // Combining currency symbol and formatted value
                        return `${currencySymbol}${formattedValue}`;
            },
            convertToWords(num,curr) {
                return convertToWords(num,curr);
            },
            printInvoice() {
                window.print();
            },
            setTotal() {
                this.total = 0;
                for(let i=0;i<this.invoice.billables.length;i++){
                    /* console.log(this.invoice.billables[i]); */
                    this.total += Number(this.invoice.billables[i].subTotal);
                }                                
            },            
            setTaxes() {
                this.taxes = [];
                for(let i=0;i<this.invoice.tax_id.length;i++){

                    this.taxes.push(
                        {  name: this.invoice.tax_id[i].name, val: Number (this.invoice.tax_id[i].perc) * Number (this.total) / 100}
                    );
                    
               }
               console.log(this.taxes);
            },
            getCurrentDate() {
                    const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
                    const today = new Date();
                    const day = String(today.getDate()).padStart(2, "0");
                    const month = months[today.getMonth()];
                    const year = today.getFullYear();
                    return `${day}-${month}-${year}`;
            },
            async saveInvoice(){
                let submitData = {};
                Object.keys(this.invoice).forEach(k=>{
                    switch (k.replaceAll(".","_")) {
                        case "bank_accounts_account_no":
                            submitData["bank_account_no"]=this.invoice[k]
                            break;
                        case "bank_accounts_bank_branch_bank_id":
                            submitData["bank_id"]=this.invoice[k]
                            break;
                        case "bank_accounts_bank_branch_bank_name":
                            submitData["bank_name"]=this.invoice[k]
                            break;
                        case "bank_accounts_bank_branch_id":
                            submitData["bank_branch_id"]=this.invoice[k]
                            break;
                        case "bank_accounts_id":
                            submitData["bank_account_id"]=this.invoice[k]
                            break;
                        case "bank_accounts_name":
                            submitData["bank_account_name"]=this.invoice[k]
                            break;
                        case "bank_accounts_bank_branch_name":
                            submitData["bank_branch_name"]=this.invoice[k]
                            break;
                        case "bank_accounts_bank_branch_ifsc":
                            submitData["bank_branch_ifsc"]=this.invoice[k]
                            break;
                        default:
                            submitData[k.replaceAll(".","_")]=this.invoice[k]
                            break;
                    }
                });
                submitData['template_id'] = submitData.id;
                delete submitData.id;
                console.log("=============Data to be submitted==============");
                console.log(submitData);
                console.log("===============================================");
                this.loading=true;
                await this.$store.getters.getAxios.post(invoiceLinks.post,submitData)
                    .then(resp=>{
                        if(!resp.data.isLoggedIn){
                            this.$store.dispatch('loggedOut');
                        }
                        else {
                            this.invoice =  resp.data.data;
                            this.$store.commit('addAlert', {
                                title: resp.data.title,
                                message: resp.data.msg,
                                type: resp.data.success? 'success' : 'danger'
                            });
                        }
                        this.invtemp = null;
                    })
                    // eslint-disable-next-line
                    .catch(err=>{
                        this.$store.commit('addAlert', {
                            title: "Error Saving Invoice",
                            message: "Try after some time",
                            type: 'danger'
                        });
        
                    });
                this.loading=false;
            },
            async getDropDownData(table,listName,filter) {
                    this.loading=true;
                    await this.$store.getters.getAxios.post(dropDownLinks[table],{ent_id:this.$store.getters.getEntity,filter:filter})
                        .then(resp=>{
                            if(!resp.data.isLoggedIn){
                                this.$store.dispatch('loggedOut');
                            }
                            else this.ddHolder[listName] =  resp.data.data;
                            this.loading=false;
                        })
                        // eslint-disable-next-line
                        .catch(err=>{
                            this.$store.commit('addAlert', {
                                title: "Error Getting DropDown Data for "+listName,
                                message: "Try after some time",
                                type: 'danger'
                            });
        
                        })
            },
            async getInvoiceData() {
                this.loading=true;
                await this.$store.getters.getAxios.post(invoiceLinks.generate,{biller_id:this.$store.getters.getEntity,template_id:this.invtemp})
                    .then(resp=>{
                        if(!resp.data.isLoggedIn){
                            this.$store.dispatch('loggedOut');
                        }
                        else {
                            this.invoice =  resp.data.data;
                            this.invoice.billables.forEach(item => {
                                item['qty'] = 1;
                                item['subTotal'] = item.qty * item.cost;
                                this.currency = item.currency;
                            });                            
                            this.setTotal();
                            this.setTaxes();
                            this.invoice.terms==null? this.invoice.terms = {delivery:'',payment:''}: this.invoice.terms;
                            if(this.invoice.terms['delivery'] == undefined || this.invoice.terms['delivery']==null) this.invoice.terms['delivery']=[];
                            if(this.invoice.terms['payment'] == undefined || this.invoice.terms['payment']==null) this.invoice.terms['payment']=[];
                            /* this.invoice['invoice_no']=this.invoice['biller.invoice_prefix']+"-"+(this.invoice['biller.last_invoice_no']+1); */
                            this.setInvoiceNo(this.invoice['biller.invoice_prefix'],Number(this.invoice['biller.last_invoice_no'])+1);                            
                        }
                        this.$store.commit('addAlert', {
                            title: resp.data.title,
                            message: resp.data.msg,
                            type: resp.data.success? 'info' : 'danger'
                        });
                        this.loading=false;
                    })
                    // eslint-disable-next-line
                    .catch(err=>{
                        this.$store.commit('addAlert', {
                            title: "Error Getting Invoice Data",
                            message: "Try after some time",
                            type: 'danger'
                        });
        
                    })
            }
        },
        mounted() {
            /* this.getDropDownData('accounts','accounts',0);
            this.getDropDownData('pentities','pentities',0);
            this.getDropDownData('taxes','taxes',0);
            this.getDropDownData('billables','billabes',0); */
            this.getDropDownData('invtemps','invtemps',0);
        }
    }
</script>
<style scoped>
[type="number"] {
    /* max-width: 300px; */ /* Set the maximum width */
    /* width: 100%; */ /* Make it responsive */
    max-width: 100px !important; /* Set the maximum width */
}
.printblock{
    font-size: 3mm !important;
    width: 210mm; /* A4 width */
    /* height: 297mm; */ /* A4 height */
    /* padding: 10mm; */ /* Optional: content padding */
  }
@media print {
  body{
    visibility: hidden;
  }
  .printblock{
    visibility: visible;
    position: absolute;
    top: 0;
    left: 0;
    page-break-after: always; /* Force page break after each A4 block */
  }
}
</style>