<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Appointment;
use App\Models\Doctor;
use App\Models\Patient;
use App\Models\Queue;
use App\Models\Subscription;
use App\Models\User;
use Illuminate\Support\Facades\DB;

class DashboardController extends Controller
{
    public function index()
    {
        // --- إحصائيات عامة ---
        $stats = [
            'total_doctors'         => Doctor::count(),
            'active_doctors'        => Doctor::where('status', 'active')->count(),
            'pending_doctors'       => Doctor::where('status', 'pending')->count(),
            'total_patients'        => Patient::count(),
            'new_patients_month'    => Patient::whereMonth('created_at', now()->month)->count(),
            'today_appointments'    => Appointment::whereDate('appointment_date', today())->count(),
            'today_queue'           => Queue::whereDate('queue_date', today())
                                            ->whereIn('status', ['waiting','called','in_progress'])
                                            ->count(),
            'active_subscriptions'  => Subscription::where('status','active')
                                            ->where('ends_at', '>', now())->count(),
            'monthly_revenue'       => Subscription::where('status','active')
                                            ->whereMonth('created_at', now()->month)
                                            ->sum('amount_paid'),
        ];

        // --- آخر 7 أيام: مواعيد يومياً ---
        $weeklyAppointments = Appointment::select(
                DB::raw('DATE(appointment_date) as date'),
                DB::raw('COUNT(*) as total')
            )
            ->whereBetween('appointment_date', [now()->subDays(6), now()])
            ->groupBy('date')
            ->orderBy('date')
            ->pluck('total', 'date');

        // --- أحدث الأطباء المنتظرين الموافقة ---
        $pendingDoctors = Doctor::with('user')
            ->where('status', 'pending')
            ->latest()
            ->take(5)
            ->get();

        // --- أحدث المرضى ---
        $recentPatients = User::where('role', 'patient')
            ->latest()
            ->take(5)
            ->get();

        // --- توزيع الاشتراكات حسب الباقة ---
        $subscriptionsByPlan = Subscription::with('plan')
            ->where('status', 'active')
            ->select('plan_id', DB::raw('COUNT(*) as total'))
            ->groupBy('plan_id')
            ->get();

        return view('admin.dashboard.index', compact(
            'stats',
            'weeklyAppointments',
            'pendingDoctors',
            'recentPatients',
            'subscriptionsByPlan'
        ));
    }
}
