@extends('admin.layouts.app')

@section('content')
    <div class="page-header">
        <div class="page-title">
            <h4>Production Report</h4>
            <ul class="breadcrumb">
                <li class="breadcrumb-item active">Production 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.production-report') }}" class="row gy-2 gx-3 align-items-end" method="get">
            <div class="col-sm-4 col-md-3">
                <label class="form-label" for="year">Select Year</label>
                <select class="form-select" id="year" name="year">
                    @php
                        $currentYear = date('Y');
                        $startYear = $currentYear - 25;
                        for ($yearOption = $currentYear; $yearOption >= $startYear; $yearOption--) {
                            $selected = isset($year) && $year == $yearOption ? 'selected' : '';
                            echo "<option value=\"$yearOption\" $selected>$yearOption</option>";
                        }
                    @endphp
                </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-0">Production Report</h5>
            <p class="text-center text-muted">From {{ \Carbon\Carbon::create($year)->startOfYear()->format('d M, Y') }} to
                {{ \Carbon\Carbon::create($year)->endOfYear()->format('d M, Y') }}</p>
            <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-striped" id="productionTable">
                    <thead class="table-primary">
                        <tr>
                            <th>Item</th>
                            <th>Jan</th>
                            <th>Feb</th>
                            <th>Mar</th>
                            <th>Apr</th>
                            <th>May</th>
                            <th>June</th>
                            <th>July</th>
                            <th>Aug</th>
                            <th>Sept</th>
                            <th>Oct</th>
                            <th>Nov</th>
                            <th>Dec</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach ($productionReport as $production)
                            <tr>
                                <td>{{ $production->product->name . ' | ' . $production->packingType->name . ' | ' . $production->packSize->name }}
                                </td>
                                @foreach ($production->monthly_totals as $month => $total)
                                    <td>{{ $total }}</td>
                                @endforeach
                            </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    <!-- Print timestamp will be added here -->
    <div id="printTimestampContainer"></div>
    </div>
    </div>
@endsection

<style>
    @media print {
        @page {
            margin: 3% !important;
            size: landscape;
        }

        body {
            font-size: 12px;
            line-height: 1.2;
            margin: 0;
            padding: 0;
        }

        .card {
            border: none;
            margin: 0;
        }

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

        }

        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;
            font-size: 11px;
        }

        .table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }

        .table th,
        .table td {
            padding: 4px 8px;
            font-size: 10px;
        }
    }
</style>
<script>
function exportPDF() {
    const table = document.getElementById("productionTable");
    if (!table) {
        alert("Table not found!");
        return;
    }

    const title = "Production Report";
    const dateRange = document.querySelector('.text-muted')?.innerText || '';
    
    const now = new Date();
    const dd = String(now.getDate()).padStart(2, '0');
    const mm = String(now.getMonth() + 1).padStart(2, '0');
    const yy = String(now.getFullYear()).slice(-2);
    const formattedDate = dd + '/' + mm + '/' + yy;
    
    const printedOn = "Printed on: " + formattedDate;

    const headers = [];
    const tableHeaderCells = table.querySelectorAll("thead tr th");
    tableHeaderCells.forEach(cell => {
        headers.push({ text: cell.innerText.trim(), 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: 'landscape',
        content: [
            { text: title, style: 'header' },
            { text: dateRange, style: 'subheader' },
            { text: printedOn, style: 'timestamp' },
            { text: '\n' },
            {
                table: {
                    headerRows: 1,
                    widths: ['*', 'auto', 'auto', '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 4; },
                    paddingRight: function(i, node) { return 4; },
                    paddingTop: function(i, node) { return 4; },
                    paddingBottom: function(i, node) { return 4; }
                }
            }
        ],
        styles: {
            header: { fontSize: 16, bold: true, alignment: 'center', margin: [0, 0, 0, 5] },
            subheader: { fontSize: 11, alignment: 'center', margin: [0, 0, 0, 5] },
            timestamp: { fontSize: 9, alignment: 'center', margin: [0, 0, 0, 10], color: '#666' },
            tableHeader: { fontSize: 9, bold: true, fillColor: '#f2f2f2', alignment: 'center' },
            tableCell: { fontSize: 8, alignment: 'center' }
        },
        defaultStyle: { fontSize: 8 }
    };

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

function exportCSV() {
    let csv = [];

    csv.push("Production Report");

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

    const now = new Date();
    const dd = String(now.getDate()).padStart(2, '0');
    const mm = String(now.getMonth() + 1).padStart(2, '0');
    const yy = String(now.getFullYear()).slice(-2);
    const formattedDate = dd + '/' + mm + '/' + yy;

    csv.push("Printed on: " + formattedDate);
    csv.push("");
    csv.push("");

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

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