

<?php $__env->startSection('title', 'Dashboard - Harshana Systems'); ?>
<?php $__env->startSection('page-title', 'Dashboard'); ?>

<?php $__env->startSection('content'); ?>
    <?php
        $colorMap = [
            'blue' => '#007bff',
            'green' => '#28a745',
            'red' => '#dc3545',
            'purple' => '#6f42c1',
            'orange' => '#fd7e14',
            'pink' => '#e83e8c',
            'teal' => '#20c997',
            'lime' => '#ffc107',
            'slate' => '#6c757d',
            'cyan' => '#17a2b8'
        ];
            $appColor = optional(\App\Models\SoftwareSetting::first())->app_color ?? 'blue';
        $themeColor = $colorMap[$appColor] ?? $colorMap['blue'];
    ?>
    
    
    <?php if(isset($appExpiry) && $appExpiry['is_expired']): ?>
        <div class="alert alert-danger alert-dismissible fade show mb-4" role="alert">
            <h5 class="alert-heading">
                <i class="fas fa-exclamation-triangle me-2"></i>Application Expired
            </h5>
            <p class="mb-2">
                Your application expired on <strong><?php echo e($appExpiry['expiry_date']->format('F d, Y')); ?></strong> 
                (<?php echo e(abs($appExpiry['days_until_expiry'])); ?> days ago).
            </p>
            <p class="mb-0">
                <i class="fas fa-info-circle me-1"></i>
                Access to Users and other pages is restricted. Please contact administrator to renew the subscription.
            </p>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php elseif(isset($appExpiry) && $appExpiry['show_warning']): ?>
        <div class="alert alert-warning alert-dismissible fade show mb-4" role="alert">
            <h5 class="alert-heading">
                <i class="fas fa-exclamation-circle me-2"></i>Application Expiring Soon
            </h5>
            <p class="mb-0">
                Your application will expire on <strong><?php echo e($appExpiry['expiry_date']->format('F d, Y')); ?></strong> 
                (in <?php echo e($appExpiry['days_until_expiry']); ?> <?php echo e($appExpiry['days_until_expiry'] == 1 ? 'day' : 'days'); ?>).
            </p>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>
    
    <?php if(session('error')): ?>
        <div class="alert alert-danger alert-dismissible fade show mb-4" role="alert">
            <i class="fas fa-exclamation-triangle me-2"></i><?php echo e(session('error')); ?>

            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>
    
    <div class="row">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <div>
                    <h1 class="h3 mb-0 page-title-theme"
                        style="color: var(--primary-color); text-shadow: 1px 1px 2px rgba(0,0,0,0.1);">Dashboard Overview</h1>
                    <?php if($filterType !== 'all' && $filterType !== 'today'): ?>
                        <small class="text-muted">
                            <i class="fas fa-filter me-1"></i>
                            <?php switch($filterType):
                                case ('year'): ?>
                                    Filtered by Year: <?php echo e($year); ?>

                                    <?php break; ?>
                                <?php case ('month'): ?>
                                    Filtered by Month: <?php echo e(date('F', mktime(0, 0, 0, $month, 1))); ?> <?php echo e($yearMonth); ?>

                                    <?php break; ?>
                                <?php case ('date_range'): ?>
                                    Filtered by Date Range: <?php echo e($startDate ?: 'Start'); ?> to <?php echo e($endDate ?: 'End'); ?>

                                    <?php break; ?>
                            <?php endswitch; ?>
                        </small>
                    <?php endif; ?>
                </div>
                <small class="text-muted">Welcome back, <?php echo e(auth()->user()->name); ?>!</small>
            </div>
        </div>
    </div>

    <!-- Date Filter Section -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h6 class="m-0 font-weight-bold text-primary">
                        <i class="fas fa-filter me-2"></i>
                        Filter Data by Date Range
                    </h6>
                    <button class="btn btn-sm btn-outline-primary" type="button" data-bs-toggle="collapse" data-bs-target="#filterCollapse" aria-expanded="true" aria-controls="filterCollapse">
                        <i class="fas fa-chevron-down"></i>
                    </button>
                </div>
                <div class="collapse show" id="filterCollapse">
                    <div class="card-body">
                    <form method="GET" action="<?php echo e(route('dashboard')); ?>" class="row g-3">
                        <div class="col-md-3">
                            <label for="filter_type" class="form-label">Filter Type</label>
                            <select name="filter_type" id="filter_type" class="form-select" onchange="toggleDateInputs()">
                                <option value="today" <?php echo e($filterType == 'today' ? 'selected' : ''); ?>>Today</option>
                                <option value="all" <?php echo e($filterType == 'all' ? 'selected' : ''); ?>>All Time</option>
                                <option value="year" <?php echo e($filterType == 'year' ? 'selected' : ''); ?>>By Year</option>
                                <option value="month" <?php echo e($filterType == 'month' ? 'selected' : ''); ?>>By Month</option>
                                <option value="date_range" <?php echo e($filterType == 'date_range' ? 'selected' : ''); ?>>Date Range</option>
                            </select>
                        </div>

                        <div class="col-md-2" id="year_input" style="display: <?php echo e($filterType == 'year' ? 'block' : 'none'); ?>;">
                            <label for="year" class="form-label">Year</label>
                            <select name="year" id="year" class="form-select">
                                <?php for($y = date('Y'); $y >= date('Y') - 5; $y--): ?>
                                    <option value="<?php echo e($y); ?>" <?php echo e($year == $y ? 'selected' : ''); ?>><?php echo e($y); ?></option>
                                <?php endfor; ?>
                            </select>
                        </div>

                        <div class="col-md-2" id="month_input" style="display: <?php echo e($filterType == 'month' ? 'block' : 'none'); ?>;">
                            <label for="month" class="form-label">Month</label>
                            <select name="month" id="month" class="form-select">
                                <?php for($m = 1; $m <= 12; $m++): ?>
                                    <option value="<?php echo e($m); ?>" <?php echo e($month == $m ? 'selected' : ''); ?>><?php echo e(date('F', mktime(0, 0, 0, $m, 1))); ?></option>
                                <?php endfor; ?>
                            </select>
                        </div>

                        <div class="col-md-2" id="year_month_input" style="display: <?php echo e($filterType == 'month' ? 'block' : 'none'); ?>;">
                            <label for="year_month" class="form-label">Year</label>
                            <select name="year_month" id="year_month" class="form-select">
                                <?php for($y = date('Y'); $y >= date('Y') - 5; $y--): ?>
                                    <option value="<?php echo e($y); ?>" <?php echo e($yearMonth == $y ? 'selected' : ''); ?>><?php echo e($y); ?></option>
                                <?php endfor; ?>
                            </select>
                        </div>

                        <div class="col-md-2" id="start_date_input" style="display: <?php echo e($filterType == 'date_range' ? 'block' : 'none'); ?>;">
                            <label for="start_date" class="form-label">Start Date</label>
                            <input type="date" name="start_date" id="start_date" class="form-control" value="<?php echo e($startDate); ?>">
                        </div>

                        <div class="col-md-2" id="end_date_input" style="display: <?php echo e($filterType == 'date_range' ? 'block' : 'none'); ?>;">
                            <label for="end_date" class="form-label">End Date</label>
                            <input type="date" name="end_date" id="end_date" class="form-control" value="<?php echo e($endDate); ?>">
                        </div>

                        <div class="col-md-2 d-flex align-items-end">
                            <button type="submit" class="btn btn-primary me-2">
                                <i class="fas fa-search me-1"></i>Filter
                            </button>
                            <a href="<?php echo e(route('dashboard')); ?>" class="btn btn-secondary">
                                <i class="fas fa-times me-1"></i>Clear
                            </a>
                        </div>
                    </form>
                </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Statistics Cards -->
    <div class="row mb-4">
    <!-- Total Revenue -->
    <div class="col-xl-3 col-lg-3 col-md-3 col-sm-6 mb-4">
            <div class="card border-start border-success border-4 h-100">
                <div class="card-body">
                    <div class="row align-items-center">
                        <div class="col">
                            <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                                Total Revenue
                            </div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">
                                Rs. <?php echo e(number_format($totalRevenue, 2)); ?>

                            </div>
                            <div class="text-xs text-muted">
                                Rs. <?php echo e(number_format($todayRevenue, 2)); ?> today
                            </div>
                            <?php if(!empty($branchRevenueValues)): ?>
                                <hr class="my-2" style="opacity: 0.3;">
                                <div class="text-xs font-weight-bold text-success mb-1">Branch-wise:</div>
                                <?php $__currentLoopData = $branchRevenueValues; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $branchName => $value): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                    <div class="text-xs d-flex justify-content-between">
                                        <span class="text-muted"><?php echo e($branchName); ?>:</span>
                                        <span class="font-weight-bold">Rs. <?php echo e(number_format($value, 2)); ?></span>
                                    </div>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                            <?php endif; ?>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-dollar-sign fa-2x text-success"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

    <!-- Total Profit -->
    <div class="col-xl-3 col-lg-3 col-md-3 col-sm-6 mb-4">
            <div class="card border-start border-info border-4 h-100">
                <div class="card-body">
                    <div class="row align-items-center">
                        <div class="col">
                            <div class="text-xs font-weight-bold text-info text-uppercase mb-1">
                                Total Profit
                            </div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">
                                Rs. <?php echo e(number_format($totalProfit, 2)); ?>

                            </div>
                            <div class="text-xs text-muted">
                                Rs. <?php echo e(number_format($todayProfit, 2)); ?> today
                            </div>
                            <?php if(!empty($branchProfitValues)): ?>
                                <hr class="my-2" style="opacity: 0.3;">
                                <div class="text-xs font-weight-bold text-info mb-1">Branch-wise:</div>
                                <?php $__currentLoopData = $branchProfitValues; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $branchName => $value): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                    <div class="text-xs d-flex justify-content-between">
                                        <span class="text-muted"><?php echo e($branchName); ?>:</span>
                                        <span class="font-weight-bold">Rs. <?php echo e(number_format($value, 2)); ?></span>
                                    </div>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                            <?php endif; ?>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-chart-line fa-2x text-info"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

    <!-- Total Invoices -->
    <div class="col-xl-3 col-lg-3 col-md-3 col-sm-6 mb-4">
            <div class="card border-start border-primary border-4 h-100">
                <div class="card-body">
                    <div class="row align-items-center">
                        <div class="col">
                            <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">
                                Total Invoices
                            </div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">
                                <?php echo e(number_format($totalInvoices)); ?>

                            </div>
                            <div class="text-xs text-muted">
                                <?php echo e($todayInvoices); ?> today, <?php echo e($thisMonthInvoices); ?> this month
                            </div>
                            <?php if(!empty($branchInvoiceCounts)): ?>
                                <hr class="my-2" style="opacity: 0.3;">
                                <div class="text-xs font-weight-bold text-primary mb-1">Branch-wise:</div>
                                <?php $__currentLoopData = $branchInvoiceCounts; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $branchName => $count): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                    <div class="text-xs d-flex justify-content-between">
                                        <span class="text-muted"><?php echo e($branchName); ?>:</span>
                                        <span class="font-weight-bold"><?php echo e(number_format($count)); ?></span>
                                    </div>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                            <?php endif; ?>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-file-invoice fa-2x text-primary"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        

    <!-- Total Stock Value -->
    <div class="col-xl-3 col-lg-3 col-md-3 col-sm-6 mb-4">
            <div class="card border-start border-secondary border-4 h-100">
                <div class="card-body">
                    <div class="row align-items-center">
                        <div class="col">
                            <div class="text-xs font-weight-bold text-secondary text-uppercase mb-1">
                                Total Stock Value
                            </div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">
                                Rs. <?php echo e(number_format($totalStockValue, 2)); ?>

                            </div>
                            <div class="text-xs text-muted">
                                Current inventory value
                            </div>
                            
                            <?php if(!empty($branchStockValues)): ?>
                                <hr class="my-2" style="opacity: 0.3;">
                                <div class="text-xs font-weight-bold text-secondary mb-1">Branch-wise:</div>
                                <?php $__currentLoopData = $branchStockValues; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $branchName => $value): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                    <div class="text-xs d-flex justify-content-between">
                                        <span class="text-muted"><?php echo e($branchName); ?>:</span>
                                        <span class="font-weight-bold">Rs. <?php echo e(number_format($value, 2)); ?></span>
                                    </div>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                            <?php endif; ?>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-warehouse fa-2x text-secondary"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="row mb-4">
         <!-- SMS Balance -->
            <div class="col-xl-2 col-lg-3 col-md-6 mb-4">
                <div class="card border-start border-success border-4 h-100">
                    <div class="card-body">
                        <div class="row align-items-center">
                            <div class="col">
                                <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                                    SMS Credits
                                </div>
                                <div class="h5 mb-0 font-weight-bold text-gray-800" id="sms-balance-value">
                                    <i class="fas fa-spinner fa-spin text-muted"></i>
                                </div>
                                <div class="text-xs text-muted" id="sms-balance-message">
                                    Loading...
                                </div>
                            </div>
                            <div class="col-auto">
                                <i class="fas fa-sms fa-2x text-success"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Total Customers -->
            <div class="col-xl-2 col-lg-3 col-md-6 mb-4">
                <div class="card border-start border-warning border-4 h-100">
                    <div class="card-body">
                        <div class="row align-items-center">
                            <div class="col">
                                <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">
                                    Total Customers
                                </div>
                                <div class="h5 mb-0 font-weight-bold text-gray-800">
                                    <?php echo e(number_format($totalCustomers)); ?>

                                </div>
                                <div class="text-xs text-muted">
                                    <?php echo e($activeCustomers); ?> active this month
                                </div>
                            </div>
                            <div class="col-auto">
                                <i class="fas fa-users fa-2x text-warning"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

    <!-- Second Row Statistics -->
    

    
    

    <!-- Charts Section -->
    <div class="row mb-4">
        <!-- Monthly Sales Chart -->
        <div class="col-xl-8 col-lg-7 mb-4">
            <div class="card">
                <div class="card-header">
                    <h6 class="m-0 font-weight-bold text-primary">
                        <i class="fas fa-chart-bar me-2"></i>
                        Monthly Sales & Profit (Last 12 Months)
                    </h6>
                </div>
                <div class="card-body">
                    <canvas id="monthlySalesChart" width="100%" height="300"></canvas>
                </div>
            </div>
        </div>

        <!-- Payment Methods Chart -->
        <div class="col-xl-4 col-lg-5 mb-4">
            <div class="card">
                <div class="card-header">
                    <h6 class="m-0 font-weight-bold text-primary">
                        <i class="fas fa-credit-card me-2"></i>
                        Payment Methods
                    </h6>
                </div>
                <div class="card-body">
                    <canvas id="paymentMethodsChart" width="100%" height="300"></canvas>
                </div>
            </div>
        </div>
    </div>

    <!-- Second Row Charts -->
    <div class="row mb-4">
        <!-- Daily Sales Chart -->
        <div class="col-xl-8 col-lg-7 mb-4">
            <div class="card">
                <div class="card-header">
                    <h6 class="m-0 font-weight-bold text-primary">
                        <i class="fas fa-calendar-day me-2"></i>
                        Daily Sales (Last 30 Days)
                    </h6>
                </div>
                <div class="card-body">
                    <canvas id="dailySalesChart" width="100%" height="300"></canvas>
                </div>
            </div>
        </div>

        <!-- Top Customers Chart -->
        <div class="col-xl-4 col-lg-5 mb-4">
            <div class="card">
                <div class="card-header">
                    <h6 class="m-0 font-weight-bold text-primary">
                        <i class="fas fa-star me-2"></i>
                        Top 10 Customers by Revenue
                    </h6>
                </div>
                <div class="card-body">
                    <canvas id="topCustomersChart" width="100%" height="300"></canvas>
                </div>
            </div>
        </div>
    </div>

    <!-- Recent Activity -->
    <div class="row mt-4">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h6 class="m-0 font-weight-bold text-primary">
                        <i class="fas fa-history me-2"></i>
                        Recent Activity
                    </h6>
                </div>
                <div class="card-body">
                    <div class="timeline">
                        <?php $__currentLoopData = $recentActivities; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $activity): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <div class="timeline-item">
                                <div class="timeline-marker bg-<?php echo e($activity['color']); ?>"></div>
                                <div class="timeline-content">
                                    <h6 class="timeline-title"><?php echo e($activity['title']); ?></h6>
                                    <p class="timeline-text"><?php echo e($activity['description']); ?></p>
                                    <small class="text-muted"><?php echo e($activity['time']->format('M d, Y H:i')); ?></small>
                                </div>
                            </div>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
