@extends('layouts.master')

@section('content')
    <!-- ===== Page-Content ===== -->
    <?php //echo "<pre>"; print_r($data); exit();
    ?>
    <!-- .row -->
    <div class="row hidden-print">
        <div class="card p-3">
            <h3 class="box-title pull-left">General Ledger</h3>
            <!-- <a class="btn btn-success pull-right" href="{{ url('user/create') }}"><i class="icon-plus"></i> Add New</a> -->
            <div class="clearfix"></div>
            <hr>

            <div class="col-md-12">
                <input type="hidden" id="hdn_businessname" value="<?php if (isset($business_name_id)) {
                    echo $business_name_id;
                } ?>" />

                <form class="form-horizontal" method="POST" action="{{ route('general_ledger_report') }}">
                    {{ csrf_field() }}
                    <div class="row">
                        <div class="col-md-6">
                            <div class="portlet light">
                                <div class="form-horizontal form-body">
                                    <fieldset>
                                        <div class="form-group mb-3 mb-3">
                                            <label for="fromdate" class="col-md-4 control-label">From Date</label>
                                            <div class="col-md-8">
                                                <div class="input-group mydatepicker date date-picker margin-bottom-5"
                                                    data-date-format="dd-mm-yyyy">

                                                    <input type="text" id="fromdate" required autocomplete="off"
                                                        class="form-control form-filter" name="fromdate" placeholder="From"
                                                        value="<?php if (isset($from_date)) {
                                                            echo date('m/d/Y', strtotime($from_date));
                                                        } ?>">

                                                </div>
                                            </div>
                                        </div>

                                        <div class="form-group mb-3">
                                            <label for="todate" class="col-md-4 control-label">To Date</label>
                                            <div class="col-md-8">
                                                <div class="input-group mydatepicker date date-picker"
                                                    data-date-format="dd-mm-yyyy">
                                                    <input type="text" id="todate" required autocomplete="off"
                                                        class="form-control form-filter" name="date_to" placeholder="To"
                                                        value="<?php if (isset($to_date)) {
                                                            echo date('m/d/Y', strtotime($to_date));
                                                        } ?>">
                                                </div>
                                            </div>
                                        </div>

                                        <div class="form-group mb-3">
                                            <label for="sub_account_from" class="col-md-4 control-label">From Acc.</label>
                                            <div class="col-md-8">
                                                <select name="transaction_account_from" id="transaction_account_from"
                                                    class="form-control form-filter input-md">
                                                    <option value="">All</option>
                                                    <?php if (isset($from_account)) {
                                                        $f = $from_account;
                                                    } else {
                                                        $f = 0;
                                                    } ?>
                                                    @foreach ($accounts as $row)
                                                        <option <?php echo $f == $row->id_transaction_account ? 'selected' : ''; ?>
                                                            value="{{ $row->id_transaction_account }}">
                                                            {{ $row->main_account_number . '-' . $row->control_account_number . '-' . $row->sub_control_account_number . '|' . $row->transaction_account_name }}
                                                        </option>
                                                    @endforeach
                                                </select>
                                            </div>
                                        </div>

                                        <div class="form-group mb-3">
                                            <label for="sub_account_to" class="col-md-4 control-label">To Acc.</label>
                                            <div class="col-md-8">
                                                <select name="transaction_account_to" id="transaction_account_to"
                                                    class="form-control form-filter input-md">
                                                    <option value="">All</option>
                                                    <?php if (isset($to_account)) {
                                                        $t = $to_account;
                                                    } else {
                                                        $t = 0;
                                                    } ?>
                                                    @foreach ($accounts as $row)
                                                        <option <?php echo $t == $row->id_transaction_account ? 'selected' : ''; ?>
                                                            value="{{ $row->id_transaction_account }}">
                                                            {{ $row->main_account_number . '-' . $row->control_account_number . '-' . $row->sub_control_account_number . '|' . $row->transaction_account_name }}
                                                        </option>
                                                    @endforeach
                                                </select>
                                            </div>
                                        </div>

                                    </fieldset>
                                </div>
                            </div>
                        </div>

                        <div class="col-md-6">
                            <div class="portlet light">
                                <div class="portlet-body">
                                    <div class="form-horizontal form-body">

                                        <fieldset>

                                            {{-- <div class="form-group mb-3">
                                                            <label class="control-label col-md-4">Cost Center Type:</label>
                                                            <div class="col-md-8">
                                                                <select id="cost_center_type" name="cost_center_type" class="form-control">
                                                                    <option value="All">All</option>
                                                                    <?php if (isset($cost_center_type_id)) {
                                                                        $cc = $cost_center_type_id;
                                                                    } else {
                                                                        $cc = 0;
                                                                    } ?>
                                                                    @foreach ($cost_center_type as $row)
                                                                        <option {{ $cc == $row->id_cost_center_type ? 'selected' : '' }} value="{{ $row->id_cost_center_type }}">
                                                                            {{ $row->cost_center_type }}</option>
                                                                    @endforeach
                                                                </select>
                                                            </div>
                                                        </div> --}}

                                            {{-- <div class="form-group mb-3">
                                                            <label for="sub_account_to" class="col-md-4 control-label">Cost Center.</label>
                                                            <div class="col-md-8">
                                                                <select name="cost_center" id="cost_center" class="form-control form-filter input-md">
                                                                </select>
                                                            </div>
                                                        </div> --}}

                                            <div class="form-group mb-3">
                                                <label for="business_partner" class="form-label">Business Partner <span
                                                        style="color:red;">*</span></label>
                                                <select onchange="getPartnerData();" id="business_partner"
                                                    name="business_partner" class="form-control select2" tabindex="-1"
                                                    aria-hidden="true">
                                                    <option value="">Select</option>
                                                    <option value="employee">Employee</option>
                                                    <option value="customer">Customer</option>
                                                    <option value="suppliers">Supplier</option>
                                                    <option value="other">Other</option>
                                                </select>
                                            </div>
                                            <div class="form-group mb-3">
                                                <div class="mb-3">
                                                    <label for="partner_name" class="form-label">Partner Name <span
                                                            style="color:rgb(255, 0, 0);">*</span></label>
                                                    <select id="partner_name" name="partner_name"
                                                        class="form-control select2" tabindex="-1" aria-hidden="true">
                                                        <option value="">Select</option>
                                                    </select>
                                                </div>
                                                {{-- <div class="col-md-8">
                                                                <select id="business_type" name="business_type" class="form-control">
                                                                    <option value="All">All</option>
                                                                    <?php if (isset($business_type)) {
                                                                        $bp = $business_type;
                                                                    } else {
                                                                        $bp = '-';
                                                                    } ?>
                                                                    @foreach ($business_partners as $row)
                                                                        <option {{ $bp == $row->id_business_type ? 'selected' : '' }} value="{{ $row->id_business_type }}">
                                                                            {{ $row->business_type }}</option>
                                                                    @endforeach
                                                                    <select onchange="getPartnerData();" id="business_partner" name="business_partner" class="form-control select2" tabindex="-1" aria-hidden="true">
                                                                        <option value="">Select</option>
                                                                        <option value="employee">Employee</option>
                                                                        <option value="customer">Customer</option>
                                                                        <option value="suppliers">Supplier</option>
                                                                        <option value="other">Other</option>
                                                                        <option {{ $bp == 0 ? '' : '' }} value="0">Walk in Customer</option>
                                                                    </select>
                                                                </select>
                                                            </div> --}}
                                            </div>

                                            {{-- <div class="form-group mb-3">
                                                            <label class="col-md-4 control-label">Business Name.</label>
                                                            <div class="col-md-8">
                                                                <select name="business_name" id="business_name" class="form-control form-filter input-md">
                                                                    <option value="All">All</option>
                                                                </select>
                                                            </div>
                                                        </div> --}}

                                        </fieldset>
                                        <div style="text-align: right;">
                                            <button type="submit" class="btn btn-primary"><i class="fa fa-search"></i>
                                                Run</button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </form>


            </div>

        </div>
    </div>

    <!-- ===== Table for result ===== -->

    <?php if(isset($data)): ?>
    <div class="printableArea mt-5">
        <div class="row">
            <!-- .row -->
            <div class="col-md-12">
                <div class="card p-3">
                    <h6><strong> Statement of Account</strong></h6>
                    <h6>From :&nbsp;&nbsp; <span id="fdate"><?php if (isset($from_date)) {
                        echo date('d-m-Y', strtotime($from_date));
                    } ?></span> &nbsp;&nbsp;&nbsp;Till
                        &nbsp;&nbsp; : <span id="tdate"><?php if (isset($to_date)) {
                            echo date('d-m-Y', strtotime($to_date));
                        } ?></span> <span class="pull-right">Statement
                            Date: <?= date('d-m-Y') ?></span> </h6>

                    <div class="tools pull-right hidden-xs">
                        <button class="btn btn-inverse waves-effect waves-light" onclick='window.print();'><i
                                class="fa fa-print"></i></button>
                    </div>

                    <?php $openingBlance = 0; foreach($data as $index=>$value): ?>

                    <?php $opening_debit = $value['ob'][0]->debit; ?>
                    <?php $opening_credit = $value['ob'][0]->credit; ?>

                    <?php $ac = $value['av']->main_account_number . '-' . $value['av']->control_account_number . '-' . $value['av']->sub_control_account_number . '-' . $value['av']->transaction_account_number; ?>
                    <?php $bp_name = isset($value['details'][0]->bp_name) ? $value['details'][0]->bp_name : 0; ?>

                    <table class="" style=" width: 100%;margin-top: -10px;" cellspacing="0" id="podetailstbl"
                        class="customtble">
                        <thead>
                            <tr>
                                <th style="padding: 6px 5px 6px 5px;border-bottom: 1px solid black;" colspan="5">
                                    A/C Title :- {{ $value['av']->transaction_account_name }}</th>
                                <th style="padding: 6px 5px 6px 5px;border-bottom: 1px solid black;" colspan="3">
                                    A/C No : {{ $ac }} </th>
                            </tr>
                            <tr role="row" class="heading">
                                <th style="padding: 6px 5px 6px 5px;border: 1px solid black;width:12%;">Date / تاریخ</th>
                                <th style="padding: 6px 5px 6px 5px;border: 1px solid black;width:10%;">Voucher # / واؤچر
                                </th>
                                <th style="padding: 6px 5px 6px 5px;border: 1px solid black;width:25%;">
                                    Description / تفصیل
                                </th>
                                <th style="padding: 6px 5px 6px 5px;border: 1px solid black;width:20%;">
                                    Business Partner / بزنس پارٹنر
                                </th>
                                <th style="padding: 6px 5px 6px 5px;border: 1px solid black;width:5%;">
                                    Check/Slip# / چیک/پرچی
                                </th>
                                <th style="padding: 6px 5px 6px 5px;border: 1px solid black;text-align: right;width:10%;">
                                    Debit / ڈیبٹ رقم
                                </th>
                                <th style="padding: 6px 5px 6px 5px;border: 1px solid black;text-align: right;width:10%;">
                                    Credit / کریڈٹ رقم
                                </th>
                                <th style="padding: 6px 5px 6px 5px;border: 1px solid black;text-align: right;width:15%;">
                                    Balance / میزان
                                </th>
                            </tr>
                        </thead>
                        <tr>
                            <td style="font-size: 12px !important;padding: 6px 5px 6px 5px;border: 1px solid black;">
                            </td>
                            <td style="font-size: 12px !important;padding: 6px 5px 6px 5px;border: 1px solid black;">
                            </td>
                            <td style="font-size: 12px !important;padding: 6px 5px 6px 5px;border: 1px solid black;">
                                Opening Balance</td>
                            <td style="font-size: 12px !important;padding: 6px 5px 6px 5px;border: 1px solid black;">
                            </td>
                            <td style="font-size: 12px !important;padding: 6px 5px 6px 5px;border: 1px solid black;">
                            </td>
                            <td
                                style="font-size: 12px !important;padding: 6px 5px 6px 5px;border: 1px solid black;text-align: right;">
                            </td>
                            <td
                                style="font-size: 12px !important;padding: 6px 5px 6px 5px;border: 1px solid black;text-align: right;">
                            </td>
                            <td
                                style="font-size: 12px !important;padding: 6px 5px 6px 5px;border: 1px solid black;text-align: right;">
                                {{ number_format($openingBlance, 2) }}</td>

                        </tr>
                        <tbody>
                            <?php $debit = 0;
                            $credit = 0; ?>
                            @foreach ($value['details'] as $tras)
                                <tr>


                                    <td
                                        style="font-size: 12px !important;padding: 6px 5px 6px 5px;border: 1px solid black;">
                                        {{ date('d-m-y', strtotime($tras->date)) }}</td>
                                    <td
                                        style="font-size: 12px !important;padding: 6px 5px 6px 5px;border: 1px solid black;">
                                        {{ $tras->voucher_number }}</td>
                                    <td
                                        style="font-size: 12px !important;padding: 6px 5px 6px 5px;border: 1px solid black;">
                                        {{ $tras->remarks }}</td>
                                    <td
                                        style="font-size: 12px !important;padding: 6px 5px 6px 5px;border: 1px solid black;">
                                        {{ $tras->partner_name }} <br /> ({{ $tras->business_partner_type }})</td>
                                    <td
                                        style="font-size: 12px !important;padding: 6px 5px 6px 5px;border: 1px solid black;">
                                        {{ $tras->instrument }}</td>
                                    <td
                                        style="font-size: 12px !important;padding: 6px 5px 6px 5px;border: 1px solid black;text-align: right;">
                                        {{ number_format($tras->debit, 2) }}</td>
                                    <td
                                        style="font-size: 12px !important;padding: 6px 5px 6px 5px;border: 1px solid black;text-align: right;">
                                        {{ number_format($tras->credit, 2) }}</td>
                                    <td
                                        style="font-size: 12px !important;padding: 6px 5px 6px 5px;border: 1px solid black;text-align: right;">
                                        {{ number_format($openingBlance, 2) }}</td>

                                    <?php $debit += $tras->debit; ?>
                                    <?php $credit += $tras->credit; ?>
                                </tr>
                            @endforeach
                        </tbody>

                        <tfoot>
                            <tr role="row" class="heading">

                                <th colspan="5"
                                    style="padding: 6px 5px 6px 5px;border: 0px solid black;width:5%;text-align: right;">
                                    Total / کل &nbsp;</th>
                                <th style="padding: 6px 5px 6px 5px;border: 1px solid black;text-align: right;width:10%;">
                                    {{ number_format($debit, 2) }}</th>
                                <th style="padding: 6px 5px 6px 5px;border: 1px solid black;text-align: right;width:10%;">
                                    {{ number_format($credit, 2) }}</th>
                                <th style="padding: 6px 5px 6px 5px;border: 1px solid black;text-align: right;width:15%;">
                                    {{ number_format($openingBlance, 2) }}</th>
                            </tr>
                            <!--  <tr style="font-weight: bold;">
                                                                                                                                                                        <td colspan="5" style="text-align: right;">Total : </td>
                                                                                                                                                                        <td class="text-right" id="totalDebits">{{ number_format($debit, 2) }}</td>
                                                                                                                                                                        <td class="text-right" id="totalCredits">{{ number_format($credit, 2) }}</td>
                                                                                                                                                                        <td class="text-right" id="totalBalance">{{ number_format($openingBlance, 2) }}</td>
                                                                                                                                                                    </tr> -->
                        </tfoot>

                    </table>
                    <br />
                    <?php $openingBlance =0; endforeach; ?>
                </div>
            </div>
        </div>
    </div>

    </div>

    <?php endif; ?>

    <!-- ===== Page-Content-End ===== -->
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />

    <!-- jQuery (required for Select2) -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

    <!-- Select2 JS -->
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script>
        $('#business_partner').select2({
            theme: 'default'
        });
        $('#partner_name').select2({
            theme: 'default'
        });
        jQuery(document).ready(function() {
            var businessname = $("#hdn_businessname").val();
            BusinessName(businessname);
            // Uncomment and use the following lines as needed
            // getBP(); // Get Business partner
            // getCC(); // Get Cost Center

            // Initialize DatePickers
            $('#fromdate').datepicker({
                autoclose: true,
                todayHighlight: true
            });

            $('#todate').datepicker({
                autoclose: true,
                todayHighlight: true
            });

            // Initialize Select2 elements
            $('#transaction_account_from').select2();
            $('#transaction_account_to').select2();
            $('#cost_center').select2();
            $('#business_name').select2();

            // Event to change Business Name based on Business Type
            $("#business_type").change(function() {
                BusinessName(0); // Reset Business Name when Business Type changes
            });

            // Event to change Cost Center based on Cost Center Type
            $("#cost_center_type").change(function() {
                var centertype = $("#cost_center_type option:selected").val();
                if ($("#ccost_center_type option:selected").text() == "Select") {
                    $('#ccost_center').html('');
                    return false;
                }
                if (centertype === 'select') {
                    return false;
                }

                $.ajax({
                    type: "POST",
                    url: "{{ url('get_cost_center') }}",
                    dataType: 'json',
                    cache: false,
                    async: false,
                    data: {
                        ctype: centertype
                    },
                    beforeSend: function(xhr) {
                        xhr.setRequestHeader('X-CSRF-Token', "{{ csrf_token() }}");
                    },
                    success: function(data) {
                        var mdata = data;
                        if (mdata.length > 0) {
                            var html = '';
                            $('#ccost_center').html('');
                            html += '<option value="select">Select</option>';
                            for (var x = 0; x < mdata.length; x++) {
                                html += '<option value="' + mdata[x].id + '">' + mdata[x].name +
                                    '</option>';
                            }
                            $('#cost_center').html(html);
                        } else {
                            $('#cost_center').html('');
                        }
                    }
                });
            });

        });

        // Function to update Business Name dropdown based on Business Type
        function BusinessName(businessname) {
            var bustype = $("#business_type option:selected").val();
            if (bustype == '0') {
                $('#business_name').html('');
                $('#business_name').html('<option value="0">Walk in Customer</option>');
                return false;
            }

            if (bustype == 'All') {
                $('#business_name').html('');
                $('#business_name').html('<option value="All">All</option>');
                return false;
            }

            if (bustype === 'select') {
                return false;
            }

            var tax_for = '';
            if (bustype === '1') {
                tax_for = 1;
            } else if (bustype === '2') {
                tax_for = 1;
            }

            $.ajax({
                type: "POST",
                url: "{{ url('get_business_partners') }}",
                dataType: 'json',
                cache: false,
                async: false,
                data: {
                    bt: bustype,
                    tax_id: tax_for
                },
                beforeSend: function(xhr) {
                    xhr.setRequestHeader('X-CSRF-Token', "{{ csrf_token() }}");
                },
                success: function(data) {
                    var mdata = data;
                    if (mdata.length > 0) {
                        var html = '';
                        $('#business_name').html('');
                        html += '<option value="All">All</option>';
                        for (var x = 0; x < mdata.length; x++) {
                            html += '<option value="' + mdata[x].id + '" tax="' + mdata[x].tax + '">' + mdata[x]
                                .name + '</option>';
                        }
                        $('#business_name').html(html);
                        if (html) {
                            $('#business_name option[value="' + businessname + '"').attr('selected',
                                'selected');
                        }
                    } else {
                        $('#business_name').html('');
                    }
                }
            });
        }

        // Function to get Business Partners based on Business Type
        function getPartnerData() {
            var selectedPartnerType = $('#business_partner').val();

            if (selectedPartnerType === 'employee' || selectedPartnerType === 'customer' || selectedPartnerType ===
                'suppliers') {
                $.ajax({
                    url: '{{ route('get-partner-data') }}',
                    type: 'GET',
                    data: {
                        type: selectedPartnerType
                    },
                    dataType: 'json',
                    success: function(data) {
                        $('#partner_name').empty();
                        $('#partner_name').append('<option value="">Select</option>');

                        if (data && Object.keys(data).length > 0) {
                            $.each(data, function(key, value) {
                                $('#partner_name').append('<option value="' + value + '">' + value +
                                    '</option>');
                            });

                            $('#partner_name').val($('#partner_name option:eq(1)').val());
                        } else {
                            alert("No partners found for the selected type.");
                        }
                        $('#addVendorButtonContainer').hide();
                    },
                    error: function(xhr, status, error) {
                        console.error("An error occurred: " + xhr.responseText);
                        alert("An error occurred while fetching partner data. Please try again.");
                    }
                });
            } else if (selectedPartnerType === 'other') {
                $('#addVendorButtonContainer').show();
                $('#partner_name').empty();
                $('#partner_name').append('<option value="">Select</option>');

                // Load existing vendors to the partner_name dropdown
                $.ajax({
                    url: '{{ route('get-partner-data') }}',
                    type: 'GET',
                    data: {
                        type: 'other'
                    },
                    dataType: 'json',
                    success: function(data) {
                        $.each(data, function(key, value) {
                            $('#partner_name').append('<option value="' + key + '">' + value +
                                '</option>');
                        });
                    },
                    error: function(xhr, status, error) {
                        console.error("An error occurred: " + xhr.responseText);
                        alert("An error occurred while fetching vendor data. Please try again.");
                    }
                });
            } else {
                $('#addVendorButtonContainer').hide();
                $('#partner_name').empty();
                $('#partner_name').append('<option value="">Select</option>');
            }
        }

        // Function to print the content of a div
        function printDiv(divName) {
            var printContents = document.getElementById(divName).innerHTML;
            var originalContents = document.body.innerHTML;

            document.body.innerHTML = printContents;
            window.print();
            document.body.innerHTML = originalContents;
        }

        // Assign keyboard shortcut for print functionality
        shortcut.add("ctrl+p", function() {
            printDiv('printableArea');
        });
    </script>
    <script src="http://www.openjs.com/scripts/events/keyboard_shortcuts/shortcut.js"></script>
@endsection
