@extends('admin.layouts.app')

@section('content')
    <style>
        .table-custom thead tr:first-child th:first-child,
        .table-custom thead tr:first-child th:nth-child(2) {
            border: none !important;
            background: transparent !important;
        }
    </style>

    <div class="page-header">
        <div class="page-title">
            <h4>Batch Costing Report</h4>
            <ul class="breadcrumb">
                <li class="breadcrumb-item active">Store</li>
                <li class="breadcrumb-item active">Batch Costing Report</li>
            </ul>
        </div>
        <div class="text-right">
            {{-- <button class="btn btn-primary" onclick="aaprintWithTimestamp()"> --}}
            {{-- <button class="btn btn-primary" onclick="printWithTimestamp()"> --}}
            {{-- Print Report
            </button> --}}
        </div>
    </div>

    <div class="card">
        <div class="card-header mb-0 pb-0">
            <div class="row">
                <div class="col-md mb-3">
                    <label for="batch_id">Batch <span class="text-danger">*</span></label>
                    <select id="batch_id" class="form-control js-example-basic-single select2">
                        <option value="">Select Batch</option>
                        @foreach ($batches as $batch)
                            <option value="{{ $batch->id }}">{{ $batch->batch_no ?? '-' }}</option>
                        @endforeach
                    </select>
                </div>

                <div class="col-md d-none mb-3">
                    <label for="type">Type</label>
                    <select id="type" class="form-control js-example-basic-single select2">
                        <option @selected(isset($type) && $type == 'costing_report') value="costing_report">COSTING REPORT</option>
                        <option @selected(isset($type) && $type == 'track') value="track_report">TRACK REPORT</option>
                        <option @selected(isset($type) && $type == 'costing_voucher') value="costing_voucher">COSTING VOUCHER</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-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();
            // $('#tfoot_data').empty()
            if ($('#batch_id').val()) {
                $("#global-loader").show();
                $.ajax({
                    type: "post",
                    url: '{{ route('report.ajax-generate-costing-voucher') }}',
                    data: {
                        _token: "{{ csrf_token() }}",
                        batch_id: $('#batch_id').val(),
                        type: $('#type').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 Batch to continue !')
            }
        });

        $('#reset_btn').click(function() {
            $('#batch_id').val('').trigger('change');
            $('#report_data').empty();
            // $('#tfoot_data').empty()
        });
    </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>
    .table-excel,
    .table-excel th,
    .table-excel td {
        border: 1px solid #000 !important;
        /* solid black border */
        border-collapse: collapse !important;
    }

    .table-excel th {
        /* background-color: #f2f2f2; */
        /* light header shading (optional) */
        /* font-weight: 600; */
    }

    .table-excel td,
    .table-excel th {
        padding: 6px 8px;
        text-align: center;
        vertical-align: middle;
    }

    @media print {
        #printTimestampContainer {
            position: fixed;
            bottom: 10px;
            right: 20px;
            font-size: 12px;
            color: #000;
            visibility: visible !important;
        }

        @page {
            margin: 3% !important;
        }

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

        /* Hide everything except the card body area */
        body * {
            visibility: hidden;
        }

        /* Show only the report content (batch info + table) */
        .card-body,
        .card-body * {
            visibility: visible;
        }

        /* Position the visible area correctly */
        .card-body {
            position: absolute;
            left: 0;
            top: 0;
            width: 100%;
            padding: 20px;
        }

        /* Keep table formatting */
        table {
            width: 100%;
            border-collapse: collapse;
        }

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

        /* Optional: Add spacing between header and table */
        .mb-3 {
            margin-bottom: 1rem !important;
        }

        .table-excel,
        .table-excel th,
        .table-excel td {
            border: 1px solid #000 !important;
            -webkit-print-color-adjust: exact;
            color-adjust: exact;
        }
    }
</style> --}}

<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;
        }

        /* hide UI controls that should not appear on print */
        .page-header,
        .no-print,
        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; */
        }

        /* make the main card take normal flow in print */
        /* #main_card, */
        .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;
        }

        /* -------- SIGNATURE / LAST PAGE HANDLING --------
           Strategy:
           - Hide the on-screen signature section during print (it may appear in middle of content).
           - Show the separate .print-only-signature block only during printing.
           - Force .print-only-signature to start on a new page and use a full-page flex
             container so the signature rows sit at the bottom of that page.
        -------------------------------------------------- */

        /* hide the inline signature in the printed card body */
        .footer {
            display: none !important;
        }

        /* show the print-only signature copy */
        /* .print-only-signature {
            display: block !important;
        } */

        /* force print-only signature to its own page */
        /* .print-only-signature {
            page-break-before: always !important;
            break-before: page !important;
            height: calc(100vh - 2cm);
            display: flex !important;
            flex-direction: column;
            justify-content: flex-end;
            align-items: stretch;
            padding: 0.5cm 1cm;
            box-sizing: border-box;
        }

        .print-only-signature .signature-section {
            display: block !important;
            page-break-inside: avoid !important;
            break-inside: avoid !important;
        } */

        /* timestamp container in print-only copy */
        #printTimestampContainerPrintOnly {
            display: block !important;
            text-align: right !important;
            margin-top: 10px !important;
            font-size: 12px !important;
            color: #666 !important;
        }

        /* small helper: prevent table rows from splitting awkwardly */
        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>
