@extends('admin.layouts.app')

@section('content')
    <div class="page-header">
        <div class="page-title">
            <h4>Requirement Report</h4>
            <ul class="breadcrumb">
                <li class="breadcrumb-item active">Requirement 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.requirement-report') }}" class="row gy-2 gx-3 align-items-end" method="get">
            <div class="col-md">
                <label class="form-label" for="min_level">Min Level</label>
                <input type="checkbox" class="form-check-input" name="min_level" id="min_level"
                    @checked(isset($min_level) && $min_level)>
            </div>
            <!-- <div class="col-md">
                <label class="form-label" for="max_level">Max Level</label>
                <input type="checkbox" class="form-check-input" name="max_level" id="max_level"
                    @checked(isset($max_level) && $max_level)>
            </div> -->
            <div class="col-md">
                <label class="form-label" for="category_id">Category</label>
                <select name="category_id" id="category_id" class="js-example-basic-single select2">
                    <option value="">Select Category</option>
                    @foreach ($categories as $category)
                        <option value="{{ $category->id }}" @selected(isset($category_id) && $category_id == $category->id)>
                            {{ $category->name }}
                            {{ isset($category->prefix) ? '(' . $category->prefix . ')' : '' }}
                        </option>
                    @endforeach
                </select>
            </div>
            <div class="col-2">
                <button type="submit" class="btn btn-primary">Filter</button>
            </div>
        </form>
    </div>

    <div class="card">
        <div class="card-body p-0">
            <h4 class="card-header text-center">Requirement Report</h4>
            <div class="d-flex gap-2 mb-3 ms-3 mt-3">
                <button class="btn btn-danger btn-sm" onclick="exportPDF()">
                    <i class="fas fa-file-pdf"></i> Export PDF
                </button>
                <button class="btn btn-success btn-sm" onclick="exportCSV()">
                    <i class="fas fa-file-csv"></i> Export CSV
                </button>
            </div>
            <div class="table-responsive" style="max-height: 400px; overflow-y: auto;">
                <table class="table table-hover" id="requirementReportTable">
                    <thead class="table-primary sticky-top">
                        <tr class="">
                            <th colspan="2" class=""></th>
                            <th class="text-center" colspan="3">Level</th>
                            {{-- <th rowspan="2">Max.<br>Level</th>
                            <th rowspan="2">Min.<br>Level</th>
                            <th rowspan="2">Current<br>Level</th> --}}
                            <th></th>
                            <th colspan="4" class="text-center">In Process PR's</th>
                        </tr>
                        <tr class="">
                            <th class="">Code</th>
                            <th class="">Item</th>
                            <th class="">Category</th>
                            <th>Max</th>
                            <th>Min</th>
                            <th>Current</th>
                            <th>Reorder<br>Qty</th>
                            <th>PR#</th>
                            <th>PR Qty</th>
                            <th>Qty Recv</th>
                            <th>Qty Bal</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach ($requirementReport as $requirement)
                            <tr>
                                <td>{{ $requirement->code }}</td>
                                <td>{{ $requirement->name }}</td>
                                <td>{{ $requirement->category->name ?? '-' }}

                                </td>
                                <td>{{ $requirement->max_level ?? 0 }}</td>
                                <td>{{ $requirement->min_level ?? 0 }}</td>
                                <td>{{ $requirement->balance() ?? 0 }}</td>
                                <td>{{ $requirement->ordered_quantity ?? 0 }}</td>
                                <td>
                                    @if (isset($requirement->invoice_codes) && is_array($requirement->invoice_codes))
                                        @foreach ($requirement->invoice_codes as $invoice_code)
                                            {{ $invoice_code }}@if (!$loop->last)
                                                ,
                                            @endif
                                        @endforeach
                                    @else
                                        No invoices
                                    @endif
                                </td>
                                <td>{{ $requirement->ordered_quantity ?? 0 }}</td>
                                <td>{{ $requirement->received_quantity ?? 0 }}</td>
                                <td>{{ $requirement->ordered_quantity - $requirement->received_quantity ?? 0 }}</td>
                            </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    <!-- Print timestamp will be added here -->
    <div id="printTimestampContainer"></div>
    </div>
@endsection

