<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\DailyStatistic;
use App\Models\WaitingQueue;
use Carbon\Carbon;
use App\Models\Customer;
use App\Models\AppointmentSetting;

class StatisticsController extends Controller
{
    public function __construct()
    {
        $this->middleware("auth");
    }

    public function index_stat()
{
    $stats = [
        [
            'icon' => 'fa-users',
            'title' => __('statistics.customers'),
            'description' => __('statistics.customers_desc'),
            'route' => route('statistics.customers'),
            'color' => 'primary'
        ],
        [
            'icon' => 'fa-calendar-alt',
            'title' => __('lang.appointments'),
            'description' => __('statistics.appointments_desc'),
            'route' => route('statistics.appointments'),
            'color' => 'success'
        ],
        [
            'icon' => 'fa-user-clock',
            'title' => __('lang.queue'),
            'description' => __('statistics.queue_desc'),
            'route' => route('statistics.advanced'),
            'color' => 'info'
        ],
        [
            'icon' => 'fa-chart-bar',
            'title' => __('statistics.advanced_reports'),
            'description' => __('statistics.advanced_reports_desc'),
            'route' => route('statistics.advanced'),
            'color' => 'warning'
        ],
        [
            'icon' => 'fa-money-bill-wave',
            'title' => __('statistics.revenue'),
            'description' => __('statistics.revenue_desc'),
            'route' => route('statistics.revenues'),
            'color' => 'danger'
        ],
    ];

    return view('statistics.stat_index', compact('stats'));
}

    public function index(Request $request)
    {
        $startDate = $request->input("start_date", Carbon::today()->toDateString());
        $endDate = $request->input("end_date", Carbon::today()->toDateString());

        // حساب الإحصائيات مباشرة من جدول WaitingQueue
        $totalCustomers = WaitingQueue::whereBetween('created_at', [
            Carbon::parse($startDate)->startOfDay(),
            Carbon::parse($endDate)->endOfDay()
        ])->count();

        $servedCustomers = WaitingQueue::whereBetween('created_at', [
            Carbon::parse($startDate)->startOfDay(),
            Carbon::parse($endDate)->endOfDay()
        ])->where('status', 'completed')->count();

        $walkInCustomers = WaitingQueue::whereBetween('created_at', [
            Carbon::parse($startDate)->startOfDay(),
            Carbon::parse($endDate)->endOfDay()
        ])->where('type', 'walk-in')->count();

        $appointmentCustomers = WaitingQueue::whereBetween('created_at', [
            Carbon::parse($startDate)->startOfDay(),
            Carbon::parse($endDate)->endOfDay()
        ])->where('type', 'appointment')->count();

        // حساب متوسط وقت الانتظار
        $completedCustomers = WaitingQueue::whereBetween('created_at', [
            Carbon::parse($startDate)->startOfDay(),
            Carbon::parse($endDate)->endOfDay()
        ])
        ->where('status', 'completed')
        ->whereNotNull('served_at')
        ->whereNotNull('arrival_time')
        ->get();

        $avgWaitingTime = 0;
        if ($completedCustomers->isNotEmpty()) {
            $totalWaitTime = $completedCustomers->sum(function ($queue) {
                return Carbon::parse($queue->served_at)->diffInMinutes(Carbon::parse($queue->arrival_time));
            });
            $avgWaitingTime = round($totalWaitTime / $completedCustomers->count(), 2);
        }

        // الحصول على الإحصائيات اليومية المفصلة
        $dailyStats = [];
        $currentDate = Carbon::parse($startDate);
        $endDateCarbon = Carbon::parse($endDate);

        while ($currentDate->lte($endDateCarbon)) {
            $dayStart = $currentDate->copy()->startOfDay();
            $dayEnd = $currentDate->copy()->endOfDay();

            $dayTotal = WaitingQueue::whereBetween('created_at', [$dayStart, $dayEnd])->count();
            $dayServed = WaitingQueue::whereBetween('created_at', [$dayStart, $dayEnd])
                ->where('status', 'completed')->count();
            $dayWalkIn = WaitingQueue::whereBetween('created_at', [$dayStart, $dayEnd])
                ->where('type', 'walk-in')->count();
            $dayAppointment = WaitingQueue::whereBetween('created_at', [$dayStart, $dayEnd])
                ->where('type', 'appointment')->count();

            $dailyStats[] = (object) [
                'date' => $currentDate->toDateString(),
                'total_customers' => $dayTotal,
                'served_customers' => $dayServed,
                'walk_in_customers' => $dayWalkIn,
                'appointment_customers' => $dayAppointment,
                'avg_waiting_time' => $avgWaitingTime,
            ];

            $currentDate->addDay();
        }

        return view("statistics.index", compact(
            "dailyStats",
            "totalCustomers",
            "servedCustomers",
            "walkInCustomers",
            "appointmentCustomers",
            "avgWaitingTime",
            "startDate",
            "endDate"
        ));
    }

    public function customers(Request $request)
    {
        $startDate = $request->input('start_date', now()->startOfMonth()->toDateString());
        $endDate   = $request->input('end_date', now()->toDateString());

        // بطاقات الإحصاء
        $newCustomers = Customer::whereBetween('created_at', [$startDate, $endDate])->count();
        $allCustomers = Customer::count();

        // الشارت: عملاء جدد كل يوم
        $chart = Customer::selectRaw('DATE(created_at) as date, COUNT(*) as total')
            ->whereBetween('created_at', [$startDate, $endDate])
            ->groupBy('date')->orderBy('date')->get();

        $chartLabels = $chart->pluck('date');
        $chartData = $chart->pluck('total');

        return view('statistics.customers', compact(
            'startDate', 'endDate', 'newCustomers', 'allCustomers', 'chartLabels', 'chartData'
        ));
    }

