@extends('admin.layouts.app')

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

    <div class="mb-3">
        <form action="{{ route('reports.financial-ledger') }}" class="row gy-2 gx-3 align-items-end" method="get">
        <div class="col-md">
              <label class="form-label" for="financial_year">Financial Year</label>
               <select class="form-control" name="financial_year" id="financial_year">
                <option value="">Select Financial Year</option>
            @php
                $currentYear = date('Y');
                $financialYears = [];
                for ($i = 0; $i < 5; $i++) { // show last 5 FYs
                    $startYear = $currentYear - $i;
                    $endYear = $startYear + 1;
                    $financialYears["$startYear-$endYear"] = "$startYear-$endYear";
                }
            @endphp

            @foreach ($financialYears as $fyValue => $fyLabel)
                <option value="{{ $fyValue }}" 
                    {{ (isset($selectedFY) && $selectedFY == $fyValue) ? 'selected' : '' }}>
                    {{ $fyLabel }}
                </option>
            @endforeach
            </select>
         </div>

            <div class="col-md">
                <label class="form-label" for="report_type">Report Type</label>
                <select name="report_type" id="report_type" class="form-select js-example-basic-single select2">
                    <option value="customer" {{ (isset($report_type) && $report_type == 'customer') ? 'selected' : '' }}>Customer / Franchiser</option>
                    <option value="product" {{ (isset($report_type) && $report_type == 'product') ? 'selected' : '' }}>Product</option>
                </select>
            </div>

            <div class="col-md" id="coa_div">
                <label class="form-label" for="coa_id">Chart of Accounts</label>
                <select name="coa_id" id="coa_id" class="form-select js-example-basic-single select2">
                    <option value="">Select Chart of Account</option>
                    @foreach ($coas as $coa)
                        <option value="{{ $coa->id }}" {{ isset($coa_id) && $coa->id == $coa_id ? 'selected' : '' }}>
                            {{ $coa->code ?? '-' }}
                            ({{ $coa->abbreviation ?? '-' }})
                            ({{ $coa->particular ?? '-' }})
                        </option>
                    @endforeach
                </select>
            </div>
            <div class="col-md" id="sub_coa_div">
                <label class="form-label" for="sub_coa_id">Sub Chart of Accounts</label>
                <select name="sub_coa_id" id="sub_coa_id" class="form-select js-example-basic-single select2">
                    <option value="">Select Sub Chart of Account</option>
                </select>
            </div>
            <div class="col-md" id="customer_div">
                <label class="form-label" for="franchiser">Customers</label>
                <select name="franchiser" id="franchiser" class="form-select js-example-basic-single select2">
                    <option value="">All Customers</option>
                    @foreach ($filtered_parties ?? $parties as $party)
                        <option value="{{ $party->id }}" 
                            data-chart-of-account-id="{{ $party->chart_of_account_id ?? '' }}"
                            data-sub-chart-of-account-id="{{ $party->sub_chart_of_account_id ?? '' }}"
                            {{ isset($selected_franchiser_id) && $party->id == $selected_franchiser_id ? 'selected' : '' }}>
                            {{ $party->name }}
                        </option>
                    @endforeach
                </select>
            </div>

            <div class="col-md" id="category_div" style="display: none;">
                <label class="form-label" for="fl_category_id">Category</label>
                <select name="category_id" id="fl_category_id" class="form-select js-example-basic-single select2">
                    <option value="">Select Category</option>
                    @foreach ($categories as $category)
                        <option value="{{ $category->id }}" @selected(isset($selectedCategoryId) && $selectedCategoryId == $category->id)>
                            {{ $category->name }}
                            {{ isset($category->prefix) ? '(' . $category->prefix . ')' : '' }}
                        </option>
                    @endforeach
                </select>
            </div>

            <div class="col-md" id="drop_product_div" style="display: none;">
                <label class="form-label" for="drop_product_id">Product</label>
                <select name="product_id" id="drop_product_id" class="form-select js-example-basic-single select2">
                    <option value="">Select Product...</option>
                </select>
            </div>

            <div class="col-1">
                <button type="submit" class="btn btn-primary">Filter</button>
            </div>
        </form>
    </div>

    <div class="card">
        <div class="card-body px-0 pb-0">
            <h5 class="text-center card-title mb-0">Financial Ledger Report</h5>
            <p class="text-center text-muted">From {{ \Carbon\Carbon::create($from_date)->format('d M, Y') }} to
                {{ \Carbon\Carbon::create($to_date)->format('d M, Y') }}</p>
            <div class="border-top border-bottom p-2">
                @if(isset($report_type) && $report_type === 'product')
                    <p class="text-muted">Product Financial Ledger @if($selected_product) - Specific Selection @endif</p>
                @else
                    @if($franchiser)
                        <p class="text-muted">{{ $franchiser->code . ' ' . $franchiser->name }}</p>
                    @else
                        <p class="text-muted">All Franchisers</p>
                    @endif
                @endif
            </div>
            <div class="table-responsive">
                <table class="table table-striped">
                    <thead class="table-primary">
                        <tr>
                            <th>Date</th>
                            <th>VR</th>
                            @if(!isset($report_type) || $report_type !== 'product')
                                <th>Payment <br> Method</th>
                            @endif
                            <th>Particular</th>
                            <th>Debit</th>
                            <th>Credit</th>
                            <th>Balance</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach ($financial_ledger as $report)
                            <tr>
                                <td>{{ $report['created_at'] }}</td>
                                <td>{{ $report['vr'] }}</td>
                                @if(!isset($report_type) || $report_type !== 'product')
                                    <td>{{ $report['payment_method'] ?? '-' }}</td>
                                @endif
                                <td>{{ $report['particular'] }}</td>
                                <td>{{ $report['type'] == 'debit' ? number_format($report['amount'], 2) : '' }}</td>
                                <td>{{ $report['type'] == 'credit' ? number_format($report['amount'], 2) : '' }}</td>
                                <td>{{ number_format($report['balance'], 2) }}</td>
                            </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    <!-- Print timestamp will be added here -->
    <div id="printTimestampContainer"></div>

    <script>
        const sub_coas = @json($sub_coas ?? []);
        const selected_coa_id = @json($coa_id ?? null);
        const selected_sub_coa_id = @json($sub_coa_id ?? null);
        const allParties = @json($parties ?? []);

        function filterCustomers() {
            const coaId = $('#coa_id').val();
            const subCoaId = $('#sub_coa_id').val();
            const selectedFranchiserId = $('#franchiser').val();
            
            let html = `<option value="">All Customers</option>`;
            
            allParties.forEach(party => {
                let showParty = true;
                
                // Filter by Chart of Account (convert to string for comparison, handle null)
                if (coaId) {
                    const partyCoaId = party.chart_of_account_id ? String(party.chart_of_account_id) : '';
                    if (partyCoaId !== String(coaId)) {
                        showParty = false;
                    }
                }
                
                // Filter by Sub Chart of Account (convert to string for comparison, handle null)
                if (subCoaId) {
                    const partySubCoaId = party.sub_chart_of_account_id ? String(party.sub_chart_of_account_id) : '';
                    if (partySubCoaId !== String(subCoaId)) {
                        showParty = false;
                    }
                }
                
                if (showParty) {
                    let selectedAttr = (selectedFranchiserId && party.id == selectedFranchiserId) ? 'selected' : '';
                    html += `<option value="${party.id}" 
                        data-chart-of-account-id="${party.chart_of_account_id || ''}"
                        data-sub-chart-of-account-id="${party.sub_chart_of_account_id || ''}"
                        ${selectedAttr}>${party.name}</option>`;
                }
            });
            
            $('#franchiser').html(html);
            
            // Reinitialize select2 if it's being used
            if ($('#franchiser').hasClass('select2-hidden-accessible')) {
                $('#franchiser').select2('destroy');
                $('#franchiser').select2();
            }
        }

        $(document).ready(function () {
            toggleReportType();

            if(selected_coa_id) {
                $('#coa_id').trigger('change');
                setTimeout(() => {
                    if(selected_sub_coa_id) {
                        $('#sub_coa_id').val(selected_sub_coa_id).trigger('change');
                    }
                    filterCustomers();
                }, 200);
            } else {
                filterCustomers();
            }
        });

        $('#report_type').on('change', function() {
            toggleReportType();
        });

        function toggleReportType() {
            var type = $('#report_type').val();
            if (type === 'product') {
                $('#coa_div, #sub_coa_div, #customer_div').hide();
                $('#product_type_div, #category_div, #drop_product_div, #fallback_product_div').show();
            } else {
                $('#coa_div, #sub_coa_div, #customer_div').show();
                $('#product_type_div, #category_div, #drop_product_div, #fallback_product_div').hide();
            }
        }

        // Category / Product Fetching Logic
        function fetchProducts() {
            var categoryId = $('#fl_category_id').val();
            var materialType = 'raw_items';
            
            if (categoryId && materialType) {
                $('#fallback_product_div').hide(); // Hide the fallback list if we are using categories
                $('#drop_product_div').show();
                
                $.ajax({
                    url: '{{ route('reports.category-product', ':id') }}'.replace(':id', categoryId),
                    type: 'GET',
                    data: {
                        category_id: categoryId,
                        type: materialType
                    },
                    success: function(response) {
                        var productDropdown = $('#drop_product_id');
                        productDropdown.empty();
                        productDropdown.append('<option value="">Select Product</option>');
                        var selectedProduct = '{{ isset($selected_product) ? $selected_product : '' }}';
                        
                        let basePrefix = materialType === 'raw_items' ? 'raw_' : 'product_';
                        
                        response.forEach(function(product) {
                            var isSelected = (selectedProduct == product.id || selectedProduct == (basePrefix + product.id)) ? 'selected' : '';
                            productDropdown.append('<option value="'+ basePrefix + product.id + '" ' + isSelected + '>' + product.name + '</option>');
                        });
                        
                        if (productDropdown.hasClass('select2-hidden-accessible')) {
                            productDropdown.select2('destroy').select2();
                        }
                    },
                    error: function() {
                        console.error('Failed to fetch products');
                    }
                });
            } else if (materialType || categoryId) {
                // Keep fallback hidden if partial category interaction
                $('#fallback_product_div').hide();
                $('#drop_product_id').empty().append('<option value="">Select Product...</option>');
            } else {
                // If both are empty, show fallback
                $('#fallback_product_div').show();
                $('#drop_product_div').hide();
            }
        }

        $('#fl_category_id').on('change', function() {
            fetchProducts();
        });

        // Initial load for products
        $(document).ready(function() {
            if ($('#report_type').val() === 'product' && ($('#fl_category_id').val() || $('#type').val())) {
                fetchProducts();
            }
        });

        $('#coa_id').on('change', function() {
            $('#sub_coa_id').html(`<option value="">Select Sub Chart of Account</option>`);
            if (this.value > 0) {
                let selected = sub_coas[this.value] || [];

                if (selected.length > 0) {
                    let html = `<option value="">Select Sub Chart of Account</option>`;
                    selected.forEach(sub => {
                        let selectedAttr = (selected_sub_coa_id && sub.id == selected_sub_coa_id) ? 'selected' : '';
                        html += `<option value="${sub.id}" ${selectedAttr}>${sub.name}</option>`;
                    });
                    $('#sub_coa_id').html(html);
                }
            } else {
                $('#sub_coa_id').val('').trigger('change');
            }
            
            // Filter customers when COA changes
            filterCustomers();
        });

        $('#sub_coa_id').on('change', function() {
            // Filter customers when Sub-COA changes
            filterCustomers();
        });


    </script>
@endsection

<style>
    @media print {
        @page {
            margin: 3% !important;
        }

        html,
        body {
            height: 100%;
            margin: 0;
            padding: 0;
            overflow: hidden;
        }

        body * {
            visibility: hidden;
        }

        .card-body,
        .card-body * {
            visibility: visible;
        }

        .card-body {
            position: fixed;
            left: 0;
            top: 0;
            width: 100%;
        }

        .table-primary th {
            background-color: transparent !important;
            -webkit-print-color-adjust: exact;
            color-adjust: exact;
        }

        /* Ensure timestamp container is visible in print */
        #printTimestampContainer {
            visibility: visible !important;
            display: block !important;
            page-break-inside: avoid !important;
        }

        #printTimestamp {
            visibility: visible !important;
            display: block !important;
            text-align: center !important;
            margin-top: 20px !important;
            font-size: 14px !important;
            color: #666 !important;
            page-break-inside: avoid !important;
        }
    }
</style>
