<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\WaitingQueue;

class StatisticsAdvancedController extends Controller
{
    public function index(Request $request)
    {
      // التواريخ الافتراضية
    $startDate = $request->start_date ?? now()->startOfMonth()->toDateString();
    $endDate   = $request->end_date ?? now()->endOfMonth()->toDateString();

    $type   = $request->type;
    $status = $request->status;

    // Base query
    $baseQuery = WaitingQueue::query()
        ->whereBetween('created_at', [$startDate, $endDate]);

    if ($type) {
        $baseQuery->where('type', $type);
    }
    if ($status) {
        $baseQuery->where('status', $status);
    }

    // ---- الكروت ----
    $total     = (clone $baseQuery)->count();
    $waiting   = (clone $baseQuery)->where('status', 'waiting')->count();
    $serving   = (clone $baseQuery)->where('status', 'serving')->count();
    $completed = (clone $baseQuery)->where('status', 'completed')->count();
    $cancelled = (clone $baseQuery)->where('status', 'cancelled')->count();

    // متوسط الانتظار (بالدقائق)
    $avgWait = (clone $baseQuery)
        ->whereNotNull('served_at')
        ->selectRaw('AVG(TIMESTAMPDIFF(MINUTE, created_at, served_at)) as avg_wait')
        ->value('avg_wait') ?? 0;

    // ---- Chart 1: walk-in vs appointment by date ----
    $byDateType = (clone $baseQuery)
        ->selectRaw('DATE(created_at) as date, type, COUNT(*) as total')
        ->groupByRaw('DATE(created_at), type')
        ->orderBy('date')
        ->get()
        ->groupBy('date');

    // ---- Chart 2: visit_type by date ----
    $visitByDate = (clone $baseQuery)
        ->selectRaw('DATE(created_at) as date, visit_type, COUNT(*) as total')
        ->groupByRaw('DATE(created_at), visit_type')
        ->orderBy('date')
        ->get()
        ->groupBy('date');

    // ---- Chart القديم حسب النوع (موعد / زيارة مباشرة) ----
    $byType = (clone $baseQuery)
        ->selectRaw('type, COUNT(*) as total')
        ->groupBy('type')
        ->pluck('total', 'type');

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



}
