@section('heading', 'Laporan Laba Rugi')
@extends('layouts.app')
@section('content')
<section class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1>Laporan Laba Rugi</h1>
            </div>
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="{{route('home')}}">Home</a></li>
                    <li class="breadcrumb-item active">Laporan Laba Rugi</li>
                </ol>
            </div>
        </div>
    </div>
</section>

<section class="content">
    <div class="container-fluid">
        <!-- Filter Card -->
        <div class="card">
            <div class="card-header">
                <h3 class="card-title"><i class="fas fa-filter"></i> Filter Laporan</h3>
            </div>
            <div class="card-body">
                <form action="{{route('report.profit-loss')}}" method="GET">
                    <div class="row">
                        <div class="col-md-3">
                            <div class="form-group">
                                <label>Tanggal Mulai</label>
                                <input type="date" name="start_date" class="form-control" value="{{$startDate}}" required>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="form-group">
                                <label>Tanggal Akhir</label>
                                <input type="date" name="end_date" class="form-control" value="{{$endDate}}" required>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group">
                                <label>Cabang</label>
                                <select name="branch_id" class="form-control">
                                    <option value="">Semua Cabang</option>
                                    @foreach($branches as $branch)
                                        <option value="{{$branch->id}}" {{$branchId == $branch->id ? 'selected' : ''}}>
                                            {{$branch->name}}
                                        </option>
                                    @endforeach
                                </select>
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="form-group">
                                <label>&nbsp;</label>
                                <button type="submit" class="btn btn-primary btn-block">
                                    <i class="fas fa-search"></i> Filter
                                </button>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div>

        <!-- Summary Cards -->
        <div class="row">
            <div class="col-lg-3 col-6">
                <div class="small-box bg-info">
                    <div class="inner">
                        <h3>Rp {{number_format($totalRevenue, 0, ',', '.')}}</h3>
                        <p>Total Penjualan</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-shopping-cart"></i>
                    </div>
                </div>
            </div>

            <div class="col-lg-3 col-6">
                <div class="small-box bg-warning ">
                    <div class="inner">
                        <h3 class="text-white">Rp {{number_format($totalCOGS, 0, ',', '.')}}</h3>
                        <p class="text-white">Harga Pokok Penjualan (HPP)</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-boxes"></i>
                    </div>
                </div>
            </div>

            <div class="col-lg-3 col-6">
                <div class="small-box bg-success">
                    <div class="inner">
                        <h3>Rp {{number_format($grossProfit, 0, ',', '.')}}</h3>
                        <p>Laba Kotor</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-hand-holding-usd"></i>
                    </div>
                </div>
            </div>

            <div class="col-lg-3 col-6">
                <div class="small-box {{$netProfit >= 0 ? 'bg-success' : 'bg-danger'}}">
                    <div class="inner">
                        <h3>Rp {{number_format($netProfit, 0, ',', '.')}}</h3>
                        <p>Laba Bersih</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-chart-line"></i>
                    </div>
                </div>
            </div>
        </div>

        <!-- Additional Metrics -->
        <div class="row">
            <div class="col-md-4">
                <div class="info-box">
                    <span class="info-box-icon bg-info"><i class="fas fa-percent"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text">Margin Laba</span>
                        <span class="info-box-number">{{number_format($profitMargin, 2)}}%</span>
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="info-box">
                    <span class="info-box-icon bg-warning "><i class="fas fa-tags text-white"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text">Total Diskon</span>
                        <span class="info-box-number">Rp {{number_format($totalSalesDiscount, 0, ',', '.')}}</span>
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="info-box">
                    <span class="info-box-icon bg-success"><i class="fas fa-receipt"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text">Total Pajak</span>
                        <span class="info-box-number">Rp {{number_format($totalSalesTax, 0, ',', '.')}}</span>
                    </div>
                </div>
            </div>
        </div>

        <!-- Chart -->
        <div class="row">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title"><i class="fas fa-chart-area"></i> Grafik Penjualan & Pembelian</h3>
                    </div>
                    <div class="card-body">
                        <canvas id="salesChart" height="80"></canvas>
                    </div>
                </div>
            </div>
        </div>

        <!-- Top 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 Produk Terlaris</h3>
                    </div>
                    <div class="card-body">
                        <table class="table table-bordered table-striped">
                            <thead>
                                <tr>
                                    <th style="width: 5%;">No</th>
                                    <th>Produk</th>
                                    <th style="width: 15%;">Qty Terjual</th>
                                    <th style="width: 20%;">Total Penjualan</th>
                                    <th style="width: 20%;">Total Laba</th>
                                </tr>
                            </thead>
                            <tbody>
                                @forelse($topProducts as $index => $item)
                                <tr>
                                    <td class="text-center">{{$index + 1}}</td>
                                    <td>{{$item->product->name ?? 'N/A'}}</td>
                                    <td class="text-center">{{number_format($item->total_qty)}} {{$item->product->unit ?? ''}}</td>
                                    <td class="text-right">Rp {{number_format($item->total_revenue, 0, ',', '.')}}</td>
                                    <td class="text-right">
                                        <span class="badge {{$item->total_profit >= 0 ? 'badge-success' : 'badge-danger'}}">
                                            Rp {{number_format($item->total_profit, 0, ',', '.')}}
                                        </span>
                                    </td>
                                </tr>
                                @empty
                                <tr>
                                    <td colspan="5" class="text-center">Tidak ada data</td>
                                </tr>
                                @endforelse
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <!-- Top Customers -->
        <div class="row">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title"><i class="fas fa-users"></i> Top 10 Customer</h3>
                    </div>
                    <div class="card-body">
                        <table class="table table-bordered table-striped">
                            <thead>
                                <tr>
                                    <th style="width: 5%;">No</th>
                                    <th>Nama Customer</th>
                                    <th style="width: 15%;">Total Transaksi</th>
                                    <th style="width: 20%;">Total Pembelian</th>
                                    <th style="width: 20%;">Rata-rata Pembelian</th>
                                </tr>
                            </thead>
                            <tbody>
                                @forelse($topCustomers as $index => $item)
                                <tr>
                                    <td class="text-center">{{$index + 1}}</td>
                                    <td>
                                        {{$item->customer->name ?? 'N/A'}}
                                        @if($item->customer->phone)
                                            <br><small class="text-muted"><i class="fas fa-phone"></i> {{$item->customer->phone}}</small>
                                        @endif
                                    </td>
                                    <td class="text-center">
                                        <span class="badge badge-info">{{number_format($item->total_transactions)}} transaksi</span>
                                    </td>
                                    <td class="text-right">
                                        <strong>Rp {{number_format($item->total_spending, 0, ',', '.')}}</strong>
                                    </td>
                                    <td class="text-right">Rp {{number_format($item->avg_spending, 0, ',', '.')}}</td>
                                </tr>
                                @empty
                                <tr>
                                    <td colspan="5" class="text-center">Tidak ada data</td>
                                </tr>
                                @endforelse
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <!-- Detailed Breakdown -->
        <div class="row">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title"><i class="fas fa-file-invoice-dollar"></i> Laporan Laba Rugi</h3>
                        <div class="card-tools">
                            <a href="{{route('report.profit-loss.export-pdf', ['start_date' => $startDate, 'end_date' => $endDate, 'branch_id' => $branchId])}}" class="btn btn-danger btn-sm" target="_blank">
                                <i class="fas fa-file-pdf"></i> Export PDF
                            </a>
                            <a href="{{route('report.profit-loss.export-excel', ['start_date' => $startDate, 'end_date' => $endDate, 'branch_id' => $branchId])}}" class="btn btn-success btn-sm">
                                <i class="fas fa-file-excel"></i> Export Excel
                            </a>
                        </div>
                    </div>
                    <div class="card-body">
                        <table class="table table-bordered">
                            <thead class="bg-light">
                                <tr>
                                    <th colspan="2">Periode: {{date('d M Y', strtotime($startDate))}} - {{date('d M Y', strtotime($endDate))}}</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr class="bg-info">
                                    <td><strong>PENDAPATAN</strong></td>
                                    <td></td>
                                </tr>
                                <tr>
                                    <td style="padding-left: 30px;">Penjualan</td>
                                    <td class="text-right">Rp {{number_format($totalRevenue, 0, ',', '.')}}</td>
                                </tr>
                                <tr>
                                    <td style="padding-left: 30px;">Diskon Penjualan</td>
                                    <td class="text-right">(Rp {{number_format($totalSalesDiscount, 0, ',', '.')}})</td>
                                </tr>
                                <tr>
                                    <td style="padding-left: 30px;">Pajak</td>
                                    <td class="text-right">Rp {{number_format($totalSalesTax, 0, ',', '.')}}</td>
                                </tr>
                                <tr class="font-weight-bold">
                                    <td><strong>Total Pendapatan Bersih</strong></td>
                                    <td class="text-right"><strong>Rp {{number_format($totalRevenue - $totalSalesDiscount + $totalSalesTax, 0, ',', '.')}}</strong></td>
                                </tr>

                                <tr class="bg-warning">
                                    <td><strong>HARGA POKOK PENJUALAN (HPP)</strong></td>
                                    <td></td>
                                </tr>
                                <tr>
                                    <td style="padding-left: 30px;">HPP</td>
                                    <td class="text-right">Rp {{number_format($totalCOGS, 0, ',', '.')}}</td>
                                </tr>

                                <tr class="font-weight-bold bg-success">
                                    <td><strong>LABA KOTOR</strong></td>
                                    <td class="text-right"><strong>Rp {{number_format($grossProfit, 0, ',', '.')}}</strong></td>
                                </tr>

                                <tr class="font-weight-bold {{$netProfit >= 0 ? 'bg-success' : 'bg-danger'}} text-white">
                                    <td><strong>LABA BERSIH</strong></td>
                                    <td class="text-right"><strong>Rp {{number_format($netProfit, 0, ',', '.')}}</strong></td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <!-- Product Detail Breakdown -->
        <div class="row">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title"><i class="fas fa-boxes"></i> Laporan Laba Rugi Per Produk</h3>
                        <div class="card-tools">
                            <a href="{{route('report.profit-loss.export-product-analysis-pdf', ['start_date' => $startDate, 'end_date' => $endDate, 'branch_id' => $branchId])}}" class="btn btn-danger btn-sm" target="_blank">
                                <i class="fas fa-file-pdf"></i> Export PDF
                            </a>
                            <a href="{{route('report.profit-loss.export-product-analysis-excel', ['start_date' => $startDate, 'end_date' => $endDate, 'branch_id' => $branchId])}}" class="btn btn-success btn-sm">
                                <i class="fas fa-file-excel"></i> Export Excel
                            </a>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-bordered table-striped">
                                <thead class="bg-light">
                                    <tr>
                                        <th rowspan="2" class="align-middle text-center" style="width: 5%;">Nota</th>
                                        <th rowspan="2" class="align-middle" style="width: 35%;">Nama Item</th>
                                        <th rowspan="2" class="align-middle text-center" style="width: 10%;">Total Jual</th>
                                        <th rowspan="2" class="align-middle text-center" style="width: 15%;">Harga Pokok</th>
                                        <th rowspan="2" class="align-middle text-center" style="width: 10%;">Potongan</th>
                                        <th colspan="2" class="text-center" style="width: 25%;">Laba</th>
                                    </tr>
                                    <tr>
                                        <th class="text-center">Laba Kotor</th>
                                        <th class="text-center">Laba %</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @php
                                        $totalJualAll = 0;
                                        $hargaPokokAll = 0;
                                        $potonganAll = 0;
                                        $labaKotorAll = 0;
                                        $counter = 1;
                                    @endphp
                                    @forelse($productDetails as $detail)
                                        <tr>
                                            <td class="text-center">{{ $counter++ }}</td>
                                            <td>{{ $detail->product->name ?? 'N/A' }} - {{ $detail->product->brand->name ?? '' }}</td>
                                            <td class="text-right">{{ number_format($detail->total_jual, 0, ',', '.') }}</td>
                                            <td class="text-right">{{ number_format($detail->harga_pokok, 0, ',', '.') }}</td>
                                            <td class="text-right">{{ number_format($detail->potongan, 0, ',', '.') }}</td>
                                            <td class="text-right">{{ number_format($detail->laba_kotor, 0, ',', '.') }}</td>
                                            <td class="text-right">{{ number_format($detail->laba_persen, 2) }}</td>
                                        </tr>
                                        @php
                                            $totalJualAll += $detail->total_jual;
                                            $hargaPokokAll += $detail->harga_pokok;
                                            $potonganAll += $detail->potongan;
                                            $labaKotorAll += $detail->laba_kotor;
                                        @endphp
                                        <!-- Sub Total every product -->
                                        <tr class="bg-light">
                                            <td colspan="2" class="text-right"><strong>Sub Total</strong></td>
                                            <td class="text-right"><strong>{{ number_format($detail->total_jual, 0, ',', '.') }}</strong></td>
                                            <td class="text-right"><strong>{{ number_format($detail->harga_pokok, 0, ',', '.') }}</strong></td>
                                            <td class="text-right"><strong>{{ number_format($detail->potongan, 0, ',', '.') }}</strong></td>
                                            <td class="text-right"><strong>{{ number_format($detail->laba_kotor, 0, ',', '.') }}</strong></td>
                                            <td></td>
                                        </tr>
                                    @empty
                                        <tr>
                                            <td colspan="7" class="text-center">Tidak ada data</td>
                                        </tr>
                                    @endforelse

                                    @if($productDetails->count() > 0)
                                        <!-- Grand Total -->
                                        <tr class="bg-success text-white font-weight-bold">
                                            <td colspan="2" class="text-right"><strong>TOTAL</strong></td>
                                            <td class="text-right"><strong>{{ number_format($totalJualAll, 0, ',', '.') }}</strong></td>
                                            <td class="text-right"><strong>{{ number_format($hargaPokokAll, 0, ',', '.') }}</strong></td>
                                            <td class="text-right"><strong>{{ number_format($potonganAll, 0, ',', '.') }}</strong></td>
                                            <td class="text-right"><strong>{{ number_format($labaKotorAll, 0, ',', '.') }}</strong></td>
                                            <td></td>
                                        </tr>
                                    @endif
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>
@endsection

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js"></script>
<script>
$(function() {
    // Prepare data for chart
    var salesData = @json($dailySales);
    var purchasesData = @json($dailyPurchases);

    // Create labels (dates)
    var labels = [];
    var salesValues = [];
    var purchasesValues = [];

    // Get all unique dates
    var allDates = new Set();
    salesData.forEach(item => allDates.add(item.date));
    purchasesData.forEach(item => allDates.add(item.date));

    // Sort dates
    labels = Array.from(allDates).sort();

    // Map sales data
    labels.forEach(date => {
        var saleItem = salesData.find(s => s.date === date);
        salesValues.push(saleItem ? parseFloat(saleItem.total) : 0);

        var purchaseItem = purchasesData.find(p => p.date === date);
        purchasesValues.push(purchaseItem ? parseFloat(purchaseItem.total) : 0);
    });

    // Format labels to readable date
    var formattedLabels = labels.map(date => {
        var d = new Date(date);
        return d.getDate() + ' ' + d.toLocaleString('id-ID', { month: 'short' });
    });

    // Create chart
    var ctx = document.getElementById('salesChart').getContext('2d');
    var myChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: formattedLabels,
            datasets: [{
                label: 'Penjualan',
                data: salesValues,
                backgroundColor: 'rgba(54, 162, 235, 0.2)',
                borderColor: 'rgba(54, 162, 235, 1)',
                borderWidth: 2,
                fill: true,
                tension: 0.4
            }, {
                label: 'Pembelian',
                data: purchasesValues,
                backgroundColor: 'rgba(255, 99, 132, 0.2)',
                borderColor: 'rgba(255, 99, 132, 1)',
                borderWidth: 2,
                fill: true,
                tension: 0.4
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: true,
            plugins: {
                legend: {
                    display: true,
                    position: 'top'
                },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            var label = context.dataset.label || '';
                            if (label) {
                                label += ': ';
                            }
                            label += 'Rp ' + context.parsed.y.toLocaleString('id-ID');
                            return label;
                        }
                    }
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        callback: function(value) {
                            return 'Rp ' + value.toLocaleString('id-ID');
                        }
                    }
                }
            }
        }
    });
});
</script>
@endpush
