@extends('layouts.app')

@section('title', 'Reports - Harshana Systems')
@section('page-title', 'Reports')

@push('styles')
<style>
    #branch_id,
    #branch_id option {
        color: #000000 !important;
        background-color: #ffffff !important;
        opacity: 1 !important;
        font-size: 14px !important;
        font-weight: normal !important;
        -webkit-text-fill-color: #000000 !important;
        text-shadow: none !important;
    }
    
    #branch_id:disabled {
        opacity: 0.5 !important;
    }
</style>
@endpush

@section('content')
    <div class="d-flex justify-content-between mb-3">
        <h1 class="h3 mb-0 page-title-theme">Reports</h1>
    </div>

    <div class="card">
        <div class="card-body">
            <ul class="nav nav-tabs" id="reportTabs" role="tablist">
                <li class="nav-item" role="presentation">
                    <button class="nav-link active" id="stock-summary-tab" data-bs-toggle="tab" data-bs-target="#stock-summary" type="button" role="tab" aria-controls="stock-summary" aria-selected="true">Stock Summary</button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="grn-report-tab" data-bs-toggle="tab" data-bs-target="#grn-report" type="button" role="tab" aria-controls="grn-report" aria-selected="false">GRN Report</button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="grn-items-tab" data-bs-toggle="tab" data-bs-target="#grn-items" type="button" role="tab" aria-controls="grn-items" aria-selected="false">GRN Items</button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="invoice-items-tab" data-bs-toggle="tab" data-bs-target="#invoice-items" type="button" role="tab" aria-controls="invoice-items" aria-selected="false">Invoice Items</button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="product-prices-tab" data-bs-toggle="tab" data-bs-target="#product-prices" type="button" role="tab" aria-controls="product-prices" aria-selected="false">Product Selling Prices</button>
                </li>
                <li class="nav-item" role="presentation" style="display:none">
                    <button class="nav-link" id="damage-stock-tab" data-bs-toggle="tab" data-bs-target="#damage-stock" type="button" role="tab" aria-controls="damage-stock" aria-selected="false">Damage Stock</button>
                </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="stock-transfer-tab" data-bs-toggle="tab" data-bs-target="#stock-transfer" type="button" role="tab" aria-controls="stock-transfer" aria-selected="false">Stock Transfers</button>
                    </li>
            </ul>

            <div class="tab-content" id="reportTabsContent">
                <div class="tab-pane fade show active" id="stock-summary" role="tabpanel" aria-labelledby="stock-summary-tab">
                    <div class="d-flex justify-content-between mb-3">
                        <h5>Stock Summary</h5>
                        <div>
                            <button type="button" class="btn btn-success btn-sm" onclick="exportStockExcel()">Export Excel</button>
                            <button type="button" class="btn btn-danger btn-sm" onclick="exportStockPdf()">Export PDF</button>
                        </div>
                    </div>

                    <!-- Branch Filter -->
                    <form method="GET" action="{{ route('reports') }}" id="stockFilterForm" class="mb-4">
                        <input type="hidden" name="active_tab" value="stock-summary">
                        <div class="row g-3 align-items-end">
                            <div class="col-md-3">
                                <label for="branch_id" class="form-label">Branch</label>
                                <select name="branch_id" id="branch_id" class="form-select" 
                                        style="color: #212529 !important; 
                                               background-color: #ffffff !important; 
                                               opacity: 1 !important;
                                               -webkit-text-fill-color: #212529 !important;">
                                    <option value="" style="color: #212529 !important; background-color: #ffffff !important;">All Branches</option>
                                    @foreach($branches as $branch)
                                        <option value="{{ $branch->id }}" 
                                                {{ request('branch_id') == $branch->id ? 'selected' : '' }} 
                                                style="color: #212529 !important; background-color: #ffffff !important;">
                                            {{ $branch->name }}
                                        </option>
                                    @endforeach
                                </select>
                            </div>
                            <div class="col-md-3">
                                <label for="stock_search_input" class="form-label">Product (name / code / barcode)</label>
                                <div style="position: relative;">
                                    <input type="text" name="stock_search" id="stock_search_input" class="form-control" value="{{ request('stock_search') }}" placeholder="Type name, code or barcode" autocomplete="off">
                                    <input type="hidden" name="stock_product_id" id="stock_product_id" value="{{ request('stock_product_id') }}">
                                    <ul id="stock_search_list" class="list-group" style="position: absolute; z-index: 9999; width: 100%; display: none; max-height: 240px; overflow-y: auto;
                                        box-shadow: 0 2px 8px rgba(0,0,0,0.15);">
                                    </ul>
                                </div>
                            </div>
                            <div class="col-md-2">
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-filter"></i> Filter
                                </button>
                                <a href="{{ route('reports') }}" class="btn btn-secondary">
                                    <i class="fas fa-redo"></i> Reset
                                </a>
                            </div>
                        </div>
                    </form>

                    <div class="table-responsive">
                        <table class="table table-striped table-hover mb-0">
                            <thead>
                                <tr>
                                    <th>#</th>
                                    <th>Product Code</th>
                                    <th>Product Name</th>
                                    <th>Category</th>
                                    <th>Branch</th>
                                    <th>Qty Type</th>
                                    <th>Qty</th>
                                    <th style="display: none;">Total Cost</th>
                                </tr>
                            </thead>
                            <tbody>
                                @php
                                    $totalStockValue = 0;
                                @endphp
                                @foreach($stockData as $index => $stock)
                                    <tr>
                                        <td>{{ $index + 1 }}</td>
                                        <td>{{ $stock->product->product_code }}</td>
                                        <td>{{ $stock->product->product_name }}</td>
                                        <td>{{ $stock->product->category->name ?? '-' }}</td>
                                        <td>{{ $stock->branch->name ?? '-' }}</td>
                                        <td>{{ $stock->product->qtyType->qty_type ?? '-' }}</td>
                                        <td>{{ $stock->qty }}</td>
                                        <td style="display: none;">{{ number_format($stock->total_cost, 2) }}</td>
                                    </tr>
                                    @php
                                        $totalStockValue += $stock->total_cost;
                                    @endphp
                                @endforeach
                                <tr style="color: black; font-weight: bold; display: none;">
                                    <td colspan="7">Total Stock Value</td>
                                    <td>{{ number_format($totalStockValue, 2) }}</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>

                <div class="tab-pane fade" id="grn-report" role="tabpanel" aria-labelledby="grn-report-tab">
                    <div class="d-flex justify-content-between mb-3">
                        <h5>GRN Report</h5>
                        <div>
                            <button type="button" class="btn btn-success btn-sm" onclick="exportGrnExcel()">Export Excel</button>
                            <button type="button" class="btn btn-danger btn-sm" onclick="exportGrnPdf()">Export PDF</button>
                        </div>
                    </div>

                    <!-- Filters -->
                    <form method="GET" action="{{ route('reports') }}" id="grnFilterForm" class="mb-4">
                        <input type="hidden" name="active_tab" value="grn-report">
                        <div class="row g-3">
                            <div class="col-md-2">
                                <label for="year" class="form-label">Year</label>
                                <select name="year" id="year" class="form-select">
                                    <option value="">All Years</option>
                                    @for($i = date('Y'); $i >= date('Y') - 5; $i--)
                                        <option value="{{ $i }}" {{ request('year') == $i ? 'selected' : '' }}>{{ $i }}</option>
                                    @endfor
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label for="month" class="form-label">Month</label>
                                <select name="month" id="month" class="form-select">
                                    <option value="">All Months</option>
                                    @for($i = 1; $i <= 12; $i++)
                                        <option value="{{ $i }}" {{ request('month') == $i ? 'selected' : '' }}>{{ date('F', mktime(0, 0, 0, $i, 1)) }}</option>
                                    @endfor
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label for="start_date" class="form-label">Start Date</label>
                                <input type="date" name="start_date" id="start_date" class="form-control" value="{{ request('start_date') }}">
                            </div>
                            <div class="col-md-2">
                                <label for="end_date" class="form-label">End Date</label>
                                <input type="date" name="end_date" id="end_date" class="form-control" value="{{ request('end_date') }}">
                            </div>
                            <div class="col-md-2">
                                <label for="supplier_id" class="form-label">Supplier</label>
                                <select name="supplier_id" id="supplier_id" class="form-select" style="color: white;">
                                    <option value="" style="color: white;">All Suppliers</option>
                                    @foreach($suppliers as $supplier)
                                        <option value="{{ $supplier->id }}" {{ request('supplier_id') == $supplier->id ? 'selected' : '' }} style="color: white;">{{ $supplier->supplier_name }}</option>
                                    @endforeach
                                </select>
                            </div>
                            <div class="col-md-2 d-flex align-items-end">
                                <button type="submit" class="btn btn-primary me-2">Filter</button>
                                <a href="{{ route('reports') }}#grn-report" class="btn btn-secondary">Clear</a>
                            </div>
                        </div>
                    </form>

                    <div class="table-responsive">
                        <table class="table table-striped table-hover mb-0">
                            <thead>
                                <tr>
                                    <th>#</th>
                                    <th>Date</th>
                                    <th>GRN Number</th>
                                    <th>Supplier</th>
                                    <th>Total</th>
                                    <th>Total Cost</th>
                                </tr>
                            </thead>
                            <tbody>
                                @php
                                    $totalAmount = 0;
                                    $totalCost = 0;
                                @endphp
                                @foreach($grns as $index => $grn)
                                    <tr>
                                        <td>{{ $index + 1 }}</td>
                                        <td>{{ $grn->date_time ? \Carbon\Carbon::parse($grn->date_time)->format('Y-m-d') : '-' }}</td>
                                        <td>{{ $grn->grn_number }}</td>
                                        <td>{{ $grn->supplier->supplier_name ?? '-' }}</td>
                                        <td>{{ number_format($grn->total, 2) }}</td>
                                        <td>{{ number_format($grn->total_cost, 2) }}</td>
                                    </tr>
                                    @php
                                        $totalAmount += $grn->total;
                                        $totalCost += $grn->total_cost;
                                    @endphp
                                @endforeach
                               <tr style="color: black;">
                                    <td colspan="4">Total</td>
                                    <td >{{ number_format($totalAmount, 2) }}</td>
                                    <td>{{ number_format($totalCost, 2) }}</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>

                <div class="tab-pane fade" id="grn-items" role="tabpanel" aria-labelledby="grn-items-tab">
                    <div class="d-flex justify-content-between mb-3">
                        <h5>GRN Items Report (Item-wise totals)</h5>
                        <div>
                            <button type="button" class="btn btn-success btn-sm" onclick="exportGrnItemsExcel()">Export Excel</button>
                            <button type="button" class="btn btn-danger btn-sm" onclick="exportGrnItemsPdf()">Export PDF</button>
                        </div>
                    </div>

                    <!-- Filters -->
                    <form method="GET" action="{{ route('reports') }}" id="grnItemsFilterForm" class="mb-4">
                        <input type="hidden" name="active_tab" value="grn-items">
                        <div class="row g-3">
                            <div class="col-md-2">
                                <label for="year" class="form-label">Year</label>
                                <select name="year" id="year" class="form-select">
                                    <option value="">All Years</option>
                                    @for($i = date('Y'); $i >= date('Y') - 5; $i--)
                                        <option value="{{ $i }}" {{ request('year') == $i ? 'selected' : '' }}>{{ $i }}</option>
                                    @endfor
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label for="month" class="form-label">Month</label>
                                <select name="month" id="month" class="form-select">
                                    <option value="">All Months</option>
                                    @for($i = 1; $i <= 12; $i++)
                                        <option value="{{ $i }}" {{ request('month') == $i ? 'selected' : '' }}>{{ date('F', mktime(0, 0, 0, $i, 1)) }}</option>
                                    @endfor
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label for="start_date" class="form-label">Start Date</label>
                                <input type="date" name="start_date" id="start_date" class="form-control" value="{{ request('start_date') }}">
                            </div>
                            <div class="col-md-2">
                                <label for="end_date" class="form-label">End Date</label>
                                <input type="date" name="end_date" id="end_date" class="form-control" value="{{ request('end_date') }}">
                            </div>
                            <div class="col-md-2">
                                <label for="supplier_id" class="form-label">Supplier</label>
                                <select name="supplier_id" id="supplier_id" class="form-select">
                                    <option value="">All Suppliers</option>
                                    @foreach($suppliers as $supplier)
                                        <option value="{{ $supplier->id }}" {{ request('supplier_id') == $supplier->id ? 'selected' : '' }}>{{ $supplier->supplier_name }}</option>
                                    @endforeach
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label for="grn_item_product_id" class="form-label">Product</label>
                                <select name="grn_item_product_id" id="grn_item_product_id" class="form-select">
                                    <option value="">All Products</option>
                                    @foreach($allProducts as $product)
                                        <option value="{{ $product->id }}" {{ request('grn_item_product_id') == $product->id ? 'selected' : '' }}>{{ $product->product_name }}</option>
                                    @endforeach
                                </select>
                            </div>
                            <div class="col-md-2 d-flex align-items-end">
                                <button type="submit" class="btn btn-primary me-2">Filter</button>
                                <a href="{{ route('reports') }}#grn-items" class="btn btn-secondary">Clear</a>
                            </div>
                        </div>
                    </form>

                    <div class="table-responsive">
                        <table class="table table-striped table-hover mb-0">
                            <thead>
                                <tr>
                                    <th>#</th>
                                    <th>Product</th>
                                    <th>GRN Numbers</th>
                                    <th>Total Qty</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($grnItems as $index => $it)
                                    <tr>
                                        <td>{{ $index + 1 }}</td>
                                        <td>{{ $it->product->product_name ?? '-' }}</td>
                                        <td>{{ $it->grn_numbers ?? '-' }}</td>
                                        <td>{{ number_format($it->total_qty, 2) }}</td>
                                    </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                </div>

                <div class="tab-pane fade" id="invoice-items" role="tabpanel" aria-labelledby="invoice-items-tab">
                    <div class="d-flex justify-content-between mb-3">
                        <h5>Invoice Items Report (Item-wise totals)</h5>
                        <div>
                            <button type="button" class="btn btn-success btn-sm" onclick="exportInvoiceItemsExcel()">Export Excel</button>
                            <button type="button" class="btn btn-danger btn-sm" onclick="exportInvoiceItemsPdf()">Export PDF</button>
                        </div>
                    </div>

                    <form method="GET" action="{{ route('reports') }}" id="invoiceItemsFilterForm" class="mb-4">
                        <input type="hidden" name="active_tab" value="invoice-items">
                        <div class="row g-3">
                            <div class="col-md-2">
                                <label for="invoice_year" class="form-label">Year</label>
                                <select name="invoice_year" id="invoice_year" class="form-select">
                                    <option value="">All Years</option>
                                    @for($i = date('Y'); $i >= date('Y') - 5; $i--)
                                        <option value="{{ $i }}" {{ request('invoice_year') == $i ? 'selected' : '' }}>{{ $i }}</option>
                                    @endfor
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label for="invoice_month" class="form-label">Month</label>
                                <select name="invoice_month" id="invoice_month" class="form-select">
                                    <option value="">All Months</option>
                                    @for($i = 1; $i <= 12; $i++)
                                        <option value="{{ $i }}" {{ request('invoice_month') == $i ? 'selected' : '' }}>{{ date('F', mktime(0, 0, 0, $i, 1)) }}</option>
                                    @endfor
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label for="invoice_start_date" class="form-label">Start Date</label>
                                <input type="date" name="invoice_start_date" id="invoice_start_date" class="form-control" value="{{ request('invoice_start_date') }}">
                            </div>
                            <div class="col-md-2">
                                <label for="invoice_end_date" class="form-label">End Date</label>
                                <input type="date" name="invoice_end_date" id="invoice_end_date" class="form-control" value="{{ request('invoice_end_date') }}">
                            </div>
                            <div class="col-md-2">
                                <label for="invoice_branch_id" class="form-label">Branch</label>
                                <select name="invoice_branch_id" id="invoice_branch_id" class="form-select">
                                    <option value="">All Branches</option>
                                    @foreach($branches as $branch)
                                        <option value="{{ $branch->id }}" {{ request('invoice_branch_id') == $branch->id ? 'selected' : '' }}>{{ $branch->name }}</option>
                                    @endforeach
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label for="invoice_customer_id" class="form-label">Customer</label>
                                <select name="invoice_customer_id" id="invoice_customer_id" class="form-select">
                                    <option value="">All Customers</option>
                                    @foreach(($customers ?? []) as $customer)
                                        <option value="{{ $customer->id }}" {{ request('invoice_customer_id') == $customer->id ? 'selected' : '' }}>{{ $customer->name ?? $customer->customer_name ?? '-' }}</option>
                                    @endforeach
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label for="invoice_item_product_id" class="form-label">Product</label>
                                <select name="invoice_item_product_id" id="invoice_item_product_id" class="form-select">
                                    <option value="">All Products</option>
                                    @foreach($allProducts as $product)
                                        <option value="{{ $product->id }}" {{ request('invoice_item_product_id') == $product->id ? 'selected' : '' }}>{{ $product->product_name }}</option>
                                    @endforeach
                                </select>
                            </div>
                            <div class="col-md-2 d-flex align-items-end">
                                <button type="submit" class="btn btn-primary me-2">Filter</button>
                                <a href="{{ route('reports') }}#invoice-items" class="btn btn-secondary">Clear</a>
                            </div>
                        </div>
                    </form>

                    <div class="table-responsive">
                        <table class="table table-striped table-hover mb-0">
                            <thead>
                                <tr>
                                    <th>#</th>
                                    <th>Product</th>
                                    <th>Branch</th>
                                    <th>Customer</th>
                                    <th>Invoice Numbers</th>
                                    <th>Invoice Dates</th>
                                    <th>Total Qty</th>
                                    <th>Total Amount</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($invoiceItems as $index => $it)
                                    <tr>
                                        <td>{{ $index + 1 }}</td>
                                        <td>{{ $it->product_name ?? ($it->product->product_name ?? '-') }}</td>
                                        <td>{{ $it->branch_name ?? ($it->branch->name ?? '-') }}</td>
                                        <td>{{ $it->customer_name ?? '-' }}</td>
                                        <td>{{ $it->invoice_numbers ?? '-' }}</td>
                                        <td>{{ $it->invoice_dates ?? '-' }}</td>
                                        <td>{{ number_format($it->total_qty, 2) }}</td>
                                        <td>{{ number_format($it->total_amount, 2) }}</td>
                                    </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                </div>

                <div class="tab-pane fade" id="product-prices" role="tabpanel" aria-labelledby="product-prices-tab">
                    <div class="d-flex justify-content-between mb-3">
                        <h5>Product Selling Prices</h5>
                        <div>
                            <button type="button" class="btn btn-success btn-sm" onclick="exportProductPricesExcel()">Export Excel</button>
                            <button type="button" class="btn btn-danger btn-sm" onclick="exportProductPricesPdf()">Export PDF</button>
                        </div>
                    </div>

                    <form method="GET" action="{{ route('reports') }}" id="productPricesFilterForm" class="mb-4">
                        <input type="hidden" name="active_tab" value="product-prices">
                        <div class="row g-3">
                            <div class="col-md-3">
                                <label for="price_category_id" class="form-label">Category</label>
                                <select name="price_category_id" id="price_category_id" class="form-select">
                                    <option value="">All Categories</option>
                                    @foreach($categories as $cat)
                                        <option value="{{ $cat->id }}" {{ request('price_category_id') == $cat->id ? 'selected' : '' }}>{{ $cat->name }}</option>
                                    @endforeach
                                </select>
                            </div>
                            <!-- Active filter removed -->
                            <div class="col-md-4">
                                <label for="price_search" class="form-label">Search</label>
                                <input type="text" name="price_search" id="price_search" class="form-control" placeholder="Product name or code" value="{{ request('price_search') }}">
                            </div>
                            <div class="col-md-3 d-flex align-items-end">
                                <button type="submit" class="btn btn-primary me-2">Filter</button>
                                <a href="{{ route('reports') }}#product-prices" class="btn btn-secondary">Clear</a>
                            </div>
                        </div>
                    </form>

                    <div class="table-responsive">
                        <table class="table table-striped table-hover mb-0">
                            <thead>
                                <tr>
                                    <th>#</th>
                                    <th>Product Code</th>
                                    <th>Product Name</th>
                                    <th>Category</th>
                                    <th>Qty Type</th>
                                    <th>Selling Price</th>
                                    <th>Market Price</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($productPrices as $index => $p)
                                    <tr>
                                        <td>{{ $index + 1 }}</td>
                                        <td>{{ $p->product_code ?? '-' }}</td>
                                        <td>{{ $p->product_name ?? '-' }}</td>
                                        <td>{{ $p->category->name ?? '-' }}</td>
                                        <td>{{ $p->qtyType->qty_type ?? '-' }}</td>
                                        <td>{{ number_format($p->selling_price, 2) }}</td>
                                        <td>{{ number_format($p->market_price, 2) }}</td>
                                    </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                </div>

                <div class="tab-pane fade" id="damage-stock" role="tabpanel" aria-labelledby="damage-stock-tab">
                    <div class="d-flex justify-content-between mb-3">
                        <h5>Damage Stock Report</h5>
                        <div>
                            <button type="button" class="btn btn-success btn-sm" onclick="exportDamageStockExcel()">Export Excel</button>
                            <button type="button" class="btn btn-danger btn-sm" onclick="exportDamageStockPdf()">Export PDF</button>
                        </div>
                    </div>

                    <!-- Filters -->
                    <form method="GET" action="{{ route('reports') }}" id="damageStockFilterForm" class="mb-4">
                        <input type="hidden" name="active_tab" value="damage-stock">
                        <div class="row g-3">
                            <div class="col-md-2">
                                <label for="damage_year" class="form-label">Year</label>
                                <select name="damage_year" id="damage_year" class="form-select">
                                    <option value="">All Years</option>
                                    @for($i = date('Y'); $i >= date('Y') - 5; $i--)
                                        <option value="{{ $i }}" {{ request('damage_year') == $i ? 'selected' : '' }}>{{ $i }}</option>
                                    @endfor
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label for="damage_month" class="form-label">Month</label>
                                <select name="damage_month" id="damage_month" class="form-select">
                                    <option value="">All Months</option>
                                    @for($i = 1; $i <= 12; $i++)
                                        <option value="{{ $i }}" {{ request('damage_month') == $i ? 'selected' : '' }}>{{ date('F', mktime(0, 0, 0, $i, 1)) }}</option>
                                    @endfor
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label for="damage_start_date" class="form-label">Start Date</label>
                                <input type="date" name="damage_start_date" id="damage_start_date" class="form-control" value="{{ request('damage_start_date') }}">
                            </div>
                            <div class="col-md-2">
                                <label for="damage_end_date" class="form-label">End Date</label>
                                <input type="date" name="damage_end_date" id="damage_end_date" class="form-control" value="{{ request('damage_end_date') }}">
                            </div>
                            <div class="col-md-2">
                                <label for="product_id" class="form-label">Product</label>
                                <select name="product_id" id="product_id" class="form-select">
                                    <option value="">All Products</option>
                                    @foreach($allProducts as $product)
                                        <option value="{{ $product->id }}" {{ request('product_id') == $product->id ? 'selected' : '' }}>{{ $product->product_name }}</option>
                                    @endforeach
                                </select>
                            </div>
                            <div class="col-md-2 d-flex align-items-end">
                                <button type="submit" class="btn btn-primary me-2">Filter</button>
                                <a href="{{ route('reports') }}#damage-stock" class="btn btn-secondary">Clear</a>
                            </div>
                        </div>
                    </form>

                    <div class="table-responsive">
                        <table class="table table-striped table-hover mb-0">
                            <thead>
                                <tr>
                                    <th>#</th>
                                    <th>Date</th>
                                    <th>Product Name</th>
                                    <th>Qty</th>
                                    <th>Total Cost</th>
                                    <th>Remark</th>
                                </tr>
                            </thead>
                            <tbody>
                                @php
                                    $totalQty = 0;
                                    $totalCost = 0;
                                @endphp
                                @foreach($damageStocks as $index => $damage)
                                    <tr>
                                        <td>{{ $index + 1 }}</td>
                                        <td>{{ $damage->date_time ? \Carbon\Carbon::parse($damage->date_time)->format('Y-m-d') : '-' }}</td>
                                        <td>{{ $damage->product->product_name ?? '-' }}</td>
                                        <td>{{ number_format($damage->qty, 2) }}</td>
                                        <td>{{ number_format($damage->total_cost, 2) }}</td>
                                        <td>{{ $damage->remark ?? '-' }}</td>
                                    </tr>
                                    @php
                                        $totalQty += $damage->qty;
                                        $totalCost += $damage->total_cost;
                                    @endphp
                                @endforeach
                                <tr style="color: black;">
                                    <td colspan="3">Total</td>
                                    <td>{{ number_format($totalQty, 2) }}</td>
                                    <td>{{ number_format($totalCost, 2) }}</td>
                                    <td></td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>

                <div class="tab-pane fade" id="stock-transfer" role="tabpanel" aria-labelledby="stock-transfer-tab">
                    <div class="d-flex justify-content-between mb-3">
                        <h5>Stock Transfer Report (Item-wise)</h5>
                        <div>
                            <button type="button" class="btn btn-success btn-sm" onclick="exportStockTransferExcel()">Export Excel</button>
                            <button type="button" class="btn btn-danger btn-sm" onclick="exportStockTransferPdf()">Export PDF</button>
                        </div>
                    </div>

                    <form method="GET" action="{{ route('reports') }}" id="stockTransferFilterForm" class="mb-4">
                        <input type="hidden" name="active_tab" value="stock-transfer">
                        <div class="row g-3">
                            <div class="col-md-2">
                                <label for="transfer_year" class="form-label">Year</label>
                                <select name="transfer_year" id="transfer_year" class="form-select">
                                    <option value="">All Years</option>
                                    @for($i = date('Y'); $i >= date('Y') - 5; $i--)
                                        <option value="{{ $i }}" {{ request('transfer_year') == $i ? 'selected' : '' }}>{{ $i }}</option>
                                    @endfor
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label for="transfer_month" class="form-label">Month</label>
                                <select name="transfer_month" id="transfer_month" class="form-select">
                                    <option value="">All Months</option>
                                    @for($i = 1; $i <= 12; $i++)
                                        <option value="{{ $i }}" {{ request('transfer_month') == $i ? 'selected' : '' }}>{{ date('F', mktime(0, 0, 0, $i, 1)) }}</option>
                                    @endfor
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label for="transfer_start_date" class="form-label">Start Date</label>
                                <input type="date" name="transfer_start_date" id="transfer_start_date" class="form-control" value="{{ request('transfer_start_date') }}">
                            </div>
                            <div class="col-md-2">
                                <label for="transfer_end_date" class="form-label">End Date</label>
                                <input type="date" name="transfer_end_date" id="transfer_end_date" class="form-control" value="{{ request('transfer_end_date') }}">
                            </div>
                            <div class="col-md-2">
                                <label for="from_branch_id" class="form-label">From Branch</label>
                                <select name="from_branch_id" id="from_branch_id" class="form-select">
                                    <option value="">All From Branches</option>
                                    @foreach($branches as $branch)
                                        <option value="{{ $branch->id }}" {{ request('from_branch_id') == $branch->id ? 'selected' : '' }}>{{ $branch->name }}</option>
                                    @endforeach
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label for="to_branch_id" class="form-label">To Branch</label>
                                <select name="to_branch_id" id="to_branch_id" class="form-select">
                                    <option value="">All To Branches</option>
                                    @foreach($branches as $branch)
                                        <option value="{{ $branch->id }}" {{ request('to_branch_id') == $branch->id ? 'selected' : '' }}>{{ $branch->name }}</option>
                                    @endforeach
                                </select>
                            </div>
                            <div class="col-md-3">
                                <label for="transfer_product_id" class="form-label">Product</label>
                                <select name="transfer_product_id" id="transfer_product_id" class="form-select">
                                    <option value="">All Products</option>
                                    @foreach($allProducts as $product)
                                        <option value="{{ $product->id }}" {{ request('transfer_product_id') == $product->id ? 'selected' : '' }}>{{ $product->product_name }}</option>
                                    @endforeach
                                </select>
                            </div>
                            <div class="col-md-1 d-flex align-items-end">
                                <button type="submit" class="btn btn-primary">Filter</button>
                            </div>
                        </div>
                    </form>

                    <div class="table-responsive">
                        <table class="table table-striped table-hover mb-0">
                            <thead>
                                    <tr>
                                        <th>#</th>
                                        <th>Date</th>
                                        <th>Transfer #</th>
                                        <th>From Branch</th>
                                        <th>To Branch</th>
                                        <th>Product (From)</th>
                                        <th>Product (To)</th>
                                        <th>Qty</th>
                                    </tr>
                            </thead>
                            <tbody>
                                    @foreach($stockTransferItems as $index => $it)
                                        <tr>
                                            <td>{{ $index + 1 }}</td>
                                            <td>{{ $it->stockTransfer && $it->stockTransfer->date_time ? \Carbon\Carbon::parse($it->stockTransfer->date_time)->format('Y-m-d') : '-' }}</td>
                                            <td>{{ $it->stockTransfer->id ?? '-' }}</td>
                                            <td>{{ $it->stockTransfer->fromBranch->name ?? '-' }}</td>
                                            <td>{{ $it->stockTransfer->toBranch->name ?? '-' }}</td>
                                            <td>{{ $it->fromProduct->product_name ?? '-' }}</td>
                                            <td>{{ $it->toProduct->product_name ?? '-' }}</td>
                                            <td>{{ number_format($it->qty, 2) }}</td>
                                        </tr>
                                    @endforeach
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection

