@extends('layouts.app')

@section('main')
<div class="container-fluid">
    <div class="content-header">
        <div class="container-fluid">
            <div class="row mb-2">
                <div class="col-sm-6">
                    <h1>Profit 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 active">Profit Report</li>
                    </ol>
                </div>
            </div>
        </div>
    </div>

    <!-- Summary Cards -->
    <div class="row">
        <div class="col-lg-3 col-md-6 col-12">
            <div class="small-box bg-info">
                <div class="inner">
                    <h3 id="totalSalesCard">{{ number_format($totalSales + ($totalDirectSales ?? 0), 2) }}</h3>
                    <p>Total Sales</p>
                </div>
                <div class="icon">
                    <i class="ion ion-bag"></i>
                </div>
            </div>
        </div>
        <div class="col-lg-3 col-md-6 col-12">
            <div class="small-box bg-success">
                <div class="inner">
                    <h3 id="totalProfitCard">{{ number_format($totalProfit + ($totalDirectProfit ?? 0), 2) }}</h3>
                    <p>Complete Profit</p>
                </div>
                <div class="icon">
                    <i class="ion ion-stats-bars"></i>
                </div>
            </div>
        </div>
        <div class="col-lg-3 col-md-6 col-12">
            <div class="small-box bg-warning">
                <div class="inner">
                    <h3 id="totalExpensesCard">{{ number_format($totalExpenses, 2) }}</h3>
                    <p>Total Expenses</p>
                </div>
                <div class="icon">
                    <i class="ion ion-pie-graph"></i>
                </div>
            </div>
        </div>
        <div class="col-lg-3 col-md-6 col-12">
            <div class="small-box bg-danger">
                <div class="inner">
                    <h3 id="netProfitCard">{{ number_format(($totalProfit + ($totalDirectProfit ?? 0)) - $totalExpenses, 2) }}</h3>
                    <p>Net Profit</p>
                </div>
                <div class="icon">
                    <i class="ion ion-person-add"></i>
                </div>
            </div>
        </div>
    </div>

    <!-- Date Range Filter -->
    <div class="row mb-3">
        <div class="col-md-4">
            <div class="input-group">
                <button type="button" class="btn btn-default" id="daterange-btn">
                    <i class="far fa-calendar-alt"></i> <span>Select Date Range</span>
                    <i class="fas fa-caret-down"></i>
                </button>
            </div>
        </div>
    </div>

    <!-- Data Table -->
    <div class="card">
        <div class="card-header">
            <h3 class="card-title">Detailed Profit Report</h3>
        </div>
        <div class="card-body">
            <table id="profitReportTable" class="table table-striped table-bordered">
                <thead>
                    <tr>
                        <th>Date</th>
                        <th>Total Sales</th>
                        <th>Total Profit</th>
                        <th>Total Direct Sales</th>
                        <th>Total Direct Profit</th>
                        <th>Total Expenses</th>
                        <th>Net Profit</th>
                    </tr>
                </thead>
                <tbody>
                    @php
                        $totalSalesSum = 0;
                        $totalProfitSum = 0;
                        $totalDirectSalesSum = 0;
                        $totalDirectProfitSum = 0;
                        $totalExpensesSum = 0;
                        $netProfitSum = 0;
                    @endphp
                    
                    @if(isset($dailyData))
                        @foreach($dailyData as $date => $data)
                            @php
                                $sales = $data['sales'] ?? 0;
                                $profit = $data['profit'] ?? 0;
                                $directSales = $data['directSales'] ?? 0;
                                $directProfit = $data['directProfit'] ?? 0;
                                $expenses = $data['expenses'] ?? 0;
                                $netProfit = ($profit + $directProfit) - $expenses;
                                
                                $totalSalesSum += $sales;
                                $totalProfitSum += $profit;
                                $totalDirectSalesSum += $directSales;
                                $totalDirectProfitSum += $directProfit;
                                $totalExpensesSum += $expenses;
                                $netProfitSum += $netProfit;
                            @endphp
                            <tr>
                                <td>{{ $date }}</td>
                                <td>{{ number_format($sales, 2) }}</td>
                                <td>{{ number_format($profit, 2) }}</td>
                                <td>{{ number_format($directSales, 2) }}</td>
                                <td>{{ number_format($directProfit, 2) }}</td>
                                <td>{{ number_format($expenses, 2) }}</td>
                                <td>{{ number_format($netProfit, 2) }}</td>
                            </tr>
                        @endforeach
                    @endif
                </tbody>
                <tfoot>
                    <tr style="font-weight: bold; background-color: #f8f9fa;">
                        <th>Total</th>
                        <th>{{ number_format($totalSalesSum, 2) }}</th>
                        <th>{{ number_format($totalProfitSum, 2) }}</th>
                        <th>{{ number_format($totalDirectSalesSum, 2) }}</th>
                        <th>{{ number_format($totalDirectProfitSum, 2) }}</th>
                        <th>{{ number_format($totalExpensesSum, 2) }}</th>
                        <th>{{ number_format($netProfitSum, 2) }}</th>
                    </tr>
                </tfoot>
            </table>
        </div>
    </div>
