@extends('layouts.app')
@section('title', @$voucher_type->voucher_title .' STATEMENT')
@section('pages')
@php $pageTitle=@$voucher_type->voucher_title; @endphp
<link rel="stylesheet" type="text/css" href="{{ asset('admin/plugins/datepicker/less/datepicker.less') }}">
<link href="{{ asset('admin/plugins/datepicker/css/datepicker.css') }}" rel="stylesheet" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/12.1.10/css/intlTelInput.css">
<link href="{{ asset('admin/css/print.css')}}" rel="stylesheet" />
<style>
   .clear{
    clear:both;
    margin-top: 20px;
    }

    .autocomplete{
        position: relative;
    }
    .autocomplete .searchResult{
        list-style: none;
        padding: 0px;
        width: 50%;
        position: absolute;
        margin: 0;
        margin-top: 40px;
        background: white;
        z-index: 5;
    }

    .autocomplete .searchResult li{
        background: #F2F3F4;
        padding: 10px;
        margin-bottom: 1px;
        white-space: break-spaces;
    }

    .autocomplete .searchResult li:nth-child(even){
        background: #E5E7E9;
        color: black;
    }

    .autocomplete .searchResult li:hover{
        cursor: pointer;
        background: #CACFD2;
    }
</style>

<!--breadcrumb-->
<div class="page-breadcrumb d-flex align-items-center mb-3 px-3 px-md-0">
  <div class="breadcrumb-title pe-3"><i class="bi bi-list"></i> {{ @$voucher_type->voucher_title }} STATEMENT</div>

  <div class="ms-auto">
    <div class="btn-group">
      <a href="{{ route('receipt-voucher.index') }}" class="btn btn-outline-secondary me-2"><i class="bx bx-arrow-back ms-0 me-1"></i>Back</a>
    </div>
  </div>
</div>
<!--end breadcrumb-->

<div class="card style_table shadow-none radius-5 min-height">
 <x-FinancialAccounting.StatementSearchForm />
</div>

<div id="tables">
    @include('invoice-formats.receipt-voucher.statement-table')

    <div class="row print-buttons" style="display: none;">
        <div class="col-md-6" style="text-align: right;">
            <button id="btn_print" type="button" class="btn btn-primary btn-lg"><i class="bi bi-printer text-white"></i> Print Statement </button>
        </div>

        <div class="col-md-6" style="text-align: left;">
            <a href="javascript:;" class="btn btn-outline-primary export-statement"><i class="bi bi-download"></i> Export</a>
        </div>
    </div>