@push('scripts')
<script>
// Debug: Check if branches are loaded
document.addEventListener('DOMContentLoaded', function() {
    const branchSelect = document.getElementById('branch_id');
    console.log('Branch dropdown options:', branchSelect.options.length);
    for(let i = 0; i < branchSelect.options.length; i++) {
        console.log('Option ' + i + ':', branchSelect.options[i].text, '(value: ' + branchSelect.options[i].value + ')');
    }
    // If the server provided an active_tab parameter, show that tab after reload
    var activeTab = "{{ request('active_tab') }}";
    if (activeTab) {
        try {
            var triggerEl = document.querySelector('#reportTabs button[data-bs-target="#' + activeTab + '"]');
            if (triggerEl && typeof bootstrap !== 'undefined') {
                var tab = new bootstrap.Tab(triggerEl);
                tab.show();
            }
        } catch (e) {
            console.warn('Could not activate tab', activeTab, e);
        }
    }
});

function exportStockExcel() {
    const form = document.getElementById('stockFilterForm');
    const formData = new FormData(form);
    const params = new URLSearchParams(formData);
    window.location.href = '{{ route("reports.export-excel") }}?' + params.toString();
}

function exportStockPdf() {
    const form = document.getElementById('stockFilterForm');
    const formData = new FormData(form);
    const params = new URLSearchParams(formData);
    window.location.href = '{{ route("reports.export-pdf") }}?' + params.toString();
}

