<template>
    <theme-table :noneActions="true">
        <span slot="main-title">
            {{ $t('Client Payment List') }}
        </span>
        <div slot="body">
            <div class="row g-4">
                <div class="col-lg-8">
                    <div class="card mb-4 bg-body-tertiary  border-0">
                        <div class="card-body">
                            <div class="row">
                                <div class="col-6">
                                    <table class="w-100">
                                        <tr>
                                            <td>{{ $t('Principal') }}</td>
                                            <td class="px-2 text-end">{{ acc_unpaid.principal | numberFomartValue}}</td>
                                        </tr>
                                        <tr>
                                            <td>{{ $t('Interest') }}</td>
                                            <td class="px-2 text-end">{{ acc_unpaid.interest_per_month | numberFomartValue}}</td>
                                        </tr>
                                        <tr>
                                            <td>{{ $t('Operating Services') }}</td>
                                            <td class="px-2 text-end">{{ acc_unpaid.operating_service | numberFomartValue}}</td>
                                        </tr>
                                        <tr>
                                            <td>{{ $t('Payment') }}</td>
                                            <td class="px-2 text-end">{{ acc_unpaid.payment_per_month | numberFomartValue}}</td>
                                        </tr>
                                    </table>
                                </div>
                                <div class="col-6">
                                    <table class="w-100">
                                        <tr>
                                            <td>{{ $t('Payment Date') }}</td>
                                            <td class="px-2 text-end">{{ acc_unpaid.payment_date | onlyDate}}</td>
                                        </tr>
                                        <tr>
                                            <td>{{ $t('Paid') }}</td>
                                            <td class="px-2 text-end">{{ acc_unpaid.received | numberFomartValue}}</td>
                                        </tr>
                                        <tr>
                                            <td><strong>{{ $t('Unreceived') }}</strong></td>
                                            <td class="px-2 text-end"><strong>{{ acc_unpaid.unreceived | numberFomartValue}}</strong></td>
                                        </tr>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="row g-3 mb-5">
                        <div class="col-md-6">
                            <label class="form-label">{{ $t('Client Name') }}</label>
                            <Multiselect 
                                v-model="loan_id" 
                                @input="fSearchPayment" 
                                trackBy="client_loan" 
                                value="id" 
                                label="client_loan" 
                                :searchable="true" 
                                :options="clientLoans" 
                                :placeholder="$t('Client Name')" 
                            />
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">{{ $t('Received Date') }}<span class="text-danger">*</span></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="valid text-danger" v-if="form.errors.has('received_date')" v-html="form.errors.get('received_date')"></div>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">{{ $t('Penalty') }}</label>
                            <small v-show="acc_unpaid.total_late>0" style="color: green;font-size:12px">(យឺត{{acc_unpaid.total_late}}ថ្ងៃ)</small>
                            <input type="text" :value="formattedAmountPenalty" @input="funPenalty" class="form-control" @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 class="col-md-6">
                            <label class="form-label">{{ $t('Total Amount Repay') }}<sup class="text-danger">*</sup></label>
                            <input type="text" :value="formattedAmountPay" @input="updateAmountRepay($event.target.value)" class="form-control" @keypress="isNumber($event)" :placeholder="$t('Total Amount Repay')" :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 class="mb-3">
                            <label class="form-label">{{ $t('Note') }}</label>
                            <input
                                type="text"
                                v-model="form.note"
                                class="form-control"
                                :class="{ 'is-invalid': form.errors.has('note') }"
                                :placeholder="$t('Note')"
                            />
                            <div class="valid text-danger" v-if="form.errors.has('note')" v-html="form.errors.get('note')"></div>
                        </div>
                    </div>
                    <div>
                        <label class="form-label">{{ $t('Payment Method') }}<span class="text-danger">*</span></label>
                        <div class="d-flex flex-nowrap overflow-auto text-nowrap">
                            <div class="pe-2" v-for="method in payment_methods" :key="method.value">
                                <button type="button"
                                        :class="{ active: form.chart_of_acc_id === method.value }"
                                        @click="selectPaymentMethod(method)"
                                        class="btn btn-light text-body border bg-body payment-btn">
                                    <span>{{ method.chart_code_name }}</span>
                                </button>
                            </div>
                        </div>
                        <div class="valid text-danger" v-if="form.errors.has('chart_of_acc_id')" v-html="form.errors.get('chart_of_acc_id')"></div>
                    </div>
                    
                </div>
                <div class="col-lg-4">
                    <div class="summary-panel bg-body-tertiary">
                        <div class="text-center">
                            <div class="order-details-title">{{$t('Total Amount Repay') }}</div>
                            <div class="h2 fw-bold my-2">{{ formattedAmountPay }}</div>
                        </div>
                        <div class="w-100 my-3" style="border: 1px dashed #eee"></div>
                        <div>
                            <div class="order-details-title">{{$t('Detail Payments') }}</div>
                            <div class="order-details-item">
                                <span>{{ $t('Payment Method') }}</span>
                                <span  v-if="selectedMethod">{{ selectedMethod }}</span>
                            </div>
                            <div class="order-details-item">
                                <span>{{ $t('Client Name') }}</span>
                                <span><strong>{{data_loans.client_name}}</strong></span>
                            </div>
                            <div class="order-details-item">
                                <span>{{ $t('Loan Code') }}</span>
                                <span>{{data_loans.loan_code}}</span>
                            </div>
                            <div class="order-details-item">
                                <span>{{ $t('Level Loan') }}</span>
                                <span>{{data_loans.level_loan}}</span>
                            </div>
                            <div class="order-details-item">
                                <span>បង់លើកទី</span>
                                <span>{{count_paid}}</span>
                            </div>
                            <div class="order-details-item">
                                <span>{{ $t('Balance Principal') }}</span>
                                <span>{{data_loans.balance_principal | numberFomartValue}}</span>
                            </div>
                            <div class="order-details-item">
                                <span>{{ $t('Loan Balance') }}</span>
                                <span>{{data_loans.loan_balance | numberFomartValue}}</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="d-flex justify-content-end pt-4">
                <button type="button" class="btn btn-light bg-body border btn-lg me-2" @click="ClearData">{{$t('Clear') }}</button>
                <button 
                        type="submit" 
                        class="btn btn-primary btn-lg border" 
                        :disabled="!loan_id"
                        @click="submitData()">
                        {{ $t('Submit Payment') }}
                </button>
            </div>
        </div>

        <!-- Receipt Payment -->
            <div slot="modal-custom">
              <div class="modal fade" id="modalPrintReciept">
               
                <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" @click="ClearData"></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" @click="ClearData">{{ $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 moment from "moment";
    import BodyReciept from "../loan/BodyReciept.vue";
    import ThemeTable from "../../components/ThemeTable.vue";
    export default {
        components: {
            ThemeTable,
            BodyReciept,
        },
        data() {  
            return {
                moment      : moment,
                format      : "YYYY-MM-DD",
                loan_id     : "",
                data_loans  : "",
                count_paid  : "",
                acc_unpaid  : "",
                clientLoans : [],
                payment_methods : [],
                selectedMethod: "",
                dataAcc: {},
                form: new Form({
                    id : "",
                    received_date: new Date().toISOString(),
                    paid_penalty : 0,
                    amount_repay : 0,
                    chart_of_acc_id : '',
                    note : '',
                    submitting : false,
                    
                }),
                params: {

                },
                
            };
        },
        created() {
            this.funGetClientLoan();
            this.funPaymentMethod();
        },
        methods: {
            funPaymentMethod() {
                axios.get("accounting/com-cash-bank").then((res) => {
                    this.payment_methods = res.data;
                }).catch((error) => {
                    console.log(error);
                });
            },
            selectPaymentMethod(value) {
                this.form.chart_of_acc_id = value.id;
                this.selectedMethod = value.chart_code_name;
            },
            funGetClientLoan() {
                axios.get("admin-api/com-client-loan",{
                    params:{
                        type_collect : 1,
                    }
                }).then((res) => {
                    this.clientLoans = res.data;
                }).catch((error) => {
                    console.log(error);
                });
            },
            fSearchPayment(){
                this.dataPayment = [];
                if(this.loan_id!='' && this.loan_id!=null){
                    axios.get("admin-api/loans/show-client-payment/" + this.loan_id).then((res) => {
                        this.data_loans = res.data.loan;
                        this.count_paid = res.data.count_paid;
                        this.acc_unpaid = res.data.acc_unpaid;
                        this.form.id    = res.data.acc_unpaid.id;
                        this.form.amount_repay = res.data.acc_unpaid.unreceived;
                    }).catch((error) => {
                        console.log(error);
                    });
                }
            },
            funPenalty(event){
                let pay_penalty = event.target.value;
                this.form.paid_penalty  = pay_penalty==''?0:pay_penalty;
                const amount_penalty    = event.target.value;
                const convert_to_number = parseFloat(amount_penalty.replace(/[^\d\.]/g, ""));
                this.form.paid_penalty  = convert_to_number;
                this.form.amount_repay = parseFloat(this.acc_unpaid.unreceived) + parseFloat(convert_to_number);
            },
            updateAmountRepay(value) {
                const numericValue = parseFloat(value.replace(/,/g, '')) || 0;
                this.form.amount_repay = numericValue;
            },
            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;
                }
            },
            emtyData(){
                this.form.reset();
                this.loan_id    = "";
                this.data_loans = "";
                this.count_paid = "";
                this.acc_unpaid = "";
                this.selectedMethod = "";
                this.quoteShow = "";
                this.quoteShowDetails = "";
            },
            ClearData(){
                this.emtyData();
            },
            
            submitData() {
             
              
                this.$confirm({
                    message: "Are you sure?",
                    button: { no: "No", yes: "Yes" },
                    callback: (confirm) => {
                        if (!confirm) return;
                        if (this.form.submitting) return;
                        this.form.submitting = true;
                        this.form.post("admin-api/client-payment")
                            .then((res) => {
                                if (res.data.status == 1) {
                                    // this.emtyData();
                                    this.$toast.success(res.data.message);
                                    // this.showPrint(res.data.data?.id);
                                    this.dataAcc = res.data.accReceivableDetail;
                                    $("#modalPrintReciept").modal("show");
                                } else {
                                    this.$toast.warning(res.data.message);
                                }
                            })
                            .catch((error) => console.error(error))
                            .finally(() => {
                                this.form.submitting = false;
                            });
                    },
                });
            },
            // showPrint(id) {
            //     $("#modalPrintReciept").modal("show");
            //     axios.get("admin-api/quote/" + id, { params: { is_details: 1 } }
            //     ).then((res) => {
            //         this.quoteShow = res.data.data;
            //     });
            // },
            printP() {
                this.$htmlToPaper("show-print", {
                    styles: ["/css/app.css", "/css/print/print-reciept.css"],
                });
            },
        },
        computed: {
            formattedAmountPenalty(){
                return new Intl.NumberFormat('en-US').format(this.form.paid_penalty || 0);
            },
            formattedAmountPay() {
                return new Intl.NumberFormat('en-US').format(this.form.amount_repay || 0);
            },
        },
    };
</script>

<style>
    .payment-btn {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        font-weight: bold;
        border-radius: 50px;
        transition: all 0.2s ease;
    }
    .payment-btn.btn-light.active {
        border-color: var(--bs-primary) !important;
        background-color: #e7f1ff !important;
        color: var(--bs-primary) !important;
    }
    .summary-panel {
        border-radius: 1rem;
        padding: 2rem;
        height: 100%;
        display: flex;
        flex-direction: column;
    }
    .summary-header-title {
        font-weight: 600;
        color: #6c757d;
        text-transform: uppercase;
        font-size: 0.8rem;
        letter-spacing: 0.5px;
    }
    .summary-total-amount {
        font-size: 2rem;
        font-weight: 700;
        margin-bottom: 1.5rem;
    }
    .order-details-title {
        font-weight: 600;
        color: #6c757d;
        text-transform: uppercase;
        font-size: 0.8rem;
        letter-spacing: 0.5px;
        margin-bottom: 1rem;
    }
    .order-details-item {
        display: flex;
        justify-content: space-between;
        margin-bottom: 0.75rem;
        font-size: 0.95rem;
    }
</style>
