<template>
    <theme-table :noneActions="true">
        <div slot="body">
            <div class="row mb-2">
                <div class="col-sm-6">
                    <h5 class="text-moul">{{ $t("Show Payment") }} {{client_name}}</h5>
                </div>
                <div class="col-sm-6">
                    <Multiselect v-model="loan_id" @input="fSearchPayment" trackBy="name" value="id" label="name" :searchable="true" :options="clients" :placeholder="$t('Client Name')" />
                </div>
            </div>
            <div class="table-responsive table_scroll">
                <table class="table table-bordered">
                    <thead class="text-nowrap fixed_table">
                        <tr>
                            <th>{{ $t("Show") }}</th>
                            <th>{{ $t("#") }}</th>
                            <th>{{ $t("Payment Date") }}</th>
                            <th>{{ $t("Received Date") }}</th>
                            <th>{{ $t("Principal") }}</th>
                            <th>{{ $t("Interest") }}</th>
                            <th>{{ $t("Payment") }}</th>
                            <th>{{ $t("Received") }}</th>
                            <th>{{ $t("Unreceive") }}</th>
                            <th>{{ $t("Loan Balance") }}</th>
                            <th>{{ $t("Paid Penalty") }}</th>
                            <th>{{ $t("Status") }}</th>
                        </tr>
                    </thead>
                    <tbody class="text-nowrap">
                        <tr v-for="(value, index) in details" :key="index">
                            <td>
                                <button type="button" @click="funShowPayment(value.id)" v-show="value.payment_status_id==1 || value.payment_status_id==2" :title="$t('Show Payment')" class="btn btn-success s-btn-xs m-1">
                                    <i class="fa-solid fa-eye fa-sm"></i>
                                </button>
                            </td>
                            <td>{{ index + 1 }}</td>
                            <td>{{ value.payment_date | onlyDate}}</td>
                            <td>{{ value.received_date | onlyDate}}</td>
                            <td>{{ value.principal | numberFomartValue }}</td>
                            <td>{{ value.interest_per_month | numberFomartValue }}</td>
                            <td>{{ value.payment_per_month | numberFomartValue }}</td>
                            <td>{{ value.received | numberFomartValue }}</td>
                            <td>{{ value.unreceived | numberFomartValue }}</td>
                            <td>{{ value.loan_balance | numberFomartValue }}</td>
                            <td>{{ value.penalty | numberFomartValue }}</td>
                            <td><span :style="{ 'color': value.color_code }">
                                {{value.status_title}}</span>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
        <div slot="modal-custom">
            <!-- Show Details -->
            <div class="modal fade" id="modalShowPayment" aria-hidden="true" role="dialog" data-bs-backdrop="static">
                <div class="modal-dialog modal-xl modal-dialog-scrollable">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h4 class="modal-title">{{ $t("Client Name") }}: <strong>{{client_name}}</strong></h4>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            <div class="table-responsive border-0">
                                <table class="table table-bordered">
                                    <thead class="text-nowrap fixed_table">
                                        <tr>
                                            <th>{{ $t("#") }}</th>
                                            <th>{{ $t("Received Date") }}</th>
                                            <th>{{ $t("Paid Principal") }}</th>
                                            <th>{{ $t("Paid Interest") }}</th>
                                            <th>{{ $t("Total Received") }}</th>
                                            <th>{{ $t("Penalty") }}</th>
                                            <th>{{ $t("Payment Method") }}</th>
                                            <th>{{ $t("Action") }}</th>
                                        </tr>
                                    </thead>
                                    <tbody class="text-nowrap">
                                        <tr v-for="(value, index) in dataDetails.data" :key="index">
                                            <td>{{ index + 1 }}</td>
                                            <td>{{ value.received_date | onlyDate}}</td>
                                            <td>{{ value.paid_principal | numberFomartValue }}</td>
                                            <td>{{ value.paid_interest | numberFomartValue }}</td>
                                            <td>{{ value.received | numberFomartValue }}</td>
                                            <td>{{ value.paid_penalty | numberFomartValue }}</td>
                                            <td>{{ value.payment_method}}</td>
                                            <td>
                                                <button @click="funPrintPayment(value)" :title="$t('Print Payment')" class="btn btn-success s-btn-xs">
                                                    <i class="fa-solid fa-print fa-sm"></i>
                                                </button>

                                                <button type="button" :title="$t('Repay Edit')" class="btn btn-primary s-btn-xs"
                                                    @click="EditDataPayment(value)"
                                                    v-if="$can('Repay Edit')"
                                                    v-show="value.closing_date==null && value.approved_by==null && value.payment_status_id !=6 && value.payment_status_id !=8 && index == dataDetails.data.length-1 && value.id == max_id_details && user_branch != -1">
                                                    <i class="fa-solid fa-edit fa-sm"></i>
                                                </button>

                                                <button type="button" :title="$t('Delete')" class="btn btn-danger s-btn-xs" 
                                                    @click="funDelete(value.id)"
                                                    v-if="$can('Repay Delete')"
                                                    v-show="value.closing_date==null && value.approved_by==null && value.payment_status_id !=6 && value.payment_status_id !=8 && index == dataDetails.data.length-1 && value.id == max_id_details && user_branch != -1">
                                                    <i class="fa-solid fa-trash-can fa-sm"></i>
                                                </button>
                                            </td>
                                        </tr>
                                        <tr class="table-active">
                                            <td colspan="2" class="text-end">{{ $t("Total") }}</td>
                                            <td>{{totalPaidPrincipal | numberFomartValue}}</td>
                                            <td>{{totalPaidInterest | numberFomartValue}}</td>
                                            <td>{{totalReceived | numberFomartValue}}</td>
                                            <td>{{totalPaidPenalty | numberFomartValue}}</td>
                                            <td></td>
                                            <td></td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-danger" data-bs-dismiss="modal"><img src="/icons/b_drop.png" alt="" /> {{ $t("Close") }}</button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Form Edit Payment -->
            <form method="post" role="form">
                <div class="modal fade" id="modalEditForm" aria-hidden="true" role="dialog" data-bs-backdrop="static">
                    <div class="modal-dialog modal-xl">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h4 class="modal-title">{{ $t("Edit Payment") }}: <strong>{{client_name}}</strong></h4>
                                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                            </div>
                            <div class="modal-body">
                                <div class="row">
                                    <div class="col-xl-4 col-6">
                                        <div class="mb-3">
                                            <label class="form-label">{{ $t('Paid Principal') }}</label>
                                            <input type="text" class="form-control" @keypress="isNumber($event)" :value="principal | numberFomartValue" :placeholder="$t('Principal')" disabled />
                                        </div>
                                    </div>
                                    <div class="col-xl-4 col-6">
                                        <div class="mb-3">
                                            <label class="form-label">{{ $t('Paid Interest') }}</label>
                                            <input type="text" class="form-control" @keypress="isNumber($event)" :value="interest | numberFomartValue" :placeholder="$t('Interest')" disabled />
                                        </div>
                                    </div>
                                    <div class="col-xl-4 col-6">
                                        <div class="mb-3">
                                            <label class="form-label">{{ $t('Payment') }}</label>
                                            <input type="text" class="form-control" @keypress="isNumber($event)" :value="payment | numberFomartValue" :placeholder="$t('Payment')" disabled />
                                        </div>
                                    </div>
                                    <div class="col-xl-4 col-6">
                                        <div class="mb-3">
                                            <label class="form-label">{{ $t('Unreceived') }}</label>
                                            <input type="text" class="form-control" @keypress="isNumber($event)" :value="unreceived | numberFomartValue" :placeholder="$t('Unreceived')" disabled />
                                        </div>
                                    </div>
                                    <div class="col-xl-4 col-6">
                                        <div class="mb-3">
                                            <label class="form-label">{{ $t('Penalty') }}</label>
                                            <input type="number" min="0"class="form-control" v-model="form.paid_penalty" @input="funEditPenalty" @keypress="isNumber($event)" :placeholder="$t('Penalty')" :class="{ 'is-invalid': form.errors.has('paid_penalty') }" />
                                            <div class="valid text-danger" v-if="form.errors.has('paid_penalty')" v-html="form.errors.get('paid_penalty')"></div>
                                        </div>
                                    </div>
                                    <div class="col-xl-4 col-6">
                                        <div class="mb-3">
                                            <label class="form-label">{{ $t('Total Received') }}<sup class="text-danger">*</sup></label>
                                            <input type="text" class="form-control" @keypress="isNumber($event)" v-model="form.amount_repay" :placeholder="$t('Total Received')" :class="{ 'is-invalid': form.errors.has('amount_repay') }" />
                                            <div class="valid text-danger" v-if="form.errors.has('amount_repay')" v-html="form.errors.get('amount_repay')"></div>
                                        </div>
                                    </div>
                                    <div class="col-xl-4 col-6">
                                        <div class="mb-3">
                                            <div class="mb-3">
                                                <label class="form-label">{{ $t('Received Date') }}<sup class="text-danger">*</sup></label>
                                                <date-picker v-model="form.received_date" valueType="format" :placeholder="$t('Received Date')" :format="format" :class="{'is-invalid': form.errors.has('received_date') }"></date-picker>
                                                <div class="text-danger" v-if="form.errors.has('received_date')" v-html="form.errors.get('received_date')" />
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-xl-4 col-6">
                                        <div class="mb-3">
                                            <label class="form-label">{{ $t('Payment Method') }}<sup class="text-danger">*</sup></label>
                                            <Multiselect v-model="form.chart_of_acc_id" :placeholder="$t('Payment Method')" label="chart_code_name" :class="{ 'is-invalid': form.errors.has('chart_of_acc_id') }" :searchable="true" :options="payment_methods" />
                                            <div class="text-danger" v-if="form.errors.has('chart_of_acc_id')" v-html="form.errors.get('chart_of_acc_id')" />
                                        </div>
                                    </div>
                                    <div class="col-xl-4 col-6">
                                        <div class="mb-3">
                                            <label class="form-label">{{ $t('Note') }}</label>
                                            <textarea class="form-control" v-model="form.note" :placeholder="$t('Note')" rows="1"></textarea>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="modal-footer">
                                <button type="button" :disabled="params.busy || form.isSubmitting" class="btn btn-danger" data-bs-dismiss="modal">
                                    <img src="/icons/b_drop.png" alt="" /> {{ $t("Close") }}
                                </button>
                                <button type="button" @click="SubmitEditPayment()" :disabled="params.busy || form.isSubmitting" class="btn btn-primary">
                                    <span v-if="params.busy || form.isSubmitting" class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
                                    <span v-else>{{$t('Submit')}}</span>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </form>

            <!-- Receipt Payment -->
            <div class="modal fade" id="modalPrintReciept" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
                <div class="modal-dialog modal-xl modal-dialog-scrollable">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h4 class="modal-title">{{ $t("Print Reciept") }}</h4>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            <div id="show-print">
                                <div class="custom-reciept-top">
                                    <BodyReciept :data="dataAcc"/>
                                </div>
                                <div class="custom-reciept-bottom">
                                    <BodyReciept :data="dataAcc"/>
                                </div>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">{{ $t("Close") }}</button>
                            <button type="button" class="btn btn-primary" @click="printP">{{$t('Print')}}</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </theme-table>
