@extends('admin.layouts.app')

@section('content')
    <div class="page-header">
        <div class="page-title">
            <h4>Consumption Report</h4>
            <ul class="breadcrumb">
                <li class="breadcrumb-item active">Consumption Report</li>
            </ul>
        </div>
    <div class="text-right d-flex gap-2 justify-content-end">
    <button class="btn btn-primary" onclick="printWithTimestamp()">Print Page</button>
</div>
    </div>

    <div class="mb-3">
        <form action="{{ route('reports.consumption-report') }}" class="row gy-2 gx-3 align-items-end" method="get">
            <div class="col-sm-4 col-md-4 d-flex gap-3">
                <div>
                  <label class="form-label" for="from_date">From</label>
                 <input type="date" class="form-control" name="from_date" id="from_date" value="{{ $from_date }}">
                </div>
            
                 <div>
                <label class="form-label" for="to_date">To</label>
                <input type="date" class="form-control" name="to_date" id="to_date" value="{{ $to_date }}">
               </div>

            </div>
               <div class="col-sm-3">
                         <label class="form-label" for="balance_category_id">Categories</label>
                         <select name="balance_category_id" id="balance_category_id" class="form-select js-example-basic-single select2">
                             <option value="" >Select Categories</option>
                             @foreach($categories as $category)
                             <option value="{{$category->id}}" {{ isset($selectedCategoryId) && $selectedCategoryId == $category->id ? 'selected' : '' }}>{{$category->name}}</option>
                             @endforeach
                   
                         </select>
                </div>
            <div class="col-sm-3 col-md-3">
                <label class="form-label" for="raw_material_item_id">Raw Material Item</label>
                <select name="category_item_id[]" id="category_item_id" class="form-select js-example-basic-single select2" multiple>
                <option value="" >Select Product</option>
                </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">Consumption Report</h5>
            <p class="text-center text-muted">From {{ \Carbon\Carbon::create($from_date)->format('d/m/y') }} to
                {{ \Carbon\Carbon::create($to_date)->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="reportTable">
                    <thead class="table-primary">
                        <tr>
                            <th>Code</th>
                            <th>Description</th>
                            <th>Unit</th>
                            <th>Consumption</th>
                            <th>Avg.Price</th>
                            <th>Total</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach ($consumptionReport as $consumption)
                            <tr>
                                <td>{{ $consumption->code }}</td>
                                <td>{{ $consumption->name }}</td>
                                <td>{{ $consumption->unit }}</td>
                                <td>{{ number_format($consumption->total_quantity, 2) }}</td>
                                <td>{{ number_format($consumption->average_unit_price, 2) }}</td>
                                <td>{{ number_format($consumption->average_unit_price * $consumption->total_quantity, 2) }}
                                </td>
                            </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;
        }

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

    const title = "Consumption 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 = {
        content: [
            { text: title, style: 'header' },
            { text: dateRange, style: 'subheader' },
            { text: printedOn, style: 'timestamp' },
            { text: '\n' },
            {
                table: {
                    headerRows: 1,
                    widths: ['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 8; },
                    paddingRight: function(i, node) { return 8; },
                    paddingTop: function(i, node) { return 6; },
                    paddingBottom: function(i, node) { return 6; }
                }
            }
        ],
        styles: {
            header: { fontSize: 18, bold: true, alignment: 'center', margin: [0, 0, 0, 5] },
            subheader: { fontSize: 12, alignment: 'center', margin: [0, 0, 0, 5] },
            timestamp: { fontSize: 10, alignment: 'center', margin: [0, 0, 0, 10], color: '#666' },
            tableHeader: { fontSize: 11, bold: true, fillColor: '#f2f2f2', alignment: 'center' },
            tableCell: { fontSize: 10, alignment: 'center' }
        },
        defaultStyle: { fontSize: 10 }
    };

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

function exportCSV() {
    let csv = [];

    csv.push("Consumption 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("reportTable");

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

$(document).ready(function() {
    @php
        $selectedItemIds = is_array($raw_material_item_id) ? $raw_material_item_id : ($raw_material_item_id ? [$raw_material_item_id] : []);
    @endphp
    var selectedItemIds = @json($selectedItemIds);
    
    if ($('#balance_category_id').val() && selectedItemIds.length > 0) {
        $.get('/report/current-balance/' + $('#balance_category_id').val() + '/item', function (data) {
            var $productDropdown = $('#category_item_id');
            $productDropdown.empty();
            $productDropdown.append('<option value="all">Select All ' + (data.category_name || '') + '</option>');
            
            $.each(data.items, function (index, product) {
                $productDropdown.append(
                    '<option value="' + product.id + '">' + product.name + '</option>'
                );
            });
            
            if(selectedItemIds.includes('all')) {
                $productDropdown.val('all'); 
            } else {
                 $productDropdown.val(selectedItemIds);
            }
            $productDropdown.trigger('change');
        });
    }
});
</script>