@extends('admin.layouts.app')
@section('title', 'Trial Balance')

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

    <div class="mb-3" id="filter_row">
        <div class="row">
            <div class="col-md mb-3">
                <label for="start_date">Start Date <span class="text-danger">*</span></label>
                <input type="date" class="form-control" id="start_date">
            </div>

            <div class="col-md mb-3">
                <label for="end_date">End Date <span class="text-danger">*</span></label>
                <input type="date" class="form-control" id="end_date">
            </div>

            <div class="col-md mb-3">
                <label for="level">Level <span class="text-danger">*</span></label>
                <select id="level" class="form-control js-example-basic-single select2">
                    <option value="1">1</option>
                    <option value="3">3</option>
                </select>
            </div>

            <div class="col-md-2 gap-2 d-flex justify-content-center align-items-center">
                <button type="button" class="btn btn-outline-success px-3" id="generate_btn">Generate</button>
                <button type="button" class="btn btn-outline-danger px-3" id="reset_btn">Reset</button>
                <button type="button" class="btn btn-outline-primary px-3" onclick="aaprintWithTimestamp()"
                    id="print_btn">Print</button>
            </div>
        </div>
    </div>

    <div class="card">
        <div class="card-body" id="report_data">

        </div>
    </div>
    <!-- Print timestamp will be added here -->
    <div id="printTimestampContainer"></div>
    </div>

    <div class="print-only-signature card" id="printSignatureCopy" aria-hidden="true">
        <div class="card-body">
            <div class="text-end" id="printTimestampContainerPrintOnly"></div>
        </div>
    </div>


    <script>
        $('#generate_btn').click(function() {
            $('#report_data').empty();

            let start_date = $('#start_date').val(),
                end_date = $('#end_date').val();

            console.log(start_date, end_date);

            // $('#tfoot_data').empty()
            if (start_date && end_date) {
                $("#global-loader").show();
                $.ajax({
                    type: "post",
                    url: '{{ route('report.ajax-generate-trial-balance') }}',
                    data: {
                        _token: "{{ csrf_token() }}",
                        start_date: start_date,
                        end_date: end_date,
                        level: $('#level').val(),
                    },
                    dataType: "json",
                    success: function(response) {
                        if (response.success) {
                            $('#report_data').html(response.view);
                        }
                        $("#global-loader").fadeOut("slow");

                    },
                    error: function(error) {
                        console.error(error);
                        $("#global-loader").fadeOut("slow");

                    }
                });
            } else {
                toastr.error('Select Date(s) to continue !')
            }
        });

        $('#reset_btn').click(function() {
            $('#start_date').val('');
            $('#end_date').val('');
        });
    </script>

    <script>
        function aaprintWithTimestamp(containerId = 'printTimestampContainer') {
            const targets = [containerId, 'printTimestampContainerPrintOnly'];

            // --- inject timestamp
            targets.forEach(id => {
                let container = document.getElementById(id);
                if (!container) {
                    container = document.createElement('div');
                    container.id = id;
                    const fallback = document.querySelector('.footer') || document.body;
                    fallback.appendChild(container);
                }

                container.innerHTML = '';
                const timestampDiv = document.createElement('div');
                timestampDiv.className = 'generated-print-timestamp';
                timestampDiv.style.cssText =
                    'text-align: right; margin-top: 6px; font-size: 12px; color: #666;';
                const now = new Date();
                const formatted = now.toLocaleString('en-GB', {
                    hour12: false
                });
                timestampDiv.innerHTML = '<strong>Printed on:</strong> ' + formatted;
                container.appendChild(timestampDiv);
            });

            // --- Create style for timestamp only (no page rules)
            if (!document.getElementById('printSignatureCopy')) {
                const printStyle = document.createElement('style');
                printStyle.id = 'printSignatureCopy';
                printStyle.textContent = `
            @media print {
                .generated-print-timestamp {
                    visibility: visible !important;
                    color: #666 !important;
                    font-size: 12px !important;
                }
                #printSignatureCopy {
                    visibility: visible !important;
                }
            }
        `;
                document.head.appendChild(printStyle);
            }

            // --- Handle signature placement: only on last page
            const sig = document.getElementById('printSignatureCopy');
            let sigClone = null;
            if (sig) {
                // Hide all existing ones
                sig.style.display = 'none';

                // Clone and append to body (prints last)
                sigClone = sig.cloneNode(true);
                sigClone.style.display = 'block';
                sigClone.style.position = 'relative';
                sigClone.style.pageBreakBefore = 'always';
                document.body.appendChild(sigClone);
            }

            // --- Print
            setTimeout(() => {
                window.print();

                // Cleanup
                setTimeout(() => {
                    document.querySelectorAll('.generated-print-timestamp').forEach(n => n.remove());
                    const styleElement = document.getElementById('printTimestampStyle');
                    if (styleElement) styleElement.remove();

                    // remove clone and restore original signature
                    if (sigClone) sigClone.remove();
                    if (sig) sig.style.display = 'block';
                }, 500);
            }, 150);
        }
    </script>
