@extends('admin.layouts.app')

@section('content')
<style>
    .rec-tab{
        background-color: #f2f6faff !important;
        border-left:1px solid grey;
        border-right:1px solid grey;
    }
    .issue-tab{
        border-left:1px solid grey;
        border-right:1px solid grey;
    }
    .balance-tab{
        background-color: #d1d4d1ff !important;
        border-left:1px solid grey;
        border-right:1px solid grey;
    }
</style>
    <div class="page-header">
        <div class="page-title">
            <h4>Stock Bin Card</h4>
            <ul class="breadcrumb">
                <li class="breadcrumb-item active">Stock Bin Card</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.stock-bin-card') }}" class="row gy-2 gx-3 align-items-end" method="get">
            <div class="col-md">
                <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 class="col-md">
                <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 class="col-md">
                <label class="form-label" for="product">Products</label>
                <select name="product" id="product" class="js-example-basic-single select2">
                    <option value="">Select Product</option>
                    <optgroup label="Final Products">
                        @foreach ($finalProducts as $finalProduct)
                            <option value="{{ 'product_' . $finalProduct->id }}"
                                {{ isset($productType, $product) && $productType == 1 && $product->id == $finalProduct->id ? 'selected' : '' }}>
                                {{ $finalProduct->product->name ?? $finalProduct->product->brand_name }}
                            </option>
                        @endforeach
                    </optgroup>
                    <optgroup label="Raw Materials">
                        @foreach ($rawMaterials as $rawMaterial)
                            <option value="{{ 'raw_' . $rawMaterial->id }}"
                                {{ isset($productType, $product) && $productType == 1 && $product->id == $rawMaterial->id ? 'selected' : '' }}>
                                {{ $rawMaterial->name }}
                            </option>
                        @endforeach
                    </optgroup>
                </select>
            </div> --}}
            <div class="col-md">
                <label class="form-label" for="type">Type</label>
                <select name="type" id="type" class="js-example-basic-single select2">
                    <option @selected(isset($type) && $type == 'product') value="product">Product</option>
                    <option @selected(isset($type) && $type == 'raw_items') value="raw_items">Raw Material Items</option>
                </select>
            </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($selectedCategoryId) && $selectedCategoryId == $category->id)>
                            {{ $category->name }}
                            {{ isset($category->prefix) ? '(' . $category->prefix . ')' : '' }}
                        </option>
                    @endforeach
                </select>
            </div>

            <div class="col-md">
                <label class="form-label" for="drop_product_id">Product</label>
                <select name="product_id" id="drop_product_id" class="js-example-basic-single select2">
                    <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">Stock Bin Card</h5>
            <p class="text-center text-muted mb-2">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>
            @if ($productType && $productType == 0)
                <div class="row mx-0">
                    <div class="col-md-4">
                        <div class="card">
                            <div class="card-body">
                                <p class="mb-0">Max Level: {{ $product->max_level }}</p>
                                <p class="mb-0">Max Level: {{ $product->min_level }}</p>
                            </div>
                        </div>
                    </div>
                </div>
            @endif
            @if ($productType)
                <div class="row mx-0">
                    <div class="col">
                        <p class="fs-6 mb-2">Material:
                            <strong>{{ $productType == 0 ? $product->name : $product->product->name . ' | ' . $product->packingType->name . ' | ' . $product->packSize->name }}</strong>
                        </p>
                    </div>
                    <div class="col-auto">
                        <p class="fs-6 mb-2">Code #
                            <strong>{{ $productType == 0 ? $product->code : $product->product->code }}</strong>
                        </p>
                    </div>
                </div>
            @endif
            <div class="table-responsive">
                <table class="table table-striped" id="binCardTable">
                    <thead class="table-primary">
                        <tr>
                            <th rowspan="2">Date</th>
                            <th rowspan="2">Name</th>
                            <th rowspan="2">Doc</th>
                            <th colspan="3" class="text-center rec-tab ">Received</th>
                            <th colspan="3" class="text-center issue-tab">Issued</th>
                            <th colspan="3" class="text-center balance-tab">Balance</th>
                        </tr>
                        <tr>
                            <th class="rec-tab">QTY</th>
                            <th class="rec-tab">Rate</th>
                            <th class="rec-tab">Amount</th>
                            <th class="issue-tab">QTY</th>
                            <th class="issue-tab">Rate</th>
                            <th class="issue-tab">Amount</th>
                            <th class="balance-tab">QTY</th>
                            <th class="balance-tab">Avg.Price</th>
                            <th class="balance-tab">Amount</th>
                        </tr>
                    </thead>
                    <tbody>
                        @if ($stockBinCards)
                            @php $running_balance = 0; @endphp
                            @foreach ($stockBinCards as $stockBinCard)
                                @php
                                    if ($stockBinCard['type'] == 'received') {
                                        $running_balance += $stockBinCard['quantity'];
                                    } elseif ($stockBinCard['type'] == 'issued') {
                                        $running_balance -= $stockBinCard['quantity'];
                                    }
                                @endphp
                                <tr>
                                    <td>{{ $stockBinCard['date'] }}</td>
                                    <td>{{ $stockBinCard['item_name'] }}</td>
                                    <td>{{ $stockBinCard['doc'] }}</td>
                                    <td>{{ number_format($stockBinCard['type'] == 'received' ? $stockBinCard['quantity'] : 0, 2) }}
                                    </td>
                                    <td>{{ number_format($stockBinCard['type'] == 'received' ? $stockBinCard['unit_price'] : 0, 2) }}
                                    </td>
                                    <td>{{ number_format($stockBinCard['type'] == 'received' ? $stockBinCard['total'] : 0, 2) }}
                                    </td>
                                    <td>{{ number_format($stockBinCard['type'] == 'issued' ? $stockBinCard['quantity'] : 0, 2) }}
                                    </td>
                                    <td>{{ number_format($stockBinCard['type'] == 'issued' ? $stockBinCard['unit_price'] : 0, 2) }}
                                    </td>
                                    <td>{{ number_format($stockBinCard['type'] == 'issued' ? $stockBinCard['total'] : 0, 2) }}
                                    </td>
                                    <td>{{ abs(number_format($running_balance, 2)) }}</td>
                                    <td>{{ $stockBinCard['balance_unit_price'] }}</td>
                                    <td>{{ $stockBinCard['balance_total'] }}</td>
                                </tr>
                            @endforeach
                        @endif
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    <!-- Print timestamp will be added here -->
    <div id="printTimestampContainer"></div>
    </div>
    </div>