<style>
    .card-header {
        display: none !important;
    }

    /* Print layout — targeted and predictable */
    @media print {
        .card-header {
            display: block !important;
        }

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

        .non-pdf-content {
            display: none !important;
            visibility: hidden !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;
        }

        .card {
            margin-top: -2.5rem !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;
        }

        #printTimestampContainer {
            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 {
            border: 1px solid #000 !important;
            page-break-inside: auto !important;
        }

        th,
        td {
            border: 1px solid #000 !important;
        }

        tr {
            border: 1px solid #000 !important;
            page-break-inside: avoid !important;
            page-break-after: auto !important;
        }
    }
</style>
{{-- <style>
    @media print {
        @page {
            margin: 0;
        }

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

        body * {
            visibility: hidden;
        }

        table,
        table * {
            visibility: visible;
        }

        table {
            position: fixed;
            left: 0;
            top: 0;
            width: 100%;
        }

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

<script>
function exportPDF() {
    const table = document.getElementById("requirementReportTable");
    if (!table) {
        alert("Table not found!");
        return;
    }

    const title = "Requirement Report";
    const printedOn = "Printed on: " + new Date().toLocaleString('en-GB');

    const headers = [
        { text: 'Code', style: 'tableHeader' },
        { text: 'Item', style: 'tableHeader' },
        { text: 'Category', style: 'tableHeader' },
        { text: 'Max', style: 'tableHeader' },
        { text: 'Min', style: 'tableHeader' },
        { text: 'Current', style: 'tableHeader' },
        { text: 'Reorder Qty', style: 'tableHeader' },
        { text: 'PR#', style: 'tableHeader' },
        { text: 'PR Qty', style: 'tableHeader' },
        { text: 'Qty Recv', style: 'tableHeader' },
        { text: 'Qty Bal', style: 'tableHeader' }
    ];

    const body = [];
    const tableRows = table.querySelectorAll("tbody tr");
    tableRows.forEach(row => {
        const rowData = [];
        const cells = row.querySelectorAll("td");
        cells.forEach(cell => {
            rowData.push({ text: cell.innerText.trim(), style: 'tableCell' });
        });
        body.push(rowData);
    });

    const docDefinition = {
        pageOrientation: 'portrait',
        content: [
            { text: title, style: 'header' },
            { text: printedOn, style: 'timestamp' },
            { text: '\n' },
            {
                table: {
                    headerRows: 1,
                    widths: ['auto', '*', 'auto', 'auto', 'auto', 'auto', 'auto', 'auto', 'auto', 'auto', 'auto'],
                    body: [headers, ...body]
                },
                layout: {
                    hLineWidth: function(i, node) { return 0.5; },
                    vLineWidth: function(i, node) { return 0.5; },
                    hLineColor: function(i, node) { return '#aaa'; },
                    vLineColor: function(i, node) { return '#aaa'; },
                    paddingLeft: function(i, node) { return 3; },
                    paddingRight: function(i, node) { return 3; },
                    paddingTop: function(i, node) { return 3; },
                    paddingBottom: function(i, node) { return 3; }
                }
            }
        ],
        styles: {
            header: { fontSize: 16, bold: true, alignment: 'center', margin: [0, 0, 0, 5] },
            timestamp: { fontSize: 9, alignment: 'center', margin: [0, 0, 0, 10], color: '#666' },
            tableHeader: { fontSize: 7, bold: true, fillColor: '#f2f2f2', alignment: 'center' },
            tableCell: { fontSize: 6, alignment: 'center' }
        },
        defaultStyle: { fontSize: 6 }
    };

    pdfMake.createPdf(docDefinition).download("requirement_report.pdf");
}

function exportCSV() {
    let csv = [];
    csv.push("Requirement Report");
    csv.push("Printed on: " + new Date().toLocaleString('en-GB'));
    csv.push("");

    const table = document.getElementById("requirementReportTable");
    if (!table) {
        alert("Table not found!");
        return;
    }

    const headerRow = [
        '"Code"', '"Item"', '"Category"', '"Max"', '"Min"', 
        '"Current"', '"Reorder Qty"', '"PR#"', '"PR Qty"', 
        '"Qty Recv"', '"Qty Bal"'
    ];
    csv.push(headerRow.join(","));

    const bodyRows = table.querySelectorAll("tbody tr");
    bodyRows.forEach(row => {
        let rowData = [];
        const cells = row.querySelectorAll("td");
        cells.forEach(cell => {
            let text = cell.innerText.trim();
            // Replace newlines and quotes to ensure valid CSV
            text = text.replace(/"/g, '""').replace(/\\n/g, ' ');
            rowData.push('"' + text + '"');
        });
        csv.push(rowData.join(","));
    });

    const blob = new Blob([csv.join("\\n")], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = "requirement_report.csv";
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
}
</script>