function exportGrnExcel() {
    const form = document.getElementById('grnFilterForm');
    const formData = new FormData(form);
    const params = new URLSearchParams(formData);
    window.location.href = '{{ route("reports.export-grn-excel") }}?' + params.toString();
}

function exportGrnPdf() {
    const form = document.getElementById('grnFilterForm');
    const formData = new FormData(form);
    const params = new URLSearchParams(formData);
    window.location.href = '{{ route("reports.export-grn-pdf") }}?' + params.toString();
}

function exportDamageStockExcel() {
    const form = document.getElementById('damageStockFilterForm');
    const formData = new FormData(form);
    const params = new URLSearchParams(formData);
    window.location.href = '{{ route("reports.export-damage-stock-excel") }}?' + params.toString();
}

function exportDamageStockPdf() {
    const form = document.getElementById('damageStockFilterForm');
    const formData = new FormData(form);
    const params = new URLSearchParams(formData);
    window.location.href = '{{ route("reports.export-damage-stock-pdf") }}?' + params.toString();
}

function exportStockTransferExcel() {
    const form = document.getElementById('stockTransferFilterForm');
    const formData = new FormData(form);
    const params = new URLSearchParams(formData);
    window.location.href = '{{ route("reports.export-stock-transfer-excel") }}?' + params.toString();
}