@endsection

<style>
    /* keep existing non-print styles (no change) */
    .print-header {
        margin-top: 5px !important;
    }

    .footer-row {
        padding-bottom: 0 !important;
    }

    #notes_div {
        margin-top: 10px;
        font-size: 14px;
    }

    #printSignatureCopy {
        display: none !important;
    }

    /* Print layout — targeted and predictable */
    @media print {
        .footer-row {
            padding-bottom: 4rem !important;
        }

        #notes_div {
            padding-bottom: 4.5rem !important;
        }

        #printSignatureCopy {
            display: block !important;
            position: fixed !important;
            bottom: 0 !important;
            left: 0;
            width: 100%;
            margin-top: 20px !important;
        }

        .page-header,
        .no-print,
        #filter_row,
        button,
        .btn {
            display: none !important;
        }

        /* page settings */
        @page {
            size: auto;
            margin: 3% !important;
        }

        html,
        body {
            background: none !important;
            height: auto !important;
            margin: 0;
            padding: 0;
            /* margin-bottom: 5rem !important;
            padding-bottom: 5rem !important; */
        }

        .card,
        .card-body {
            position: static !important;
            width: 100% !important;
            margin: 0 !important;
            padding: 0 !important;
            box-shadow: none !important;
            border: none !important;
        }

        #report_data {
            margin-top: -2.5rem !important;
            margin-bottom: 2.5rem !important;
        }

        .card-header {
            display: none !important;
            visibility: hidden !important;
        }

        #main_card {
            margin-top: -3rem !important;
            margin-bottom: 4rem !important;
            /* padding-bottom: 3rem !important; */
        }

        /* Keep table colors */
        .table-primary th {
            background-color: #cfe2ff !important;
            -webkit-print-color-adjust: exact !important;
            print-color-adjust: exact !important;
            color: #000 !important;
        }

        .approved-target {
            background-color: #198754 !important;
            color: white !important;
            -webkit-print-color-adjust: exact !important;
            print-color-adjust: exact !important;
        }

        .footer {
            display: none !important;
        }

        #printTimestampContainerPrintOnly {
            display: block !important;
            text-align: right !important;
            margin-top: 10px !important;
            font-size: 12px !important;
            color: #666 !important;
        }

        table {
            page-break-inside: auto !important;
        }

        tr {
            page-break-inside: avoid !important;
            page-break-after: auto !important;
        }
    }
</style>

<script>
    function printWithTimestamp() {
        const now = new Date();
        const formatted = now.toLocaleString('en-GB', {
            day: '2-digit',
            month: 'short',
            year: 'numeric',
            hour: '2-digit',
            minute: '2-digit'
        });

        const timestampDiv = document.getElementById('printTimestampContainer');
        timestampDiv.innerHTML = `Printed on: ${formatted}`;

        window.print();
    }
</script>