</div>
@endsection
@section('js')
<script type="text/javascript" src="{{ asset('admin/plugins/datepicker/js/bootstrap-datepicker.js')}}"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/table2excel@1.0.4/dist/table2excel.min.js"></script>
<script type="text/javascript">
   $('[name="from_date"]').datepicker({
        format: "{!! $companyDateFormate??'dd-mm-yyyy' !!}",
        autoclose: true,
        //startDate: financialYearDates.fromDate,//optional
        //endDate: financialYearDates.toDate//optional
        }).datepicker("setDate", new Date());
    $('[name="to_date"]').datepicker({
    format: "{!! $companyDateFormate??'dd-mm-yyyy' !!}",
    autoclose: true,
    //startDate: financialYearDates.fromDate,//optional
    //endDate: financialYearDates.toDate//optional
    }).datepicker("setDate", new Date());

  $(document).ready(function() {        

    function clear_icon() {
      $('#id_icon').html('');
      $('#post_title_icon').html('');
    }

    function populateReceiptTable(data) {
        const $receiptTableBody = $('#receipt-table-body');
        $receiptTableBody.empty(); // Clear the existing table body

        if (data.accountReceipt && Object.keys(data.accountReceipt).length > 0) {
            let grandTotal = 0;
            let totalByTransactionMode = {};
            $('.print-buttons').show();

            data.accountReceipt.forEach((receipt, i) => {

                if (receipt.transaction_type === 'CREDIT') return;

                const transactionMode = receipt.payment_mode || '';
                const accountName = receipt.account_name || '';

                if (!totalByTransactionMode[accountName]) {
                    totalByTransactionMode[accountName] = {};
                }
                totalByTransactionMode[accountName][transactionMode] = (parseInt(totalByTransactionMode[accountName][transactionMode]) || 0) + parseInt(receipt.amount);


                grandTotal = parseFloat(grandTotal) + parseFloat(receipt.amount);
                    const receiptRow = `
                        <tr>
                            <td >${i + 1}</td>
                            <td >${receipt.receipt_no || ''}</td>
                            <td >${receipt.receipt_date ? formatedDateTime(receipt.receipt_date + ' ' + receipt.receipt_time) : ''}</td>
                            <td >${receipt.account_title || ''} ${receipt.credit_account_name || ''}</td>
                            <td >${receipt.voucher_type || ''}</td>
                            <td >${receipt.prepared_by ? ' ' + receipt.prepared_by : ''}</td>
                            <td >${receipt.voucher_type === "OPD Booking" ? receipt.booking_no || '' : receipt.main_invoice_no || ''}</td>
                            <td >${receipt.voucher_type === "OPD Booking" ? (receipt.booking_date_time ? formattedDate(receipt.booking_date_time) : '') : (receipt.invoice_created_at ? formattedDate(receipt.invoice_created_at) : '')}</td>
                            <td>${accountName}</td>
                            <td>${transactionMode}</td>
                            <td style="text-align: right;">${receipt.amount > 0 ? convertDecimelPoint(receipt.amount) : "0"}</td>
                        </tr>
                    `;
                    $receiptTableBody.append(receiptRow);

            });


            // Adding summary rows for each transaction mode
            Object.keys(totalByTransactionMode).forEach(transactionMode => {
                const paymentModes = totalByTransactionMode[transactionMode];
                $receiptTableBody.append(`
                    <tr>
                        <td colspan="10" style="text-align: right; text-transform: uppercase;border-right:none !important"><b>${transactionMode} SUMMARY</b></td>
                        <td style="border-left:none !important"></td>
                    </tr>
                `);
                Object.keys(paymentModes).forEach(paymentMode => {
                    $receiptTableBody.append(`
                        <tr>
                            <td colspan="10" style="text-align: right; text-transform: uppercase;">TOTAL ${paymentMode}</td>
                            <td style="text-align: right;"><b>${convertDecimelPoint(paymentModes[paymentMode])}</b></td>
                        </tr>
                    `);
                });
            });

            // Adding grand total row
            $receiptTableBody.append(`
                <tr>
                    <td colspan="10" style="text-align: right;text-transform: uppercase;"><b>Grand TOTAL</b></td>
                    <td style="text-align: right;"><b>${convertDecimelPoint(grandTotal)}</b></td>
                </tr>
            `);
        } else {
            $receiptTableBody.append('<tr><td colspan="11" style="text-align: center;">No Records Found</td></tr>');
        }
    }

    function convertDecimelPoint(amount) {
        if (amount && !isNaN(amount)) {
            // Assuming 'decimalLength' is stored in sessionStorage or set as a default value
            const decimalLength = Number("{!! is_numeric(\Session::get('decimallength')) ? \Session::get('decimallength') : 2 !!}") || 2;
            amount = Number(amount).toFixed(decimalLength);
        } else {
            amount = '0.00'; // Default format if amount is not valid
        }
        return amount;
    }


    function fetch_data(branch, account, from_date, to_date,created_by,payment_mode,voucher_type) {
      $('#submit').prop('disabled',true);
      $('#submit').html('Loading Please Wait.');
      $('.print-buttons').hide();
      $.ajax({
        url: "?branch=" + branch + "&account=" + account + "&from_date=" + from_date + "&to_date=" + to_date + "&created_by=" + created_by + "&payment_mode="+payment_mode + "&voucher_type="+voucher_type,
        success: function(data) {
          // if(data.status == true) { 
            $('.head-from-date').html(from_date);
            $('.head-to-date').html(to_date);

            populateReceiptTable(data);

            $('#submit').prop('disabled',false);
            $('#submit').html('<i class="bi bi-search"></i> Search');
          // }
        }
      })
    }
    $("body").on("click", '.export-statement', function(event) {
        var downloadLink;
        var dataType = 'application/vnd.ms-excel';
        var tableSelect = document.getElementById("receiptdatatable");
        var tableHTML = tableSelect.outerHTML.replace(/ /g, '%20');
        
        // Specify file name
        filename = 'receipt-voucher-statement.xls';
        
        // Create download link element
        downloadLink = document.createElement("a");
        
        document.body.appendChild(downloadLink);
        
        if(navigator.msSaveOrOpenBlob){
            var blob = new Blob(['\ufeff', tableHTML], {
                type: dataType
            });
            navigator.msSaveOrOpenBlob( blob, filename);
        }else{
            downloadLink.href = 'data:' + dataType + ', ' + tableHTML;

            downloadLink.download = filename;

            downloadLink.click();
        }
    });

    $("body").on("click", '#submit', function(event) {
      var branch = $('#branch').val();
      var account = $('[name="account"]').val();
      var doctor_ac_id = $('#doctor_ac_id').val();
      var from_date = $('#from_date').val();
      var to_date = $('#to_date').val();
      var chamber_id = $('#chamber').val();
      var created_by = $('#created_by').val()
      var payment_mode = $('#payment_mode').val();
      var voucher_type = $('#voucher_type').val();


      fetch_data(branch, account, from_date, to_date,created_by,payment_mode,voucher_type);
    });


  });
</script>