function exportStockTransferPdf() {
    const form = document.getElementById('stockTransferFilterForm');
    const formData = new FormData(form);
    const params = new URLSearchParams(formData);
    window.location.href = '{{ route("reports.export-stock-transfer-pdf") }}?' + params.toString();
}

function exportGrnItemsExcel() {
    const form = document.getElementById('grnItemsFilterForm');
    const formData = new FormData(form);
    const params = new URLSearchParams(formData);
    window.location.href = '{{ route("reports.export-grn-items-excel") }}?' + params.toString();
}

function exportInvoiceItemsExcel() {
    const form = document.getElementById('invoiceItemsFilterForm');
    const formData = new FormData(form);
    const params = new URLSearchParams(formData);
    window.location.href = '{{ route("reports.export-invoice-items-excel") }}?' + params.toString();
}

function exportInvoiceItemsPdf() {
    const form = document.getElementById('invoiceItemsFilterForm');
    const formData = new FormData(form);
    const params = new URLSearchParams(formData);
    window.location.href = '{{ route("reports.export-invoice-items-pdf") }}?' + params.toString();
}

function exportGrnItemsPdf() {
    const form = document.getElementById('grnItemsFilterForm');
    const formData = new FormData(form);
    const params = new URLSearchParams(formData);
    window.location.href = '{{ route("reports.export-grn-items-pdf") }}?' + params.toString();
}

