@extends('admin.layouts.app')

@section('title', ' Current Balance Report')

@section('content')
    <div class="page-header">
        <div class="page-title">
            <h4>Current Balance Report</h4>
            <ul class="breadcrumb">
                <li class="breadcrumb-item active">Current Balance Report</li>
            </ul>
        </div>
        <div class="text-right">
            <button class="btn btn-primary" onclick="printWithTimestamp()">Print Page</button>
        </div>
    </div>

    <div class="card">
        <div class="card-body">
            <div class="table-top">
                <div class="search-set">
                    <div class="search-input mt-2">
                        <a class="btn btn-searchset">
                            <img src="{{ asset('assets/img/icons/search-white.svg') }}" alt="img">
                        </a>
                    </div>
                </div>
                <div class="mb-3" style="margin-right: 35px !important;">
                    <form action="{{route('reports.current-balance-filter')}}" class="row gy-2 align-items-end"
                        method="post" style="margin-left:12px; gap:2rem;">
                        @csrf
                        <div class="col-md-3">
                            <label class="form-label" for="balance_category_id">Categories</label>
                            <select name="balance_category_id" id="balance_category_id"
                                class="form-select js-example-basic-single select2">
                                <option value="">Select Categories</option>
                                @foreach($categories as $category)
                                    <option value="{{$category->id}}" {{ isset($selectedCategoryId) && $selectedCategoryId == $category->id ? 'selected' : '' }}>{{$category->name}}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label" for="category_item_id">Items</label>
                            <select name="category_item_id[]" id="category_item_id"
                                class="form-select js-example-basic-single select2" multiple>
                                <option value="">Select Product</option>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <label class="form-label" for="till_date">Till Date</label>
                            <input type="date" name="till_date" id="till_date" class="form-control"
                                value="{{ $tillDate ?? '' }}">
                        </div>

                        <div class="col-md-2 d-flex gap-2">
                            <button type="submit" class="btn btn-sm btn-primary" id="balanceButton">Filter</button>
                            <button type="button" class="btn btn-sm btn-secondary" id="fifoReportButton"
                                data-url="{{ route('reports.fifo-report') }}">FIFO
                                Report</button>
                        </div>
                    </form>
                </div>
            </div>
            <div class="table-responsive">
                <table class="table datanew-local dataTable no-footer table-striped" id="balanceFilterTable">
                    <thead>
                        <tr>
                            <th>Code</th>
                            <th>Item Description</th>
                            <th>Category</th>
                            <th>Available Quantity</th>
                            <th>Unit</th>
                            <th>Avg. Rate</th>
                            <th>Total Value</th>
                        </tr>
                    </thead>
                    <tbody>
                        @php
                            $totalAvailableQuantity = 0;
                            $totalValue = 0;
                        @endphp
                        @foreach ($stocks as $stock)
                            @php
                                $balance = $stock['balance'] ?? 0;
                                $unitPrice = $stock['unit_price'] ?? 0;
                                $rowTotal = $balance * $unitPrice;

                                $totalAvailableQuantity += $balance;
                                $totalValue += $rowTotal;
                            @endphp
                            <tr>
                                <td>{{ $stock['code'] ?? 'N/A' }}</td>
                                <td>{{ $stock['name'] ?? 'N/A' }}</td>
                                <td>{{ $stock['category_name'] ?? 'N/A' }}</td>
                                <td>{{ $balance }}</td>
                                <td>{{ $stock['item_unit'] ?? 'N/A' }}</td>
                                <td>{{ number_format($unitPrice, 2) }}</td>
                                <td>{{ number_format($rowTotal, 2) }}</td>
                            </tr>
                        @endforeach
                    </tbody>
                    <tfoot>
                        <tr style="font-weight: bold; background-color: #f8f9fa;">
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td class="text-end">Total Value:</td>
                            <td>{{ number_format($totalValue, 2) }}</td>
                        </tr>
                    </tfoot>
                </table>
            </div>
        </div>
    </div>
    <!-- Print timestamp will be added here -->
    <div id="printTimestampContainer"></div>
    </div>

    <script>
        $(document).ready(function () {
            // DataTable initialization for Balance Report
            if ($('#balanceFilterTable').length > 0) {
                $('#balanceFilterTable').DataTable({
                    // Removed 'destroy: true' as it's no longer needed with a unique class
                    bFilter: true,
                    dom: '<"top"fB>t<"bottom"lpi><"clear">',
                    pagingType: "numbers",
                    ordering: true,
                    language: {
                        search: " ",
                        sLengthMenu: "_MENU_",
                        searchPlaceholder: "Search...",
                        info: "_START_ - _END_ of _TOTAL_ items",
                    },
                    buttons: [
                        {
                            extend: 'pdfHtml5',
                            text: '<i class="fas fa-file-pdf"></i> Export PDF',
                            title: 'Current Balance Report',
                            filename: 'current_balance_report',
                            orientation: 'portrait',
                            pageSize: 'A4',
                            footer: true,
                            customize: function (doc) {
                                doc.content[0].text = 'Current Balance Report';
                                doc.content[0].alignment = 'center';
                                doc.content[0].margin = [0, 0, 0, 30];

                                // Set margins and layout for the table
                                doc.content[1].margin = [20, 10, 20, 10];
                                var objLayout = {};
                                objLayout['hLineWidth'] = function (i) { return 0.5; };
                                objLayout['vLineWidth'] = function (i) { return 0.5; };
                                objLayout['hLineColor'] = function (i) { return '#aaa'; };
                                objLayout['vLineColor'] = function (i) { return '#aaa'; };
                                objLayout['paddingLeft'] = function (i) { return 8; };
                                objLayout['paddingRight'] = function (i) { return 8; };
                                objLayout['paddingTop'] = function (i) { return 6; };
                                objLayout['paddingBottom'] = function (i) { return 6; };
                                doc.content[1].layout = objLayout;

                                // Center align the headers and content
                                doc.content[1].table.body[0].forEach(function (header) {
                                    header.alignment = 'center';
                                });
                                doc.content[1].table.body.forEach(function (row, index) {
                                    if (index !== 0) {
                                        row.forEach(function (cell) {
                                            cell.alignment = 'center';
                                        });
                                    }
                                });

                                // Set font sizes
                                doc.styles.tableHeader.fontSize = 12;
                                doc.defaultStyle.fontSize = 10;

                                // --- Prepend Custom Headers ---
                                var now = new Date();
                                var dateStr = ('0' + now.getDate()).slice(-2) + '-' +
                                    ('0' + (now.getMonth() + 1)).slice(-2) + '-' +
                                    now.getFullYear();

                                doc.content.splice(0, 0,
                                    {
                                        text: 'Benson Pharmaceuticals',
                                        fontSize: 18,
                                        bold: true,
                                        alignment: 'center',
                                        margin: [0, 0, 0, 5]
                                    },
                                    {
                                        text: 'Category: ' + "{{$selectedCategoryName}}",
                                        fontSize: 12,
                                        italics: true,
                                        alignment: 'center',
                                        margin: [20, 0, 0, 10],
                                        absolutePosition: { x: 60, y: 120 }
                                    },
                                    {
                                        text: 'Date: ' + dateStr,
                                        fontSize: 10,
                                        alignment: 'left',
                                        margin: [20, 0, 0, 10],
                                        absolutePosition: { x: 60, y: 120 }
                                    }
                                );
                                // --- Add Footer with Timestamp and Page Numbers ---
                                doc.footer = function (currentPage, pageCount) {
                                    return {
                                        columns: [
                                            { text: 'Printed on: ' + new Date().toLocaleString(), alignment: 'left', margin: [40, 0] },
                                            { text: 'page ' + currentPage.toString() + '/' + pageCount, alignment: 'right', margin: [0, 0, 40, 0] }
                                        ],
                                        margin: [20, 0]
                                    };
                                };
                            }
                        },
                        // {
                        //     extend: 'excelHtml5',
                        //     text: 'Excel',
                        //     title: 'Current Balance Report',
                        //     filename: 'current_balance_report',
                        //     footer: true
                        // },
                        {
                            extend: 'csvHtml5',
                            text: '<i class="fas fa-file-csv"></i> Export CSV',
                            title: 'Current Balance Report',
                            filename: 'current_balance_report',
                            footer: true
                        },
                        // {
                        //     extend: 'print',
                        //     text: 'Print',
                        //     title: 'Current Balance Report',
                        //     footer: true,
                        //     customize: function (win) {
                        //         var selectedDate = $('#till_date').val();
                        //         var dateStr = selectedDate ? ' (Till: ' + selectedDate + ')' : '';
                        //         $(win.document.body).find('h1').text('Current Balance Report' + dateStr);

                        //         $(win.document.body).prepend(
                        //             '<div style="text-align:left; margin-bottom:10px; font-size: 10pt;">Printed on: ' + new Date().toLocaleString() + '</div>'
                        //         );
                        //     }
                        // },
                        // 'copy'
                    ],
                    initComplete: (settings, json) => {
                        $(".dataTables_filter").appendTo(".search-input");
                    }
                });
            }
        });



        // FIFO Report button
        $('#fifoReportButton').on('click', function (e) {
            e.preventDefault();
            console.log('FIFO Report button clicked');

            var $form = $(this).closest('form');
            var originalAction = $form.attr('action');
            var originalTarget = $form.attr('target') || '';

            // Validate that items are selected
            var selectedItems = $('#category_item_id').val();
            console.log('Selected items:', selectedItems);

            if (!selectedItems || (Array.isArray(selectedItems) && selectedItems.length === 0)) {
                alert('Please select at least one item.');
                return;
            }

            var fifoUrl = $(this).data('url') || '/report/fifo-report';
            console.log('Constructed FIFO URL:', fifoUrl);

            // Change action and target for a new tab submission
            $form.attr('action', fifoUrl);
            $form.attr('target', '_blank');

            // Explicitly set the method to POST if not already
            $form.attr('method', 'POST');

            console.log('Submitting form...');
            $form[0].submit(); // Use native submit to bypass any jQuery block

            // Reset form after a small delay to ensure Filter button still works correctly
            setTimeout(function () {
                console.log('Resetting form action to:', originalAction);
                $form.attr('action', originalAction);
                $form.attr('target', originalTarget);
            }, 1000);
        });

    </script>

<style>
    .dt-buttons .buttons-pdf {
        background-color: #dc3545 !important;
        border-color: #dc3545 !important;
        color: #fff !important;
        padding: 0.25rem 0.5rem;
        font-size: 0.875rem;
        border-radius: 0.2rem;
        font-weight: 500 !important;
        line-height: 1.5 !important;
        transition: background-color 0.15s ease-in-out, border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out !important;
        box-shadow: none !important;
        text-shadow: none !important;
    }
    .dt-buttons .buttons-csv {
        background-color: #198754 !important;
        border-color: #198754 !important;
        color: #fff !important;
        padding: 0.25rem 0.5rem;
        font-size: 0.875rem;
        border-radius: 0.2rem;
        font-weight: 500 !important;
        line-height: 1.5 !important;
        transition: background-color 0.15s ease-in-out, border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out !important;
        box-shadow: none !important;
        text-shadow: none !important;
    }

    /* Align the buttons group nicely */
    .dt-buttons {
        display: inline-flex !important;
        gap: 0.5rem !important;
    }
</style>
@endsection