@extends('admin.layouts.app')

@section('content')
    <div class="page-header">
        <div class="page-title">
            <h4>Batch Cost Summary</h4>
            <ul class="breadcrumb">
                <li class="breadcrumb-item active">Batch Cost Summary</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.batch-report') }}" class="row gy-2 gx-3 align-items-end" method="get">
            <div class="col-md-8 col-md-3">
                <label class="form-label" for="product">Products</label>
                <select name="product" id="product" class="js-example-basic-single select2">
                    <option value="">Select Product</option>
                    @foreach ($products as $product)
                        <option value="{{ $product->id }}" {{ $product->id == $finalProduct->id ? 'selected' : '' }}>
                            {{ $product->product->brand_name }}
                            @if ($product->product->generic_name)
                                | {{ $product->product->generic_name }}
                            @endif
                            @if ($product->strength)
                                | {{ $product->strength }}
                            @endif
                            @if ($product->packingType->name)
                                | {{ $product->packingType->name }}
                            @endif
                            @if ($product->packSize->name)
                                | {{ $product->packSize->name }}
                            @endif
                        </option>
                    @endforeach
                </select>
            </div>
            <div class="col-auto">
                <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-2">Batch Cost Summary
                @if ($finalProduct->id)
                    of
                    {{ $product->product->brand_name }}
                            @if ($product->product->generic_name)
                                | {{ $product->product->generic_name }}
                            @endif
                            @if ($product->strength)
                                | {{ $product->strength }}
                            @endif
                            @if ($product->packingType->name)
                                | {{ $product->packingType->name }}
                            @endif
                            @if ($product->packSize->name)
                                | {{ $product->packSize->name }}
                            @endif
                @endif
            </h5>
            <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="table-responsive">
                <table class="table table-hover" id="batchCostTable">
                    <thead class="table-primary">
                        <tr>
                            <th>Batch #</th>
                            <th>Packs</th>
                            <th>Avg.Cost</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach ($items as $item)
                            @php
                                $matchingItem = collect($array)->firstWhere('batch_id', $item['id']);
                            @endphp
                            <tr>
                                <td>{{ $item['batch_no'] }}</td>
                                <td>{{ $item['batch_size'] }}</td>
                                <td>{{ number_format($matchingItem['avgCost'], 6) }}</td>
                            </tr>
                        @endforeach

                    </tbody>
                </table>
            </div>
        </div>
    </div>
    <!-- Print timestamp will be added here -->
    <div id="printTimestampContainer"></div>
    </div>
@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;
        }
    }
</style>
<script>
    
function exportPDF() {
    const table = document.getElementById("batchCostTable");
    if (!table) {
        alert("Table not found!");
        return;
    }

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

    // Create header row with exactly 6 columns
    const headers = [
        { text: 'Batch #', style: 'tableHeader' },
        { text: 'Packs', style: 'tableHeader' },
        { text: 'Avg.Cost', 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 === 3) {
            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: ['33%', '33%', '34%'],
                    body: [headers, ...body]
                },
                alignment:'center',
                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_cost_report.pdf");
}
function exportCSV() {
    let csv = [];

    csv.push("Batch Cost 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("batchCostTable");

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


</script>