</template>

<script>
    import BodyReciept from "./BodyReciept.vue";
    import ThemeTable from "../../components/ThemeTable.vue";
    import CumstomPagination from "../../components/CustomPagination.vue";
    import moment from "moment";
    export default {
        components: {
            BodyReciept,
            ThemeTable,
            CumstomPagination,
        },
        data() {
            return {
                moment         : moment,
                currency       : '',
                format         : "YYYY-MM-DD",
                loan_id        : "",
                client_name    : "",
                details        : {},
                clients        : [],
                payment_methods: [],
                dataDetails    : { data: [] },
                max_id_details : '',
                dataAcc        : "",
                user_branch    : "",
                form: new Form({
                    id: "",
                    received_date   : new Date().toISOString(),
                    paid_penalty    : '',
                    amount_repay    : 0,
                    chart_of_acc_id : '',
                    note            : '',
                    isSubmitting    : false,
                }),
                params: {
                },
                principal : 0,
                interest  : 0,
                payment   : 0, 
                received  : 0,  
                unreceived: 0, 
            };
        },
        created() {
            this.fGetData();
            this.funComUserBranch();
        },
        mounted() {
            this.checkInterruptedSubmission();
        },
        methods: {
            isNumber: function (evt) {
                evt = evt ? evt : window.evt;
                var charCode = evt.which ? evt.which : evt.keyCode;
                if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode !== 46) {
                    evt.preventDefault();
                } else {
                    return true;
                }
            },
            fGetData() {
                axios.get("admin-api/com-all-client-loan").then((res) => {
                    this.clients = res.data;
                }).catch((error) => {
                    console.log(error);
                });
            },
            fSearchPayment(){
                this.details = [];
                if(this.loan_id!='' && this.loan_id!=null){
                    axios.get("admin-api/show-schedule-payment/" + this.loan_id).then((res) => {
                        this.client_name = res.data.client_name;
                        this.details     = res.data.schedule;
                    }).catch((error) => {
                        console.log(error);
                    });
                }
            },
            // Show Details
            funShowPayment(id) {
                this.form.get("admin-api/show-schedule-detail/" + id).then((res) => {
                    this.dataDetails    = res.data; // 
                    this.client_name    = res.data.client_name;
                    this.max_id_details = res.data.max_id_details;
                    $("#modalShowPayment").modal("show");
                }).catch((error) => {
                    console.log(error);
                });
            },
            printP() {
                this.$htmlToPaper("show-print", {
                    styles: ["/css/app.css", "/css/print/print-reciept.css"],
                });
            },
            funPrintPayment(value) {
                $("#modalShowPayment").modal("hide");
                $("#modalPrintReciept").modal("show");
                this.dataAcc = value;
            },
            funDelete(id) {
                this.$confirm({
                    message: "Are you sure?",
                    button: {
                        no: "No",
                        yes: "Yes",
                    },
                    callback: (confirm) => {
                        if (confirm) {
                            this.form.delete("admin-api/client-payment/" + id).then((res) => {
                                if (res.data.status == 1) {
                                    this.$toast.success(res.data.message);
                                    this.funShowPayment(res.data.accID);
                                    this.fSearchPayment();
                                } else {
                                    this.$toast.warning(res.data.message);
                                }
                            });
                        }
                    },
                });
            },
            // Edit Payment
            funPaymentMethod() {
                axios.get("accounting/com-cash-bank").then((res) => {
                    this.payment_methods = res.data;
                }).catch((error) => {
                    console.log(error);
                });
            },
            // Restore state if page reloads during submission
            checkInterruptedSubmission() {
                if (sessionStorage.getItem("formSubmitting") === "true") {
                    this.$toast.warning("Submission was interrupted. Please try again.");
                    sessionStorage.removeItem("formSubmitting"); // Clear interrupted state
                }
            },
            EditDataPayment(value) {
                this.form.id              = value.id;
                this.form.chart_of_acc_id = value.chart_of_acc_id;
                this.form.received_date   = value.received_date;
                this.form.amount_repay    = parseFloat(value.received) + parseFloat(value.paid_penalty);
                this.form.note            = value.note;
                this.form.paid_penalty    = value.paid_penalty;
                this.client_name          = value.client_name;
                this.principal            = value.paid_principal;
                this.interest             = value.paid_interest;
                this.received             = value.received;
                this.payment              = value.payment_per_month;
                this.unreceived           = value.unreceived;
                this.funPaymentMethod();
                $("#modalEditForm").modal("show");
            },
            funEditPenalty(event){
                let pay_penalty = event.target.value;
                this.form.paid_penalty = pay_penalty;
                this.form.amount_repay = parseFloat(this.received) + parseFloat(pay_penalty);
            },
            async SubmitEditPayment() {
                if(this.form.amount_repay !==''){
                    if (this.form.isSubmitting) return;
                    this.form.isSubmitting = true;
                    sessionStorage.setItem("formSubmitting", "true");

                    // Add a warning for page unload
                    window.addEventListener("beforeunload", this.preventPageUnload);
                    try {
                        const res = await this.form.put("admin-api/client-payment/" + this.form.id);
                            if (res.data.status == 1) {
                                this.form.reset();
                                $("#modalEditForm").modal("hide");
                                this.$toast.success(res.data.message);
                                this.funShowPayment(res.data.accID);
                                this.fSearchPayment();
                                
                                sessionStorage.removeItem("formSubmitting");
                            } else {
                                this.$toast.warning(res.data.message);
                            }
                        } catch (error) {
                            console.error("Error submitting form:", error);
                            alert("Something went wrong!");
                        } finally {
                            window.removeEventListener("beforeunload", this.preventPageUnload);
                            this.form.isSubmitting = false;
                            sessionStorage.removeItem("formSubmitting"); // Ensure state is cleared
                        }
                }else{
                    this.$toast.warning('Please check amount repay or penalty!');
                }
            },
        },
        computed:{
            totalPaidPrincipal: function () {
                var sum = 0;
                this.dataDetails.data?.forEach(function (item) {
                    sum += parseFloat(item.paid_principal);
                });
                return sum;
            },
            totalPaidInterest: function () {
                var sum = 0;
                this.dataDetails.data?.forEach(function (item) {
                    sum += parseFloat(item.paid_interest);
                });
                return sum;
            },
            totalReceived: function () {
                var sum = 0;
                this.dataDetails.data?.forEach(function (item) {
                    sum += parseFloat(item.received);
                });
                return sum;
            },
            totalPaidPenalty: function () {
                var sum = 0;
                this.dataDetails.data?.forEach(function (item) {
                    sum += parseFloat(item.paid_penalty);
                });
                return sum;
            },
        }
    };
</script>