@endsection

<style>
    @media print {
        @page {
            margin: 0;
        }

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

    const title = "Stock Bin Card";
    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;

    // Define multi-row headers to match UI layout
    const headerRow1 = [
        { text: 'Date', style: 'tableHeader', rowSpan: 2 },
        { text: 'Name', style: 'tableHeader', rowSpan: 2 },
        { text: 'Doc', style: 'tableHeader', rowSpan: 2 },
        { text: 'Received', style: 'tableHeaderRec', colSpan: 3 },
        {},
        {},
        { text: 'Issued', style: 'tableHeaderIssue', colSpan: 3 },
        {},
        {},
        { text: 'Balance', style: 'tableHeaderBal', colSpan: 3 },
        {},
        {}
    ];

    const headerRow2 = [
        {},
        {},
        {},
        { text: 'QTY', style: 'tableHeaderRec' },
        { text: 'Rate', style: 'tableHeaderRec' },
        { text: 'Amount', style: 'tableHeaderRec' },
        { text: 'QTY', style: 'tableHeaderIssue' },
        { text: 'Rate', style: 'tableHeaderIssue' },
        { text: 'Amount', style: 'tableHeaderIssue' },
        { text: 'QTY', style: 'tableHeaderBal' },
        { text: 'Avg. Price', style: 'tableHeaderBal' },
        { text: 'Amount', style: 'tableHeaderBal' }
    ];

    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: 2,
                    widths: ['auto', '*', 'auto', 'auto', 'auto', 'auto', 'auto', 'auto', 'auto', 'auto', 'auto', 'auto'],
                    body: [headerRow1, headerRow2, ...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' },
            tableHeaderRec: { fontSize: 9, bold: true, fillColor: '#f2f6fa', alignment: 'center' },
            tableHeaderIssue: { fontSize: 9, bold: true, fillColor: '#ffffff', alignment: 'center' },
            tableHeaderBal: { fontSize: 9, bold: true, fillColor: '#d1d4d1', alignment: 'center' },
            tableCell: { fontSize: 8, alignment: 'center' }
        },
        defaultStyle: { fontSize: 8 }
    };

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

function exportCSV() {
    let csv = [];

    csv.push("Stock Bin Card");

    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("binCardTable");

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

    const headerRow = [
        '"Date"', 
        '"Item Name"', 
        '"Doc #"', 
        '"Rec. QTY"', 
        '"Rec. Rate"', 
        '"Rec. Amount"', 
        '"Iss. QTY"', 
        '"Iss. Rate"', 
        '"Iss. Amount"', 
        '"Bal. QTY"', 
        '"Bal. Avg. Price"', 
        '"Bal. Amount"'
    ];

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