@extends('layouts.dashboard.superadminapp')

@section('title', 'Inventory Report')

@section('styles')
<style>
    div.dt-buttons {
        float: left;
        display: flex !important;
    }
    .dataTable {
        overflow-x: auto !important;
        display: table !important;
    }
    .dt-buttons .btn {
        margin-right: 0.5rem !important;
        padding: 0.25rem 0.75rem !important;
        font-size: 0.95rem !important;
    }
    .stat-card {
        border-radius: 10px;
        padding: 20px;
        text-align: center;
        color: #fff;
        transition: transform 0.2s;
    }
    .stat-card:hover {
        transform: translateY(-3px);
    }
    .stat-card .stat-value {
        font-size: 1.8rem;
        font-weight: bold;
    }
    .stat-card .stat-label {
        font-size: 0.85rem;
        opacity: 0.9;
    }
    .bg-total { background: linear-gradient(135deg, #4e73df 0%, #224abe 100%); }
    .bg-inward { background: linear-gradient(135deg, #1cc88a 0%, #13855c 100%); }
    .bg-outward { background: linear-gradient(135deg, #e74a3b 0%, #be2617 100%); }
    .bg-balance { background: linear-gradient(135deg, #36b9cc 0%, #258391 100%); }
    .bg-warning-custom { background: linear-gradient(135deg, #f6c23e 0%, #dda20a 100%); }
</style>
@endsection

@section('content')

<!-- Page Heading -->
<x-layout.page-header title="UEPL | Inventory Report" icon="chart-bar" iconColor="info" />

<!-- Alerts -->
@if(session('success'))
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        <i class="fas fa-check-circle mr-2"></i>{{ session('success') }}
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>
@endif
@if(session('error'))
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <i class="fas fa-exclamation-circle mr-2"></i>{{ session('error') }}
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>
@endif

<!-- Filter Card -->
<div class="card shadow mb-4">
    <div class="card-header py-3" style="background: linear-gradient(135deg, #6c757d 0%, #495057 100%);">
        <h6 class="m-0 font-weight-bold text-white">
            <i class="fas fa-filter mr-2"></i> Filter Options
        </h6>
    </div>
    <div class="card-body">
        <form id="inventoryReportFilters" method="POST" action="{{ route('superadmin.report.inventoryreport') }}">
            @csrf
            <div class="row align-items-end">
                <div class="col-md-3 mb-3">
                    <label class="small font-weight-bold">Material / Item</label>
                    <select name="material_code" id="material_code" class="form-control">
                        <option value="">All Materials</option>
                        @foreach($materialOptions as $code => $desc)
                            <option value="{{ $code }}" {{ $selectedMaterial == $code ? 'selected' : '' }}>
                                {{ $desc }}
                            </option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-2 mb-3">
                    <label class="small font-weight-bold">From Date</label>
                    <input type="date" name="from_date" id="from_date" class="form-control" value="{{ $fromDate }}">
                </div>
                <div class="col-md-2 mb-3">
                    <label class="small font-weight-bold">To Date</label>
                    <input type="date" name="to_date" id="to_date" class="form-control" value="{{ $toDate }}">
                </div>
                <div class="col-md-3 mb-3">
                    <button type="submit" class="btn btn-primary btn-sm mr-2">
                        <i class="fas fa-search mr-1"></i> Apply Filter
                    </button>
                    <a href="{{ route('superadmin.report.inventoryreport') }}" class="btn btn-secondary btn-sm">
                        <i class="fas fa-redo mr-1"></i> Reset
                    </a>
                </div>
                <div class="col-md-2 mb-3">
                    <button type="button" class="btn btn-success btn-sm" id="exportExcelBtn">
                        <i class="fas fa-file-excel mr-1"></i> Export Excel
                    </button>
                </div>
            </div>
        </form>
    </div>
</div>

@php
    $totalItems = count($inventory);
    $totalPurchased = collect($inventory)->sum('purchased');
    $totalSold = collect($inventory)->sum('sold');
    $totalBalance = collect($inventory)->sum('balance');
    $lowStockItems = collect($inventory)->filter(fn($item) => $item['balance'] < 10)->count();
    $negativeStockItems = collect($inventory)->filter(fn($item) => $item['balance'] < 0)->count();
@endphp

<!-- Summary Statistics -->
<div class="row mb-4">
    <div class="col-xl-2 col-md-4 mb-3">
        <div class="stat-card bg-total">
            <div class="stat-value">{{ $totalItems }}</div>
            <div class="stat-label"><i class="fas fa-boxes mr-1"></i> Total Items</div>
        </div>
    </div>
    <div class="col-xl-2 col-md-4 mb-3">
        <div class="stat-card bg-inward">
            <div class="stat-value">{{ number_format($totalPurchased) }}</div>
            <div class="stat-label"><i class="fas fa-arrow-down mr-1"></i> Total Purchased</div>
        </div>
    </div>
    <div class="col-xl-2 col-md-4 mb-3">
        <div class="stat-card bg-outward">
            <div class="stat-value">{{ number_format($totalSold) }}</div>
            <div class="stat-label"><i class="fas fa-arrow-up mr-1"></i> Total Sold</div>
        </div>
    </div>
    <div class="col-xl-2 col-md-4 mb-3">
        <div class="stat-card bg-balance">
            <div class="stat-value">{{ number_format($totalBalance) }}</div>
            <div class="stat-label"><i class="fas fa-warehouse mr-1"></i> Total Balance</div>
        </div>
    </div>
    <div class="col-xl-2 col-md-4 mb-3">
        <div class="stat-card bg-warning-custom">
            <div class="stat-value">{{ $lowStockItems }}</div>
            <div class="stat-label"><i class="fas fa-exclamation-triangle mr-1"></i> Low Stock</div>
        </div>
    </div>
    <div class="col-xl-2 col-md-4 mb-3">
        <div class="stat-card" style="background: linear-gradient(135deg, #858796 0%, #5a5c69 100%);">
            <div class="stat-value">{{ $negativeStockItems }}</div>
            <div class="stat-label"><i class="fas fa-minus-circle mr-1"></i> Negative Stock</div>
        </div>
    </div>
</div>

<!-- Inventory Report Table -->
<div class="card shadow mb-4">
    <div class="card-header py-3" style="background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);">
        <h6 class="m-0 font-weight-bold text-white">
            <i class="fas fa-clipboard-list mr-2"></i> Inventory Summary
        </h6>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table id="inventoryTable" class="table table-bordered table-striped table-sm" width="100%">
                <thead class="thead-light">
                    <tr class="text-center">
                        <th>#</th>
                        <th>Material Code / Item</th>
                        <th>Description</th>
                        <th>Purchased (Inward)</th>
                        <th>Sold (Outward)</th>
                        <th>Balance</th>
                        <th>Status</th>
                    </tr>
                </thead>
                <tbody>
                    @forelse($inventory as $index => $row)
                        <tr class="text-center {{ $row['balance'] < 0 ? 'table-danger' : ($row['balance'] < 10 ? 'table-warning' : '') }}">
                            <td>{{ $index + 1 }}</td>
                            <td class="text-left font-weight-bold">{{ $row['material_code'] }}</td>
                            <td class="text-left">{{ $row['description'] ?? '-' }}</td>
                            <td>
                                <span class="badge badge-success">{{ number_format($row['purchased']) }}</span>
                            </td>
                            <td>
                                <span class="badge badge-danger">{{ number_format($row['sold']) }}</span>
                            </td>
                            <td>
                                <strong class="{{ $row['balance'] < 0 ? 'text-danger' : ($row['balance'] < 10 ? 'text-warning' : 'text-success') }}">
                                    {{ number_format($row['balance']) }}
                                </strong>
                            </td>
                            <td>
                                @if($row['balance'] < 0)
                                    <span class="badge badge-danger"><i class="fas fa-exclamation-circle mr-1"></i>Negative</span>
                                @elseif($row['balance'] < 10)
                                    <span class="badge badge-warning"><i class="fas fa-exclamation-triangle mr-1"></i>Low Stock</span>
                                @elseif($row['balance'] > 100)
                                    <span class="badge badge-success"><i class="fas fa-check-circle mr-1"></i>In Stock</span>
                                @else
                                    <span class="badge badge-info"><i class="fas fa-info-circle mr-1"></i>Normal</span>
                                @endif
                            </td>
                        </tr>
                    @empty
                        <tr>
                            <td colspan="7" class="text-center text-muted py-4">
                                <i class="fas fa-inbox fa-2x mb-2 d-block"></i>
                                No inventory records found. Please select filters and try again.
                            </td>
                        </tr>
                    @endforelse
                </tbody>
                @if(count($inventory) > 0)
                <tfoot class="thead-light">
                    <tr class="text-center font-weight-bold">
                        <td colspan="3" class="text-right">TOTALS:</td>
                        <td><span class="badge badge-success">{{ number_format($totalPurchased) }}</span></td>
                        <td><span class="badge badge-danger">{{ number_format($totalSold) }}</span></td>
                        <td><strong class="{{ $totalBalance < 0 ? 'text-danger' : 'text-success' }}">{{ number_format($totalBalance) }}</strong></td>
                        <td>-</td>
                    </tr>
                </tfoot>
                @endif
            </table>
        </div>
    </div>
</div>

<!-- Quick Summary Cards -->
<div class="row">
    <div class="col-md-6">
        <div class="card shadow mb-4">
            <div class="card-header py-3" style="background: linear-gradient(135deg, #e74a3b 0%, #be2617 100%);">
                <h6 class="m-0 font-weight-bold text-white">
                    <i class="fas fa-exclamation-triangle mr-2"></i> Low Stock Items (< 10)
                </h6>
            </div>
            <div class="card-body p-0">
                <table class="table table-sm mb-0">
                    <thead class="thead-light">
                        <tr>
                            <th>Item</th>
                            <th>Description</th>
                            <th class="text-center">Balance</th>
                        </tr>
                    </thead>
                    <tbody>
                        @php
                            $lowStockList = collect($inventory)->filter(fn($item) => $item['balance'] < 10 && $item['balance'] >= 0)->take(5);
                        @endphp
                        @forelse($lowStockList as $item)
                            <tr>
                                <td class="font-weight-bold">{{ $item['material_code'] }}</td>
                                <td>{{ Str::limit($item['description'], 30) }}</td>
                                <td class="text-center">
                                    <span class="badge badge-warning">{{ $item['balance'] }}</span>
                                </td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="3" class="text-center text-muted">No low stock items</td>
                            </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    <div class="col-md-6">
        <div class="card shadow mb-4">
            <div class="card-header py-3" style="background: linear-gradient(135deg, #1cc88a 0%, #13855c 100%);">
                <h6 class="m-0 font-weight-bold text-white">
                    <i class="fas fa-boxes mr-2"></i> Top Stock Items
                </h6>
            </div>
            <div class="card-body p-0">
                <table class="table table-sm mb-0">
                    <thead class="thead-light">
                        <tr>
                            <th>Item</th>
                            <th>Description</th>
                            <th class="text-center">Balance</th>
                        </tr>
                    </thead>
                    <tbody>
                        @php
                            $topStockList = collect($inventory)->sortByDesc('balance')->take(5);
                        @endphp
                        @forelse($topStockList as $item)
                            <tr>
                                <td class="font-weight-bold">{{ $item['material_code'] }}</td>
                                <td>{{ Str::limit($item['description'], 30) }}</td>
                                <td class="text-center">
                                    <span class="badge badge-success">{{ number_format($item['balance']) }}</span>
                                </td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="3" class="text-center text-muted">No items found</td>
                            </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

@endsection

@section('scripts')
<script>
$(document).ready(function() {
    $('#inventoryTable').DataTable({
        dom: 'Bfrtip',
        buttons: [
            { extend: 'copy', className: 'btn btn-secondary btn-sm' },
            { extend: 'csv', className: 'btn btn-secondary btn-sm' },
            { extend: 'excel', className: 'btn btn-secondary btn-sm' },
            { extend: 'pdf', className: 'btn btn-secondary btn-sm' },
            { extend: 'print', className: 'btn btn-secondary btn-sm' },
            { extend: 'colvis', className: 'btn btn-secondary btn-sm' }
        ],
        pageLength: 25,
        responsive: true,
        order: [[5, 'asc']], // Sort by balance ascending to show low stock first
        language: {
            emptyTable: "No inventory records found"
        }
    });

    // Export Excel logic
    $('#exportExcelBtn').click(function() {
        let form = $('#inventoryReportFilters');
        let originalAction = form.attr('action');
        form.attr('action', '{{ route('superadmin.report.inventoryreport.export') }}');
        form.attr('target', '_blank');
        form.submit();
        setTimeout(function() {
            form.attr('action', originalAction);
            form.removeAttr('target');
        }, 100);
    });
});
</script>
@endsection
