@extends('admin.layouts.app')

@section('content')
    <div class="page-header">
        <div class="page-title">
            <h4>Batch Wise Current Balance Report</h4>
            <ul class="breadcrumb">
                <li class="breadcrumb-item active">Batch Wise 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" id="main_card">
        <h4 class="card-header text-center">
            Batch Balance Report
        </h4>
         <div class="d-flex gap-2 mb-3 ms-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="card-body p-0">
            <div class="table-responsive">
                <table class="table table-striped" id="batchReportTable">
                    <thead class="table-primary">
                        <tr>
                            <th rowspan="2">Code</th>
                            <th rowspan="2">Description</th>
                            <th colspan="4" class="text-center">Balance</th>
                        </tr>
                        <tr>
                            <th>Quantity</th>
                            <th>Unit</th>
                            <th>Rate</th>
                            <th>Value</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach ($batchBalanceReport as $balanceReport)
                            <tr>
                                <td>{{ $balanceReport['code'] }}</td>
                                <td>{{ $balanceReport['name'] }}</td>
                                <td>{{ number_format($balanceReport['quantity'], 2) }}</td>
                                <td>{{ $balanceReport['unit'] }}</td>
                                <td>{{ number_format($balanceReport['unit_price'], 2) }}</td>
                                <td>{{ number_format($balanceReport['unit_price'] * $balanceReport['quantity'], 2) }}</td>
                            </tr>
                            <tr>
                                <td colspan="6">
                                    @foreach ($balanceReport['batches'] as $batch)
                                        <div class="d-flex mb-2">
                                            <div class="col">
                                                <a href="{{ route('reports.costing-voucher', $batch['batch_id']) }}">Batch #
                                                    {{ $batch['batch_code'] }}</a>
                                            </div>
                                            <div class="col">
                                                Bal QTY # {{ $batch['batch_balance'] }}
                                            </div>
                                            <div class="col">
                                                Mfg
                                                @if (array_key_exists('mfg', $batch) && !empty($batch['mfg']))
                                                    {{ \Carbon\Carbon::parse($batch['mfg'])->toDateString() }}
                                                @endif
                                            </div>
                                            <div class="col">
                                                Exp
                                                @if (array_key_exists('exp', $batch) && !empty($batch['exp']))
                                                    {{ \Carbon\Carbon::parse($batch['exp'])->toDateString() }}
                                                @endif
                                            </div>
                                        </div>
                                    @endforeach
                                </td>
                            </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    <!-- Print timestamp will be added here -->
    <div id="printTimestampContainer"></div>
    </div>
@endsection

<style>
    @media print {

        .page-header,
        .page-header * {
            visibility: visible !important;
        }

        .card-header,
        .card-header * {
            visibility: visible !important;
        }

        .card-header {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            text-align: center;
            font-size: 20px;
            margin-bottom: 20px;
        }

        table {
            margin-top: 60px !important;
            /* Push table down to avoid overlapping with title */
        }

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

        @page {
            margin: 4% !important;
        }
    }

    /* @media print {

        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("batchReportTable");
    if (!table) {
        alert("Table not found!");
        return;
    }

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

    // Create header row with exactly 6 columns
    const headers = [
        { text: 'Code', style: 'tableHeader' },
        { text: 'Description', style: 'tableHeader' },
        { text: 'Quantity', style: 'tableHeader' },
        { text: 'Unit', style: 'tableHeader' },
        { text: 'Rate', style: 'tableHeader' },
        { text: 'Value', style: 'tableHeader' }
    ];

    // Extract only the main data rows (skip batch detail rows)
    const body = [];
    const tableRows = table.querySelectorAll("tbody > tr");
    
    tableRows.forEach((row, index) => {
        const cells = row.querySelectorAll("td");
        
        // Check if this is a data row (has 6 cells) vs batch detail row (has 1 cell with colspan)
        if (cells.length === 6) {
            const rowData = [];
            cells.forEach(cell => {
                rowData.push({ text: cell.innerText.trim(), style: 'tableCell' });
            });
            body.push(rowData);
        }
    });

    // Validate we have data
    if (body.length === 0) {
        alert("No data found in table!");
        return;
    }

    const docDefinition = {
        content: [
            { text: title, style: 'header' },
            { text: printedOn, style: 'timestamp' },
            { text: '\n' },
            {
                table: {
                    headerRows: 1,
                    widths: ['10%', '25%', '15%', '15%', '15%', '20%'],
                    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 4; },
                    paddingRight: function(i, node) { return 4; },
                    paddingTop: function(i, node) { return 3; },
                    paddingBottom: function(i, node) { return 3; }
                }
            }
        ],
        styles: {
            header: { fontSize: 18, bold: true, alignment: 'center', margin: [0, 0, 0, 10] },
            timestamp: { fontSize: 9, alignment: 'center', margin: [0, 0, 0, 10], color: '#666' },
            tableHeader: { fontSize: 10, bold: true, fillColor: '#4472C4', color: 'white', alignment: 'center' },
            tableCell: { fontSize: 9, alignment: 'right' }
        },
        defaultStyle: { fontSize: 9 },
        pageMargins: [40, 40, 40, 40]
    };

    pdfMake.createPdf(docDefinition).download("batch_balance_report.pdf");
}
function exportCSV() {
    let csv = [];

    csv.push("Batch Report");

    const dateText = document.querySelector('.text-muted')?.innerText || '';
    csv.push(dateText);

    csv.push("Printed on: " + new Date().toLocaleString('en-GB'));
    csv.push("");
    csv.push("");

    const table = document.getElementById("batchReportTable");

    if (!table) {
        alert("Table not found!");
        return;
    }

    const headerCells = table.querySelectorAll("thead tr th");
    let headerRow = [];

    headerCells.forEach(cell => {
        headerRow.push('"' + cell.innerText.trim().replace(/"/g, '""') + '"');
    });

    csv.push(headerRow.join(","));

    const bodyRows = table.querySelectorAll("tbody tr");

    bodyRows.forEach(row => {
        let rowData = [];

        const cells = row.querySelectorAll("td");

        cells.forEach(cell => {
            rowData.push('"' + cell.innerText.trim().replace(/"/g, '""') + '"');
        });

        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 = "batch_report.csv";
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
}


</script>