</div>

@push('styles')
<link rel="stylesheet" href="{{ asset('assets/plugins/daterangepicker/daterangepicker.css') }}">
@endpush

@push('scripts')
<script src="{{ asset('assets/plugins/moment/moment.min.js') }}"></script>
<script src="{{ asset('assets/plugins/daterangepicker/daterangepicker.js') }}"></script>

<script>
$(document).ready(function() {
    // Check if DataTable is already initialized and destroy it
    if ($.fn.DataTable.isDataTable('#profitReportTable')) {
        $('#profitReportTable').DataTable().destroy();
    }
    
    // Initialize DataTable with unique ID
    var table = $('#profitReportTable').DataTable({
        "paging": true,
        "lengthChange": true,
        "searching": true,
        "ordering": true,
        "info": true,
        "autoWidth": false,
        "responsive": true,
        "order": [[0, "desc"]], // Sort by date descending
        "columnDefs": [
            {
                "targets": [1, 2, 3, 4, 5, 6], // Numeric columns
                "className": "text-right"
            }
        ]
    });

    // Initialize Date Range Picker if it exists
    if (typeof moment !== 'undefined' && $('#daterange-btn').length) {
        $('#daterange-btn').daterangepicker({
            ranges: {
                'Today': [moment(), moment()],
                'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                'Last 7 Days': [moment().subtract(6, 'days'), moment()],
                'Last 30 Days': [moment().subtract(29, 'days'), moment()],
                'This Month': [moment().startOf('month'), moment().endOf('month')],
                'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
            },
            startDate: moment().subtract(29, 'days'),
            endDate: moment()
        }, function(start, end) {
            $('#daterange-btn span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
            
            // Clear previous search filters
            $.fn.dataTable.ext.search.length = 0;
            
            // Add new date range filter
            $.fn.dataTable.ext.search.push(
                function(settings, data, dataIndex) {
                    var min = start.format('YYYY-MM-DD');
                    var max = end.format('YYYY-MM-DD');
                    var date = data[0] || ''; // Date column
                    
                    if (
                        (min === null && max === null) ||
                        (min === null && date <= max) ||
                        (min <= date && max === null) ||
                        (min <= date && date <= max)
                    ) {
                        return true;
                    }
                    return false;
                }
            );
            
            table.draw();
            updateSummaryCards();
        });
    }

    // Function to update summary cards based on filtered data
    function updateSummaryCards() {
        var totalSales = 0;
        var totalProfit = 0;
        var totalDirectSales = 0;
        var totalDirectProfit = 0;
        var totalExpenses = 0;
        var netProfit = 0;

        table.rows({ search: 'applied' }).every(function() {
            var data = this.data();
            totalSales += parseFloat(data[1].replace(/,/g, '')) || 0;
            totalProfit += parseFloat(data[2].replace(/,/g, '')) || 0;
            totalDirectSales += parseFloat(data[3].replace(/,/g, '')) || 0;
            totalDirectProfit += parseFloat(data[4].replace(/,/g, '')) || 0;
            totalExpenses += parseFloat(data[5].replace(/,/g, '')) || 0;
            netProfit += parseFloat(data[6].replace(/,/g, '')) || 0;
        });

        // Update cards
        $('#totalSalesCard').text(totalSales.toFixed(2));
        $('#totalProfitCard').text((totalProfit + totalDirectProfit).toFixed(2));
        $('#totalExpensesCard').text(totalExpenses.toFixed(2));
        $('#netProfitCard').text(netProfit.toFixed(2));
    }
});
</script>
@endpush
@endsection