@extends('layouts.app')

@section('main')
    <!-- Content Header (Page header) -->
    <div class="content-header">
        <div class="container-fluid">
            <div class="row mb-2">
                <div class="col-sm-6">
                    <h1 class="m-0">Dashboard</h1>
                </div><!-- /.col -->
                <div class="col-sm-6">
                    <ol class="breadcrumb float-sm-right">
                        <li class="breadcrumb-item"><a href="#">Home</a></li>
                        <li class="breadcrumb-item active">Dashboard v1</li>
                    </ol>
                </div><!-- /.col -->
            </div><!-- /.row -->
        </div><!-- /.container-fluid -->
    </div>
    <!-- /.content-header -->

    <!-- Main content -->
    <section class="content">
        <div class="container-fluid">
            <!-- Stats Boxes -->
            <div class="row">
                <div class="col-lg-3 col-6">
                    <!-- small box -->
                    <div class="small-box bg-gradient-primary">
                        <div class="inner">
                            <h3 id="completeSale">{{ $all_settings->currency ?? '$' }}{{ number_format($completeSale ?? 0, 2) }}</h3> <!-- Complete Sale as h3 -->
                            <p>Complete Sale</p>
                        </div>
                        <div class="icon">
                            <i class="ion ion-bag"></i>
                        </div>
                        <a href="#" class="small-box-footer">More info <i class="fas fa-arrow-circle-right"></i></a>
                    </div>
                </div>
                <div class="col-lg-3 col-6">
                    <div class="small-box bg-gradient-success">
                        <div class="inner">
                            <h3 id="completeProfit">{{ $all_settings->currency ?? '$' }}{{ number_format($completeProfit ?? 0, 2) }}</h3> <!-- Complete Profit as h3 -->
                            <p>Complete Profit</p>
                        </div>
                        <div class="icon">
                            <i class="ion ion-stats-bars"></i>
                        </div>
                        <a href="#" class="small-box-footer">More info <i class="fas fa-arrow-circle-right"></i></a>
                    </div>
                </div>
                <div class="col-lg-3 col-6">
                    <div class="small-box bg-gradient-warning">
                        <div class="inner">
                            <h3 id="dueAmount">
                                <strong>{{ $all_settings->currency ?? '$' }}{{ number_format($todayDueAmount ?? 0, 2) }}</strong>
                            </h3>
                            <p>Due Credit Amount</p>
                        </div>
                        <div class="icon">
                            <i class="ion ion-person-add"></i>
                        </div>
                        <a href="#" class="small-box-footer">More info <i class="fas fa-arrow-circle-right"></i></a>
                    </div>
                </div>
                <div class="col-lg-3 col-6">
                    <div class="small-box bg-gradient-info">
                        <div class="inner">
                            <h3 id="todayExpense">
                                <strong>{{ $all_settings->currency ?? 'BDT' }} {{ number_format($todayExpenses, 2) }}</strong>
                            </h3>
                            <p>Today Expense</p>
                        </div>
                        <div class="icon">
                            <i class="fas fa-money-bill-wave"></i>
                        </div>
                        <a href="{{ route('expenses.index') }}" class="small-box-footer">More info <i class="fas fa-arrow-circle-right"></i></a>
                    </div>
                </div>
            </div>
            <!DOCTYPE html>
            <html lang="en">

            <head>
                <meta charset="UTF-8">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <title>Sales & Profit Report</title>
                <style>
                    .data-section {
                        display: flex;
                        justify-content: space-between;
                        margin-bottom: 20px;
                    }

                    .data-card {
                        width: 45%;
                        padding: 15px;
                        background-color: #f1f1f1;
                        border-radius: 8px;
                        text-align: center;
                    }

                    .chart-container {
                        position: relative;
                        height: 400px;
                    }

                    .filter-section {
                        display: flex;
                        justify-content: space-between;
                        margin-bottom: 20px;
                    }

                    .filter-section select,
                    .filter-section input {
                        padding: 10px;
                        border-radius: 5px;
                        border: 1px solid #ccc;
                        margin-right: 10px;
                    }
                </style>
            </head>

            <body>
                <div class="row">
                    <div class="col-12">
                        <h2 class="text-center mb-4">Sales & Profit Report</h2>

                        <!-- Filter Section -->
                        <div class="filter-section">
                            <select id="dateFilter">
                                <option value="today">Today</option>
                                <option value="yesterday">Yesterday</option>
                                <option value="last7days">Last 7 Days</option>
                                <option value="last30days">Last 30 Days</option>
                                <option value="custom">Custom Range</option>
                            </select>
                            <input type="date" id="startDate" style="display:none;">
                            <input type="date" id="endDate" style="display:none;">
                        </div>
                        <!-- Chart for the sales and profit -->
                        <div class="chart-container">
                            <canvas id="profitChart"></canvas>
                        </div>
                    </div>
                </div>

                <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
                <script>
                    var salesData = @json($salesData) || []; // Get the sales data dynamically
                    var currencySymbol = @json($all_settings->currency) || '$'; // Get the currency symbol from Blade to JavaScript
                    var completeSale = @json($completeSale ?? 0); // Get complete sale from backend
                    var completeProfit = @json($completeProfit ?? 0); // Get complete profit from backend
                    var todayExpenses = @json($todayExpenses); // Get today's expenses from backend

                    function formatCurrency(value) {
                        return currencySymbol + ' ' + value.toFixed(2); // Format currency with two decimal points
                    }

                    function getFilteredData(startDate, endDate) {
                        return salesData.filter(item => {
                            const date = new Date(item.date);
                            return date >= startDate && date <= endDate;
                        });
                    }

                    function updateData(filteredData, startDate, endDate) {
                        let completeSaleFiltered = 0;
                        let completeProfitFiltered = 0;
                        let totalDueAmount = 0;
                        let totalExpenseAmount = 0;

                        // If no filter is applied (all data), use backend totals
                        if (filteredData.length === salesData.length) {
                            completeSaleFiltered = completeSale;
                            completeProfitFiltered = completeProfit;
                            // Always show today's expenses for default view
                            totalExpenseAmount = todayExpenses;
                        } else {
                            // Calculate filtered totals
                            filteredData.forEach(data => {
                                const totalSales = parseFloat(data.total_sales) || 0;
                                const totalDirectSales = parseFloat(data.total_direct_sales) || 0;
                                completeSaleFiltered += totalSales + totalDirectSales;

                                const totalProfit = parseFloat(data.total_profit) || 0;
                                const totalDirectProfit = parseFloat(data.total_direct_profit) || 0;
                                completeProfitFiltered += totalProfit + totalDirectProfit;
                                
                                // Add due amount if available
                                const dueAmount = parseFloat(data.total_due_amount) || 0;
                                totalDueAmount += dueAmount;
                                
                                // Add expense amount if available
                                const expenseAmount = parseFloat(data.total_expense_amount) || 0;
                                totalExpenseAmount += expenseAmount;
                            });
                        }

                        document.getElementById('completeSale').textContent = formatCurrency(completeSaleFiltered);
                        document.getElementById('completeProfit').textContent = formatCurrency(completeProfitFiltered);
                        
                        // Don't update todayExpense via JavaScript - let it keep the server-rendered value
                        // document.getElementById('todayExpense').innerHTML = '<strong>' + formatCurrency(totalExpenseAmount) + '</strong>';
                        
                        // Only update due amount if we have filtered data with due amounts
                        if (totalDueAmount > 0) {
                            document.getElementById('dueAmount').innerHTML = '<strong>' + formatCurrency(totalDueAmount) + '</strong>';
                        }

                        const labels = filteredData.map(item => item.date);
                        const totalSales = filteredData.map(item => item.total_sales);
                        const totalProfit = filteredData.map(item => item.total_profit);
                        const totalDirectSales = filteredData.map(item => item.total_direct_sales);
                        const totalDirectProfit = filteredData.map(item => item.total_direct_profit);

                        myChart.data.labels = labels;
                        myChart.data.datasets[0].data = totalSales;
                        myChart.data.datasets[1].data = totalProfit;
                        myChart.data.datasets[2].data = totalDirectSales;
                        myChart.data.datasets[3].data = totalDirectProfit;
                        myChart.update();
                    }

                    function applyFilter() {
                        const filterValue = document.getElementById('dateFilter').value;
                        let startDate, endDate;

                        if (filterValue === 'today') {
                            const today = new Date();
                            startDate = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 0, 0, 0, 0);
                            endDate = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 23, 59, 59, 999);
                        } else if (filterValue === 'yesterday') {
                            const today = new Date();
                            const yesterday = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 1);
                            startDate = new Date(yesterday.getFullYear(), yesterday.getMonth(), yesterday.getDate(), 0, 0, 0, 0);
                            endDate = new Date(yesterday.getFullYear(), yesterday.getMonth(), yesterday.getDate(), 23, 59, 59, 999);
                        } else if (filterValue === 'last7days') {
                            const today = new Date();
                            startDate = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 7, 0, 0, 0, 0);
                            endDate = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 23, 59, 59, 999);
                        } else if (filterValue === 'last30days') {
                            const today = new Date();
                            startDate = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 30, 0, 0, 0, 0);
                            endDate = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 23, 59, 59, 999);
                        } else if (filterValue === 'custom') {
                            startDate = new Date(document.getElementById('startDate').value);
                            endDate = new Date(document.getElementById('endDate').value);
                            startDate.setHours(0, 0, 0, 0);
                            endDate.setHours(23, 59, 59, 999);
                        }

                        const filteredData = getFilteredData(startDate, endDate);
                        updateData(filteredData, startDate, endDate);
                    }

                    document.getElementById('dateFilter').addEventListener('change', function() {
                        const filterValue = this.value;
                        if (filterValue === 'custom') {
                            document.getElementById('startDate').style.display = 'inline-block';
                            document.getElementById('endDate').style.display = 'inline-block';
                        } else {
                            document.getElementById('startDate').style.display = 'none';
                            document.getElementById('endDate').style.display = 'none';
                            applyFilter();
                        }
                    });

                    document.getElementById('startDate').addEventListener('change', applyFilter);
                    document.getElementById('endDate').addEventListener('change', applyFilter);

                    // Initial chart setup
                    var ctx = document.getElementById('profitChart').getContext('2d');
                    var myChart = new Chart(ctx, {
                        type: 'bar',
                        data: {
                            labels: [],
                            datasets: [{
                                    label: 'Total Sales',
                                    data: [],
                                    backgroundColor: 'rgba(54, 162, 235, 0.5)',
                                    borderColor: 'rgba(54, 162, 235, 1)',
                                    borderWidth: 1,
                                    tooltip: {
                                        callbacks: {
                                            label: function(tooltipItem) {
                                                return currencySymbol + tooltipItem.raw.toLocaleString();
                                            }
                                        }
                                    }
                                },
                                {
                                    label: 'Total Profit',
                                    data: [],
                                    backgroundColor: 'rgba(75, 192, 192, 0.5)',
                                    borderColor: 'rgba(75, 192, 192, 1)',
                                    borderWidth: 1,
                                    tooltip: {
                                        callbacks: {
                                            label: function(tooltipItem) {
                                                return currencySymbol + tooltipItem.raw.toLocaleString();
                                            }
                                        }
                                    }
                                },
                                {
                                    label: 'Direct Sales',
                                    data: [],
                                    backgroundColor: 'rgba(255, 99, 132, 0.5)',
                                    borderColor: 'rgba(255, 99, 132, 1)',
                                    borderWidth: 1,
                                    tooltip: {
                                        callbacks: {
                                            label: function(tooltipItem) {
                                                return currencySymbol + tooltipItem.raw.toLocaleString();
                                            }
                                        }
                                    }
                                },
                                {
                                    label: 'Direct Profit',
                                    data: [],
                                    backgroundColor: 'rgba(255, 206, 86, 0.5)',
                                    borderColor: 'rgba(255, 206, 86, 1)',
                                    borderWidth: 1,
                                    tooltip: {
                                        callbacks: {
                                            label: function(tooltipItem) {
                                                return currencySymbol + tooltipItem.raw.toLocaleString();
                                            }
                                        }
                                    }
                                }
                            ]
                        },
                        options: {
                            responsive: true,
                            maintainAspectRatio: false,
                            scales: {
                                y: {
                                    beginAtZero: true,
                                    title: {
                                        display: true,
                                        text: 'Amount (' + currencySymbol + ')', // Add currency symbol to y-axis title
                                        color: '#666',
                                        font: {
                                            size: 14
                                        }
                                    },
                                    ticks: {
                                        callback: function(value) {
                                            return currencySymbol + value
                                                .toLocaleString(); // Format y-axis ticks with currency symbol
                                        }
                                    }
                                },
                                x: {
                                    title: {
                                        display: true,
                                        text: 'Date',
                                        color: '#666',
                                        font: {
                                            size: 14
                                        }
                                    }
                                }
                            },
                            plugins: {
                                legend: {
                                    position: 'top',
                                    labels: {
                                        font: {
                                            size: 14
                                        }
                                    }
                                }
                            }
                        }
                    });

                    // Apply default filter (Today) on page load
                    applyFilter();
                </script>
            @endsection