<?php $__env->stopSection(); ?>

<?php $__env->startPush('styles'); ?>
    <style>
        .timeline {
            position: relative;
            padding-left: 20px;
        }

        .timeline-item {
            position: relative;
            padding-bottom: 1.5rem;
        }

        .timeline-item:not(:last-child)::before {
            content: '';
            position: absolute;
            left: -12px;
            top: 20px;
            height: calc(100% - 10px);
            width: 2px;
            background-color: var(--gray-200);
        }

        .timeline-marker {
            position: absolute;
            left: -16px;
            top: 4px;
            width: 8px;
            height: 8px;
            border-radius: 50%;
        }

        .timeline-content {
            padding-left: 1rem;
        }

        .timeline-title {
            font-size: 1rem;
            font-weight: 600;
            margin-bottom: 0.25rem;
        }

        .timeline-text {
            margin-bottom: 0.5rem;
            color: var(--gray-600);
        }

        .border-4 {
            border-width: 4px !important;
        }

        .chart-area {
            position: relative;
            height: 320px;
            width: 100%;
        }
    </style>
<?php $__env->stopPush(); ?>

<?php $__env->startPush('scripts'); ?>
    <script>
        // Fetch SMS balance asynchronously after page load
        document.addEventListener('DOMContentLoaded', function() {
            fetchSmsBalance();
        });

        function fetchSmsBalance() {
            const balanceValue = document.getElementById('sms-balance-value');
            const balanceMessage = document.getElementById('sms-balance-message');

            fetch('/dashboard/sms-balance', {
                method: 'GET',
                headers: {
                    'Accept': 'application/json',
                    'X-Requested-With': 'XMLHttpRequest'
                }
            })
            .then(response => response.json())
            .then(data => {
                // Update balance display
                if (data.success && data.balance !== null) {
                    // Show actual balance as-is without formatting
                    balanceValue.textContent = data.balance;
                } else {
                    balanceValue.innerHTML = '<span class="text-muted">N/A</span>';
                }

                // Update message
                balanceMessage.textContent = data.message || 'Unknown status';
            })
            .catch(error => {
                console.error('SMS balance fetch error:', error);
                balanceValue.innerHTML = '<span class="text-muted">Error</span>';
                balanceMessage.textContent = 'Failed to load';
            });
        }

        // Filter form JavaScript
        function toggleDateInputs() {
            const filterType = document.getElementById('filter_type').value;
            const yearInput = document.getElementById('year_input');
            const monthInput = document.getElementById('month_input');
            const yearMonthInput = document.getElementById('year_month_input');
            const startDateInput = document.getElementById('start_date_input');
            const endDateInput = document.getElementById('end_date_input');

            // Hide all inputs first
            yearInput.style.display = 'none';
            monthInput.style.display = 'none';
            yearMonthInput.style.display = 'none';
            startDateInput.style.display = 'none';
            endDateInput.style.display = 'none';

            // Show relevant inputs based on filter type
            switch(filterType) {
                case 'year':
                    yearInput.style.display = 'block';
                    break;
                case 'month':
                    monthInput.style.display = 'block';
                    yearMonthInput.style.display = 'block';
                    break;
                case 'date_range':
                    startDateInput.style.display = 'block';
                    endDateInput.style.display = 'block';
                    break;
            }
        }

        // Initialize on page load
        document.addEventListener('DOMContentLoaded', function() {
            toggleDateInputs();
        });

        // Wait for Chart.js to load
        document.addEventListener('chartjsLoaded', function() {
            // Set default Chart.js options
            Chart.defaults.font.family = "'Nunito', sans-serif";
            Chart.defaults.color = '#858796';

            // Monthly Sales Chart
            const monthlySalesCtx = document.getElementById('monthlySalesChart');
            if (monthlySalesCtx) {
                const monthlyData = <?php echo json_encode($monthlySales); ?>;
                new Chart(monthlySalesCtx, {
                    type: 'line',
                    data: {
                        labels: monthlyData.map(item => item.month),
                        datasets: [{
                            label: 'Revenue (Rs.)',
                            data: monthlyData.map(item => item.revenue),
                            borderColor: '#4e73df',
                            backgroundColor: 'rgba(78, 115, 223, 0.1)',
                            tension: 0.4,
                            fill: true
                        }, {
                            label: 'Profit (Rs.)',
                            data: monthlyData.map(item => item.profit),
                            borderColor: '#1cc88a',
                            backgroundColor: 'rgba(28, 200, 138, 0.1)',
                            tension: 0.4,
                            fill: true
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                display: true,
                                position: 'top'
                            },
                            tooltip: {
                                callbacks: {
                                    label: function(context) {
                                        return context.dataset.label + ': Rs. ' + context.parsed.y.toLocaleString();
                                    }
                                }
                            }
                        },
                        scales: {
                            y: {
                                beginAtZero: true,
                                ticks: {
                                    callback: function(value) {
                                        return 'Rs. ' + value.toLocaleString();
                                    }
                                }
                            }
                        }
                    }
                });
            }

            // Payment Methods Chart
            const paymentMethodsCtx = document.getElementById('paymentMethodsChart');
            if (paymentMethodsCtx) {
                const paymentData = <?php echo json_encode($paymentMethods); ?>;
                new Chart(paymentMethodsCtx, {
                    type: 'doughnut',
                    data: {
                        labels: paymentData.map(item => item.method + ' (' + item.percentage + '%)'),
                        datasets: [{
                            data: paymentData.map(item => item.amount),
                            backgroundColor: ['#4e73df', '#1cc88a', '#36b9cc', '#f6c23e'],
                            hoverBackgroundColor: ['#2e59d9', '#17a673', '#2c9faf', '#f4b619'],
                            hoverBorderColor: "rgba(234, 236, 244, 1)",
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                display: true,
                                position: 'bottom'
                            },
                            tooltip: {
                                callbacks: {
                                    label: function(context) {
                                        return context.label + ': Rs. ' + context.parsed.toLocaleString();
                                    }
                                }
                            }
                        }
                    }
                });
            }

            // Daily Sales Chart
            const dailySalesCtx = document.getElementById('dailySalesChart');
            if (dailySalesCtx) {
                const dailyData = <?php echo json_encode($dailySales); ?>;
                new Chart(dailySalesCtx, {
                    type: 'bar',
                    data: {
                        labels: dailyData.map(item => item.date),
                        datasets: [{
                            label: 'Daily Revenue (Rs.)',
                            data: dailyData.map(item => item.revenue),
                            backgroundColor: '#4e73df',
                            borderColor: '#4e73df',
                            borderWidth: 1
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                display: false
                            },
                            tooltip: {
                                callbacks: {
                                    label: function(context) {
                                        return 'Revenue: Rs. ' + context.parsed.y.toLocaleString();
                                    }
                                }
                            }
                        },
                        scales: {
                            y: {
                                beginAtZero: true,
                                ticks: {
                                    callback: function(value) {
                                        return 'Rs. ' + value.toLocaleString();
                                    }
                                }
                            }
                        }
                    }
                });
            }

            // Top Customers Chart
            const topCustomersCtx = document.getElementById('topCustomersChart');
            if (topCustomersCtx) {
                const customerData = <?php echo json_encode($topCustomers); ?>;
                new Chart(topCustomersCtx, {
                    type: 'bar',
                    data: {
                        labels: customerData.map(item => item.name.length > 15 ? item.name.substring(0, 15) + '...' : item.name),
                        datasets: [{
                            label: 'Revenue (Rs.)',
                            data: customerData.map(item => item.total_revenue),
                            backgroundColor: '#1cc88a',
                            borderColor: '#1cc88a',
                            borderWidth: 1
                        }]
                    },
                    options: {
                        indexAxis: 'y',
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                display: false
                            },
                            tooltip: {
                                callbacks: {
                                    label: function(context) {
                                        return 'Revenue: Rs. ' + context.parsed.y.toLocaleString();
                                    }
                                }
                            }
                        },
                        scales: {
                            x: {
                                beginAtZero: true,
                                ticks: {
                                    callback: function(value) {
                                        return 'Rs. ' + value.toLocaleString();
                                    }
                                }
                            }
                        }
                    }
                });
            }
        });

        function toggleDateInputs() {
            const filterType = document.getElementById('filter_type').value;
            const yearInput = document.getElementById('year_input');
            const monthInput = document.getElementById('month_input');
            const yearMonthInput = document.getElementById('year_month_input');
            const startDateInput = document.getElementById('start_date_input');
            const endDateInput = document.getElementById('end_date_input');

            // Hide all inputs first
            yearInput.style.display = 'none';
            monthInput.style.display = 'none';
            yearMonthInput.style.display = 'none';
            startDateInput.style.display = 'none';
            endDateInput.style.display = 'none';

            // Show relevant inputs based on filter type
            switch(filterType) {
                case 'year':
                    yearInput.style.display = 'block';
                    break;
                case 'month':
                    monthInput.style.display = 'block';
                    yearMonthInput.style.display = 'block';
                    break;
                case 'date_range':
                    startDateInput.style.display = 'block';
                    endDateInput.style.display = 'block';
                    break;
            }
        }

        function refreshDashboard() {
            const btn = event.target;
            const originalContent = btn.innerHTML;

            btn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Refreshing...';
            btn.disabled = true;

            setTimeout(() => {
                btn.innerHTML = originalContent;
                btn.disabled = false;

                // Show success message
                const alert = document.createElement('div');
                alert.className = 'alert alert-success alert-dismissible fade show';
                alert.innerHTML = `
                    <i class="fas fa-check-circle me-2"></i>
                    Dashboard refreshed successfully!
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                `;

                document.querySelector('.content').insertBefore(alert, document.querySelector('.content').firstChild);

                // Auto dismiss
                setTimeout(() => {
                    bootstrap.Alert.getOrCreateInstance(alert).close();
                }, 3000);
            }, 2000);
        }
    </script>
<?php $__env->stopPush(); ?>
<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH D:\ONLINE SYSTEMS ORIGINALS\demo perera\test 06-05-2026\resources\views/financial/dashboard.blade.php ENDPATH**/ ?>