@extends('layouts.app')

@push('style')
<style>
    .info-box {
        border-radius: 8px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }
    .card {
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    }
    .chart-container {
        position: relative;
        height: 300px;
    }
    .stock-status-good { color: #28a745; }
    .stock-status-warning { color: #ffc107; }
    .stock-status-danger { color: #dc3545; }
    .table-responsive {
        border-radius: 8px;
    }
    .summary-card {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border-radius: 15px;
        padding: 20px;
        margin-bottom: 20px;
    }
    .stat-card {
        transition: transform 0.2s;
    }
    .stat-card:hover {
        transform: translateY(-2px);
    }
</style>
@endpush

@section('main')
<!-- Content Header (Page header) -->
<section class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1><i class="fas fa-chart-line"></i> Product Stock Report</h1>
            </div>
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="{{ route('dashboard') }}">Home</a></li>
                    <li class="breadcrumb-item"><a href="{{ route('product.index') }}">Products</a></li>
                    <li class="breadcrumb-item active">Stock Report</li>
                </ol>
            </div>
        </div>
    </div>
</section>

<!-- Main content -->
<section class="content">
    
    <!-- Summary Cards Row -->
    <div class="row">
        <!-- Total Overview -->
        <div class="col-lg-3 col-6">
            <div class="info-box stat-card">
                <span class="info-box-icon bg-info elevation-1"><i class="fas fa-cubes"></i></span>
                <div class="info-box-content">
                    <span class="info-box-text">Total Products</span>
                    <span class="info-box-number">{{ number_format($totalProducts) }}</span>
                </div>
            </div>
        </div>
        
        <div class="col-lg-3 col-6">
            <div class="info-box stat-card">
                <span class="info-box-icon bg-success elevation-1"><i class="fas fa-box"></i></span>
                <div class="info-box-content">
                    <span class="info-box-text">Total Stock Quantity</span>
                    <span class="info-box-number">{{ number_format($totalStock) }}</span>
                </div>
            </div>
        </div>
        
        <div class="col-lg-3 col-6">
            <div class="info-box stat-card">
                <span class="info-box-icon bg-warning elevation-1"><i class="fas fa-dollar-sign"></i></span>
                <div class="info-box-content">
                    <span class="info-box-text">Total Stock Value</span>
                    <span class="info-box-number">BHD {{ number_format($totalBuyValue, 2) }}</span>
                </div>
            </div>
        </div>
        
        <div class="col-lg-3 col-6">
            <div class="info-box stat-card">
                <span class="info-box-icon bg-primary elevation-1"><i class="fas fa-chart-line"></i></span>
                <div class="info-box-content">
                    <span class="info-box-text">Potential Revenue</span>
                    <span class="info-box-number">BHD {{ number_format($totalSellValue, 2) }}</span>
                </div>
            </div>
        </div>
    </div>

    <!-- Stock Status Cards -->
    <div class="row">
        <div class="col-lg-4 col-6">
            <div class="info-box stat-card">
                <span class="info-box-icon bg-success elevation-1"><i class="fas fa-check-circle"></i></span>
                <div class="info-box-content">
                    <span class="info-box-text">In Stock (Good)</span>
                    <span class="info-box-number">{{ $inStockProducts }}</span>
                    <div class="progress">
                        <div class="progress-bar bg-success" style="width: {{ $totalProducts > 0 ? ($inStockProducts / $totalProducts) * 100 : 0 }}%"></div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="col-lg-4 col-6">
            <div class="info-box stat-card">
                <span class="info-box-icon bg-warning elevation-1"><i class="fas fa-exclamation-triangle"></i></span>
                <div class="info-box-content">
                    <span class="info-box-text">Low Stock (≤5)</span>
                    <span class="info-box-number">{{ $lowStockCount }}</span>
                    <div class="progress">
                        <div class="progress-bar bg-warning" style="width: {{ $totalProducts > 0 ? ($lowStockCount / $totalProducts) * 100 : 0 }}%"></div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="col-lg-4 col-6">
            <div class="info-box stat-card">
                <span class="info-box-icon bg-danger elevation-1"><i class="fas fa-times-circle"></i></span>
                <div class="info-box-content">
                    <span class="info-box-text">Out of Stock</span>
                    <span class="info-box-number">{{ $outOfStockCount }}</span>
                    <div class="progress">
                        <div class="progress-bar bg-danger" style="width: {{ $totalProducts > 0 ? ($outOfStockCount / $totalProducts) * 100 : 0 }}%"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Charts and Analysis Row -->
    <div class="row">
        <!-- Stock by Condition Chart -->
        <div class="col-md-6">
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title"><i class="fas fa-chart-pie"></i> Stock by Condition</h3>
                    <div class="card-tools">
                        <button type="button" class="btn btn-tool" data-card-widget="collapse">
                            <i class="fas fa-minus"></i>
                        </button>
                    </div>
                </div>
                <div class="card-body">
                    <div class="chart-container">
                        <canvas id="conditionChart"></canvas>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Stock by Type Chart -->
        <div class="col-md-6">
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title"><i class="fas fa-chart-doughnut"></i> Stock by Type</h3>
                    <div class="card-tools">
                        <button type="button" class="btn btn-tool" data-card-widget="collapse">
                            <i class="fas fa-minus"></i>
                        </button>
                    </div>
                </div>
                <div class="card-body">
                    <div class="chart-container">
                        <canvas id="typeChart"></canvas>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Condition Details Row -->
    <div class="row">
        <div class="col-lg-3 col-6">
            <div class="small-box bg-success">
                <div class="inner">
                    <h3>{{ number_format($newConditionStock) }}</h3>
                    <p>New Condition Stock</p>
                    <small>Value: BHD {{ number_format($newConditionValue, 2) }}</small>
                </div>
                <div class="icon">
                    <i class="fas fa-star"></i>
                </div>
            </div>
        </div>
        
        <div class="col-lg-3 col-6">
            <div class="small-box bg-info">
                <div class="inner">
                    <h3>{{ number_format($usedConditionStock) }}</h3>
                    <p>Used Condition Stock</p>
                    <small>Value: BHD {{ number_format($usedConditionValue, 2) }}</small>
                </div>
                <div class="icon">
                    <i class="fas fa-recycle"></i>
                </div>
            </div>
        </div>
        
        <div class="col-lg-3 col-6">
            <div class="small-box bg-warning">
                <div class="inner">
                    <h3>{{ number_format($refurbishedConditionStock) }}</h3>
                    <p>Refurbished Stock</p>
                    <small>Value: BHD {{ number_format($refurbishedConditionValue, 2) }}</small>
                </div>
                <div class="icon">
                    <i class="fas fa-tools"></i>
                </div>
            </div>
        </div>
        
        <div class="col-lg-3 col-6">
            <div class="small-box bg-secondary">
                <div class="inner">
                    <h3>{{ number_format($oldConditionStock) }}</h3>
                    <p>Old Condition Stock</p>
                    <small>Value: BHD {{ number_format($oldConditionValue, 2) }}</small>
                </div>
                <div class="icon">
                    <i class="fas fa-clock"></i>
                </div>
            </div>
        </div>
    </div>

    <!-- Top Value Products -->
    <div class="row">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title"><i class="fas fa-trophy"></i> Top 10 Most Valuable Products by Stock Value</h3>
                    <div class="card-tools">
                        <button type="button" class="btn btn-tool" data-card-widget="collapse">
                            <i class="fas fa-minus"></i>
                        </button>
                    </div>
                </div>
                <div class="card-body table-responsive p-0">
                    <table class="table table-hover text-nowrap">
                        <thead>
                            <tr>
                                <th>Rank</th>
                                <th>Product Name</th>
                                <th>Brand</th>
                                <th>Model</th>
                                <th>Stock Qty</th>
                                <th>Buy Price</th>
                                <th>Total Value</th>
                                <th>Condition</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach($topValueProducts as $index => $product)
                            <tr>
                                <td>
                                    @if($index == 0) <i class="fas fa-trophy text-warning"></i>
                                    @elseif($index == 1) <i class="fas fa-medal text-secondary"></i>
                                    @elseif($index == 2) <i class="fas fa-award text-warning"></i>
                                    @else <span class="badge badge-primary">{{ $index + 1 }}</span>
                                    @endif
                                </td>
                                <td><strong>{{ $product->name ?? 'N/A' }}</strong></td>
                                <td>
                                    @php
                                        $brandName = $product->brand;
                                        if (is_numeric($brandName)) {
                                            $brand = \App\Models\Brand::find($brandName);
                                            $brandName = $brand ? $brand->name : 'Unknown Brand';
                                        }
                                    @endphp
                                    <span class="badge badge-info">{{ $brandName }}</span>
                                </td>
                                <td>
                                    @php
                                        $modelName = $product->model;
                                        if (is_numeric($modelName)) {
                                            $mobileModel = \App\Models\MobileModel::find($modelName);
                                            $modelName = $mobileModel ? $mobileModel->name : 'Unknown Model';
                                        }
                                    @endphp
                                    {{ $modelName }}
                                </td>
                                <td><span class="badge badge-success">{{ $product->stock }}</span></td>
                                <td>BHD {{ number_format($product->buy_price, 2) }}</td>
                                <td><strong class="text-success">BHD {{ number_format($product->buy_price * $product->stock, 2) }}</strong></td>
                                <td>
                                    @switch($product->condition)
                                        @case('new')
                                            <span class="badge badge-success">New</span>
                                            @break
                                        @case('used')
                                            <span class="badge badge-warning">Used</span>
                                            @break
                                        @case('refurbished')
                                            <span class="badge badge-info">Refurbished</span>
                                            @break
                                        @default
                                            <span class="badge badge-secondary">{{ ucfirst($product->condition) }}</span>
                                    @endswitch
                                </td>
                            </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- Low Stock Alert -->
    @if($lowStockProducts->count() > 0)
    <div class="row">
        <div class="col-md-12">
            <div class="card card-warning">
                <div class="card-header">
                    <h3 class="card-title"><i class="fas fa-exclamation-triangle"></i> Low Stock Alert (Stock ≤ 5)</h3>
                    <div class="card-tools">
                        <button type="button" class="btn btn-tool" data-card-widget="collapse">
                            <i class="fas fa-minus"></i>
                        </button>
                    </div>
                </div>
                <div class="card-body table-responsive p-0">
                    <table class="table table-hover text-nowrap">
                        <thead>
                            <tr>
                                <th>Product Name</th>
                                <th>Brand</th>
                                <th>Model</th>
                                <th>Current Stock</th>
                                <th>Buy Price</th>
                                <th>Total Value</th>
                                <th>Status</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach($lowStockProducts as $product)
                            <tr>
                                <td><strong>{{ $product->name ?? 'N/A' }}</strong></td>
                                <td>
                                    @php
                                        $brandName = $product->brand;
                                        if (is_numeric($brandName)) {
                                            $brand = \App\Models\Brand::find($brandName);
                                            $brandName = $brand ? $brand->name : 'Unknown Brand';
                                        }
                                    @endphp
                                    <span class="badge badge-info">{{ $brandName }}</span>
                                </td>
                                <td>
                                    @php
                                        $modelName = $product->model;
                                        if (is_numeric($modelName)) {
                                            $mobileModel = \App\Models\MobileModel::find($modelName);
                                            $modelName = $mobileModel ? $mobileModel->name : 'Unknown Model';
                                        }
                                    @endphp
                                    {{ $modelName }}
                                </td>
                                <td>
                                    <span class="badge badge-danger">{{ $product->stock }}</span>
                                </td>
                                <td>BHD {{ number_format($product->buy_price, 2) }}</td>
                                <td>BHD {{ number_format($product->buy_price * $product->stock, 2) }}</td>
                                <td>
                                    @if($product->stock <= 0)
                                        <span class="badge badge-danger">Out of Stock</span>
                                    @else
                                        <span class="badge badge-warning">Low Stock</span>
                                    @endif
                                </td>
                                <td>
                                    <a href="{{ route('product.edit', $product->id) }}" class="btn btn-sm btn-warning">
                                        <i class="fas fa-edit"></i> Restock
                                    </a>
                                </td>
                            </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    @endif

    <!-- Complete Products Table -->
    <div class="row">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title"><i class="fas fa-list"></i> Complete Product Stock Details</h3>
                    <div class="card-tools">
                        <button type="button" class="btn btn-tool" data-card-widget="collapse">
                            <i class="fas fa-minus"></i>
                        </button>
                        <div class="btn-group">
                            <button type="button" class="btn btn-tool dropdown-toggle" data-toggle="dropdown">
                                <i class="fas fa-download"></i>
                            </button>
                            <div class="dropdown-menu dropdown-menu-right" role="menu">
                                <a href="#" class="dropdown-item" onclick="exportTableToCSV('stock-report.csv')">
                                    <i class="fas fa-file-csv"></i> Export CSV
                                </a>
                                <a href="#" class="dropdown-item" onclick="printTable()">
                                    <i class="fas fa-print"></i> Print
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table id="stockReportTable" class="table table-bordered table-striped">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>Product Name</th>
                                    <th>Type</th>
                                    <th>Brand</th>
                                    <th>Model</th>
                                    <th>IMEI/SN</th>
                                    <th>Condition</th>
                                    <th>Stock Qty</th>
                                    <th>Buy Price</th>
                                    <th>Total Value</th>
                                    <th>Stock Status</th>
                                    <th>Last Updated</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($products as $product)
                                <tr>
                                    <td>{{ $product->id }}</td>
                                    <td><strong>{{ $product->name ?? 'N/A' }}</strong></td>
                                    <td>
                                        @php
                                            $productType = $product->type ?? 'Phone';
                                        @endphp
                                        <span class="badge badge-primary">{{ $productType }}</span>
                                    </td>
                                    <td>
                                        @php
                                            $brandName = $product->brand;
                                            if (is_numeric($brandName)) {
                                                $brand = \App\Models\Brand::find($brandName);
                                                $brandName = $brand ? $brand->name : 'Unknown Brand';
                                            }
                                        @endphp
                                        <span class="badge badge-info">{{ $brandName }}</span>
                                    </td>
                                    <td>
                                        @php
                                            $modelName = $product->model;
                                            if (is_numeric($modelName)) {
                                                $mobileModel = \App\Models\MobileModel::find($modelName);
                                                $modelName = $mobileModel ? $mobileModel->name : 'Unknown Model';
                                            }
                                        @endphp
                                        {{ $modelName }}
                                    </td>
                                    <td>{{ $product->imei_or_sn ?: 'N/A' }}</td>
                                    <td>
                                        @switch($product->condition)
                                            @case('new')
                                                <span class="badge badge-success">New</span>
                                                @break
                                            @case('used')
                                                <span class="badge badge-warning">Used</span>
                                                @break
                                            @case('refurbished')
                                                <span class="badge badge-info">Refurbished</span>
                                                @break
                                            @default
                                                <span class="badge badge-secondary">{{ ucfirst($product->condition) }}</span>
                                        @endswitch
                                    </td>
                                    <td>
                                        <span class="badge 
                                            @if($product->stock <= 0) badge-danger
                                            @elseif($product->stock <= 5) badge-warning
                                            @else badge-success
                                            @endif">
                                            {{ $product->stock }}
                                        </span>
                                    </td>
                                    <td>BHD {{ number_format($product->buy_price, 2) }}</td>
                                    <td><strong>BHD {{ number_format($product->buy_price * $product->stock, 2) }}</strong></td>
                                    <td>
                                        @if($product->stock <= 0)
                                            <span class="badge badge-danger">Out of Stock</span>
                                        @elseif($product->stock <= 5)
                                            <span class="badge badge-warning">Low Stock</span>
                                        @else
                                            <span class="badge badge-success">In Stock</span>
                                        @endif
                                    </td>
                                    <td>{{ $product->updated_at ? $product->updated_at->format('d M, Y H:i') : 'N/A' }}</td>
                                </tr>
                                @endforeach
                            </tbody>
                            <tfoot>
                                <tr class="bg-light font-weight-bold">
                                    <td colspan="7"><strong>TOTALS:</strong></td>
                                    <td><strong>{{ number_format($totalStock) }}</strong></td>
                                    <td>-</td>
                                    <td><strong>BHD {{ number_format($totalBuyValue, 2) }}</strong></td>
                                    <td colspan="2">-</td>
                                </tr>
                            </tfoot>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

</section>
@endsection

@push('script')
<!-- Chart.js -->
<script src="{{ asset('assets/plugins/chart.js/Chart.min.js') }}"></script>

<script>
$(function() {
    // Initialize DataTable
    $("#stockReportTable").DataTable({
        "responsive": true,
        "lengthChange": true,
        "autoWidth": false,
        "buttons": ["copy", "csv", "excel", "pdf", "print", "colvis"],
        "pageLength": 25,
        "order": [[ 9, "desc" ]], // Sort by total value descending
        "columnDefs": [
            { "targets": [8, 9], "type": "num" } // Treat price columns as numbers
        ]
    }).buttons().container().appendTo('#stockReportTable_wrapper .col-md-6:eq(0)');

    // Condition Chart
    var conditionCtx = document.getElementById('conditionChart').getContext('2d');
    var conditionChart = new Chart(conditionCtx, {
        type: 'doughnut',
        data: {
            labels: ['New', 'Used', 'Refurbished', 'Old'],
            datasets: [{
                data: [
                    {{ $newConditionStock ?? 0 }}, 
                    {{ $usedConditionStock ?? 0 }}, 
                    {{ $refurbishedConditionStock ?? 0 }}, 
                    {{ $oldConditionStock ?? 0 }}
                ],
                backgroundColor: [
                    '#28a745',
                    '#ffc107', 
                    '#17a2b8',
                    '#6c757d'
                ],
                borderWidth: 2,
                borderColor: '#fff'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            legend: {
                position: 'bottom',
            },
            tooltips: {
                callbacks: {
                    label: function(tooltipItem, data) {
                        var dataset = data.datasets[tooltipItem.datasetIndex];
                        var currentValue = dataset.data[tooltipItem.index];
                        return data.labels[tooltipItem.index] + ': ' + currentValue + ' units';
                    }
                }
            }
        }
    });

    // Type Chart
    var typeCtx = document.getElementById('typeChart').getContext('2d');
    var typeChart = new Chart(typeCtx, {
        type: 'pie',
        data: {
            labels: ['Phones', 'Accessories'],
            datasets: [{
                data: [{{ $phoneStock ?? 0 }}, {{ $accessoriesStock ?? 0 }}],
                backgroundColor: [
                    '#007bff',
                    '#fd7e14'
                ],
                borderWidth: 2,
                borderColor: '#fff'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            legend: {
                position: 'bottom',
            },
            tooltips: {
                callbacks: {
                    label: function(tooltipItem, data) {
                        var dataset = data.datasets[tooltipItem.datasetIndex];
                        var currentValue = dataset.data[tooltipItem.index];
                        return data.labels[tooltipItem.index] + ': ' + currentValue + ' units';
                    }
                }
            }
        }
    });
});

// Export functions
function exportTableToCSV(filename) {
    var csv = [];
    var rows = document.querySelectorAll("#stockReportTable tr");
    
    for (var i = 0; i < rows.length; i++) {
        var row = [], cols = rows[i].querySelectorAll("td, th");
        
        for (var j = 0; j < cols.length; j++) {
            row.push(cols[j].innerText);
        }
        
        csv.push(row.join(","));
    }

    downloadCSV(csv.join("\n"), filename);
}

function downloadCSV(csv, filename) {
    var csvFile;
    var downloadLink;

    csvFile = new Blob([csv], {type: "text/csv"});
    downloadLink = document.createElement("a");
    downloadLink.download = filename;
    downloadLink.href = window.URL.createObjectURL(csvFile);
    downloadLink.style.display = "none";
    document.body.appendChild(downloadLink);
    downloadLink.click();
}

function printTable() {
    var printContent = document.getElementById('stockReportTable').outerHTML;
    var printWindow = window.open('', '', 'height=600,width=800');
    printWindow.document.write('<html><head><title>Product Stock Report</title>');
    printWindow.document.write('<style>table{border-collapse:collapse;width:100%;}th,td{border:1px solid black;padding:8px;text-align:left;}th{background-color:#f2f2f2;}</style>');
    printWindow.document.write('</head><body>');
    printWindow.document.write('<h1>Product Stock Report</h1>');
    printWindow.document.write(printContent);
    printWindow.document.write('</body></html>');
    printWindow.document.close();
    printWindow.print();
}
</script>
@endpush