<script>
    $(document).ready(function() {
        var page_title = $('#page_title').val();
        $("title").html(page_title);
        $(document).on('click', '#btn_print', function(event) {
            event.preventDefault();
            $('#btn_back').hide();
            printInvoice();
            return;
            // printInvoice(page_title);
            /*$('#print_div').printThis({
                importStyle: true,
            });*/
            $(this).hide();
            var printContents = document.getElementById('print_div').innerHTML;
            var originalContents = document.body.innerHTML;

            document.body.innerHTML = printContents;

            window.print();

            document.body.innerHTML = originalContents;

            $(this).show();
            $('#btn_back').show();
            $('#btn_print').show();
        });

        $(document).on('click', '#btn_pdf', function(e) {
            html2canvas($('#print_div'), {
                background: "#ffffff",
                onrendered: function(canvas) {
                    var myImage = canvas.toDataURL("image/png", 1.0);
                    // Adjust width and height
                    var imgWidth = (canvas.width * 43) / 250;
                    var imgHeight = (canvas.height * 48) / 250;
                    // jspdf changes
                    var pdf = new jsPDF('p', 'mm', 'a4');
                    pdf.addImage(myImage, 'png', 5, 5, imgWidth, imgHeight); // 2: 19
                    pdf.save(`${$('#page_title').val()}.pdf`);
                }
            });
        });
    });

    function printInvoice() {
        let printDiv = $('#print_div').html();
        let content = window.open('', '', 'height=750px,width=960px');
        let doc = content.document;
        let head = doc.head;
        let body = doc.body;

        $(head).append('<Title>{{$pageTitle}}</Title>');
        $(head).append('<link rel="stylesheet" href="{{ asset('admin/css/bootstrap.min.css') }}" type="text/css">');
        $(head).append('<link rel="stylesheet" href="{{ asset('admin/css/print.css') }}" type="text/css">');
        $(head).append('<style>@page {size: auto;}</style>');
        $(body).append(printDiv);

        setTimeout(function() {
            content.print();
        }, 500);
    }

    function formatedDateTime(datetime = '') {
        if (!datetime || datetime === '0000-00-00 00:00:00') {
            return '';
        }
        @php
          $company_data    = \Session::get('company_data');

          $time_format     = $company_data['time_format'] ?? "H:i A";
          $date_format     = $company_data['date_format'] ?? "m-d-Y";
        @endphp

        const timeFormat = "{!! $time_format !!}";
        const dateFormat = "{!! $date_format !!}";
        const dateObj = new Date(datetime);

        // Function to format the date according to the provided format
        const formatDate = (dateObj, format) => {
            const day = dateObj.getDate().toString().padStart(2, '0');
            const month = (dateObj.getMonth() + 1).toString().padStart(2, '0');
            const year = dateObj.getFullYear();

            // Replace format placeholders with actual date values
            let formattedDate = format
                .replace('YYYY', year)
                .replace('MM', month)
                .replace('DD', day)
                .replace('m', month) // Support for "m" format
                .replace('Y', year)  // Support for "Y" format
                .replace('d', day);  // Support for "d" format

            return formattedDate;
        };

        // Function to format the time according to the provided format
        const formatTime = (dateObj, format) => {
            const options = {
                second: undefined, // Ensure seconds are not shown
            };
            
            if (format.includes('HH')) options.hour = '2-digit';
            if (format.includes('mm')) options.minute = '2-digit';
            if (format.includes('A')) options.hour12 = true;
            if (!format.includes('ss')) options.second = undefined;

            return dateObj.toLocaleTimeString('en-US', options);
        };

        const formattedDate = formatDate(dateObj, dateFormat);
        const formattedTime = formatTime(dateObj, timeFormat);

        return `${formattedDate}, ${formattedTime}`;
    }
function formattedDate(date = '') {
    if (!date || date === '0000-00-00' || (!isDate(date) && !isValidDateTime(date))) {
        return '';
    }

    @php
      $company_data    = \Session::get('company_data');

      $date_format     = $company_data['date_format'] ?? "m-d-Y";
    @endphp

    const dateFormat = "{!! $date_format !!}";

    const dateObj = new Date(date);
    return formatDate(dateObj, dateFormat);
}

// Helper function to check if a date string is valid (assuming it’s in a recognized format)
function isDate(dateString) {
    const date = Date.parse(dateString);
    return !isNaN(date);
}

// Helper function to check if a datetime string matches the 'Y-m-d H:i:s' format
function isValidDateTime(dateTimeString) {
    const regex = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/;
    return regex.test(dateTimeString) && !isNaN(Date.parse(dateTimeString));
}

// Function to format the date according to the provided format
function formatDate(dateObj, format) {
    const options = {};

    if (format.includes('YYYY')) options.year = 'numeric';
    if (format.includes('MM')) options.month = '2-digit';
    if (format.includes('DD')) options.day = '2-digit';

    return dateObj.toLocaleDateString('en-US', options);
}
</script>
@endsection