function exportProductPricesExcel() {
    const form = document.getElementById('productPricesFilterForm');
    const formData = new FormData(form);
    const params = new URLSearchParams(formData);
    window.location.href = '{{ route("reports.export-product-prices-excel") }}?' + params.toString();
}

function exportProductPricesPdf() {
    const form = document.getElementById('productPricesFilterForm');
    const formData = new FormData(form);
    const params = new URLSearchParams(formData);
    window.location.href = '{{ route("reports.export-product-prices-pdf") }}?' + params.toString();
}
</script>
@endpush

@push('scripts')
<script>
// Stock summary product autocomplete
(function() {
    @php
        $productsForJs = $allProducts->map(function($p){
            return [
                'id' => $p->id,
                'name' => $p->product_name,
                'code' => $p->product_code,
                'barcode' => $p->product_barcode,
            ];
        })->values();
    @endphp
    const products = @json($productsForJs);
    const input = document.getElementById('stock_search_input');
    const list = document.getElementById('stock_search_list');
    const hiddenId = document.getElementById('stock_product_id');

    if (!input || !list) return;

    function clearList() {
        list.innerHTML = '';
        list.style.display = 'none';
    }

    function buildItem(p) {
        const li = document.createElement('li');
        li.className = 'list-group-item list-group-item-action';
        li.style.cursor = 'pointer';
        li.innerHTML = '<strong>' + (p.name || '-') + '</strong><br><small>' + (p.code || '-') + ' | ' + (p.barcode || '-') + '</small>';
        li.addEventListener('click', function() {
            input.value = p.name + ' (' + (p.code || '') + ')';
            hiddenId.value = p.id;
            clearList();
        });
        return li;
    }

    input.addEventListener('input', function(e) {
        const q = (e.target.value || '').trim().toLowerCase();
        // if user types, clear selected id
        hiddenId.value = '';
        if (!q) { clearList(); return; }

        const matches = products.filter(function(p) {
            return (p.name || '').toLowerCase().includes(q) || (p.code || '').toLowerCase().includes(q) || (p.barcode || '').toLowerCase().includes(q);
        }).slice(0, 50);

        list.innerHTML = '';
        if (matches.length === 0) { clearList(); return; }
        matches.forEach(function(m) { list.appendChild(buildItem(m)); });
        list.style.display = 'block';
    });

    // hide when clicking outside
    document.addEventListener('click', function(ev) {
        if (!input.contains(ev.target) && !list.contains(ev.target)) {
            clearList();
        }
    });

    // on form submit, if a product id is set, ensure stock_search input reflects it
    const stockForm = document.getElementById('stockFilterForm');
    if (stockForm) {
        stockForm.addEventListener('submit', function() {
            if (hiddenId.value && !input.value) {
                // set a textual label if empty
                const p = products.find(function(pp){ return pp.id == hiddenId.value; });
                if (p) input.value = p.name;
            }
        });
    }
})();
</script>
@endpush