    // صفحة إحصائيات المواعيد
    public function appointments(Request $request)
    {
        $startDate = $request->input('start_date', now()->startOfMonth()->toDateString());
        $endDate   = $request->input('end_date', now()->toDateString());
        $type   = $request->input('type', '');
        $status = $request->input('status', '');

        $query = WaitingQueue::whereBetween('created_at', [$startDate, $endDate]);
        if ($type)   $query->where('type', $type);
        if ($status) $query->where('status', $status);

        $total     = $query->count();
        $running   = (clone $query)->where('status', 'serving')->count();
        $finished  = (clone $query)->where('status', 'completed')->count();
        $cancelled = (clone $query)->where('status', 'cancelled')->count();

        $chart = WaitingQueue::selectRaw('DATE(created_at) as date, COUNT(*) as total')
            ->whereBetween('created_at', [$startDate, $endDate]);
        if ($type)   $chart->where('type', $type);
        if ($status) $chart->where('status', $status);
        $chart = $chart->groupBy('date')->orderBy('date')->get();

        $chartLabels = $chart->pluck('date');
        $chartData = $chart->pluck('total');

        return view('statistics.appointments', compact(
            'startDate', 'endDate', 'type', 'status', 'total', 'running', 'finished', 'cancelled', 'chartLabels', 'chartData'
        ));
    }

    // صفحة إحصائيات قائمة الانتظار
    public function queue(Request $request)
    {
        $startDate = $request->input('start_date', now()->startOfMonth()->toDateString());
        $endDate   = $request->input('end_date', now()->toDateString());
        $type   = $request->input('type', '');
        $status = $request->input('status', '');

        $query = WaitingQueue::whereBetween('created_at', [$startDate, $endDate]);
        if ($type)   $query->where('type', $type);
        if ($status) $query->where('status', $status);

        $total     = $query->count();
        $waiting   = (clone $query)->where('status', 'waiting')->count();
        $serving   = (clone $query)->where('status', 'serving')->count();
        $completed = (clone $query)->where('status', 'completed')->count();
        $cancelled = (clone $query)->where('status', 'cancelled')->count();
        $avgWait   = (clone $query)->avg('estimated_wait_time') ?? 0;

        // الشارت 1: عبارة عن مجموع النوع حسب اليوم
        $byDateType = WaitingQueue::selectRaw('DATE(created_at) as date, type, COUNT(*) as total')
            ->whereBetween('created_at', [$startDate, $endDate]);
        if ($status) $byDateType->where('status', $status);
        $byDateType = $byDateType->groupBy('date', 'type')->orderBy('date')->get()
            ->groupBy('date')->map(function($rows) {
                return $rows->map(function($row) {
                    return ['type' => $row->type, 'total' => $row->total];
                });
            });

        // الشارت 2: أنواع الزيارات حسب اليوم
        $visitByDate = WaitingQueue::selectRaw('DATE(created_at) as date, visit_type, COUNT(*) as total')
            ->whereBetween('created_at', [$startDate, $endDate]);
        if ($status) $visitByDate->where('status', $status);
        if ($type) $visitByDate->where('type', $type);
        $visitByDate = $visitByDate->groupBy('date', 'visit_type')->orderBy('date')->get()
            ->groupBy('date')->map(function($rows) {
                return $rows->map(function($row) {
                    return ['visit_type' => $row->visit_type, 'total' => $row->total];
                });
            });

        return view('statistics.queue', compact(
            'total', 'waiting', 'serving', 'completed', 'cancelled', 'avgWait',
            'startDate', 'endDate', 'type', 'status', 'byDateType', 'visitByDate'
        ));
    }

    // صفحة إحصائيات الإيرادات
    public function revenues(Request $request)
    {
        $startDate = $request->input('start_date', now()->startOfMonth()->toDateString());
        $endDate   = $request->input('end_date', now()->toDateString());

        // عدد الزيارات المنجزة يومياً من جدول waiting_queue
        $chart = \App\Models\WaitingQueue::selectRaw('DATE(completed_at) as date, COUNT(*) as total')
            ->whereBetween('completed_at', [$startDate, $endDate])
            ->where('status', 'completed')
            ->groupBy('date')->orderBy('date')->get();

        $chartLabels = $chart->pluck('date');
        $chartData   = $chart->pluck('total');

        // مجاميع الكروت
        $totalRevenue = \App\Models\WaitingQueue::where('status', 'completed')
            ->whereBetween('completed_at', [$startDate, $endDate])->count();
        $averageRevenue = $chart->avg('total') ?? 0;

        return view('statistics.revenues', compact(
            'startDate', 'endDate', 'totalRevenue', 'averageRevenue', 'chartLabels', 'chartData'
        ));
    }

    // صفحة التقارير المتقدمة (مثال لمخطط بياني واحد)
    public function advanced(Request $request)
    {
        $startDate = $request->input('start_date', now()->startOfMonth()->toDateString());
        $endDate   = $request->input('end_date', now()->toDateString());

        // مثال متقدم: عدد الزيارات المنجزة "completed" كل يوم حسب completed_at
        $chart = \App\Models\WaitingQueue::selectRaw('DATE(completed_at) as date, COUNT(*) as total')
            ->whereBetween('completed_at', [$startDate, $endDate])
            ->where('status', 'completed')
            ->groupBy('date')->orderBy('date')->get();

        $chartLabels = $chart->pluck('date');
        $chartData   = $chart->pluck('total');

        return view('statistics.stat_index2', compact(
            'startDate', 'endDate', 'chartLabels', 'chartData'
        ));
    }
}
