<?php

namespace App\Filament\Widgets;

use App\Models\Order;
use Filament\Widgets\ChartWidget;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;

class OrdersChart extends ChartWidget
{
    protected ?string $heading = 'الطلبات والإيرادات - آخر 30 يوم';

    protected static ?int $sort = 2;

    protected int | string | array $columnSpan = 'full';

    protected function getType(): string
    {
        return 'line';
    }

    protected function getData(): array
    {
        $startDate = Carbon::today()->subDays(29);

        $dailyData = Order::query()
            ->where('created_at', '>=', $startDate->startOfDay())
            ->selectRaw("DATE(created_at) as day, COUNT(*) as orders_count, COALESCE(SUM(CASE WHEN status != 'returned' THEN total ELSE 0 END), 0) as revenue")
            ->groupByRaw('DATE(created_at)')
            ->pluck('revenue', 'day')
            ->toArray();

        $dailyCounts = Order::query()
            ->where('created_at', '>=', $startDate->startOfDay())
            ->selectRaw('DATE(created_at) as day, COUNT(*) as cnt')
            ->groupByRaw('DATE(created_at)')
            ->pluck('cnt', 'day')
            ->toArray();

        $labels = [];
        $ordersData = [];
        $revenueData = [];

        for ($i = 29; $i >= 0; $i--) {
            $day = Carbon::today()->subDays($i)->format('Y-m-d');
            $labels[] = Carbon::today()->subDays($i)->format('m/d');
            $ordersData[] = $dailyCounts[$day] ?? 0;
            $revenueData[] = (float) ($dailyData[$day] ?? 0);
        }

        return [
            'datasets' => [
                [
                    'label' => 'عدد الطلبات',
                    'data' => $ordersData,
                    'borderColor' => '#10b981',
                    'backgroundColor' => 'rgba(16, 185, 129, 0.1)',
                ],
                [
                    'label' => 'الإيرادات (ج.م)',
                    'data' => $revenueData,
                    'borderColor' => '#3b82f6',
                    'backgroundColor' => 'rgba(59, 130, 246, 0.1)',
                ],
            ],
            'labels' => $labels,
        ];
    }
}
