<?php

namespace Modules\ClinicCore\Http\Controllers;

use Illuminate\Routing\Controller;
use Modules\ClinicCore\Entities\ClcAppointment;
use Modules\ClinicCore\Entities\ClcPatient;
use Modules\ClinicCore\Entities\ClcVaccination;
use Modules\ClinicCore\Entities\ClcDoctor;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;

class ClcDashboardController extends Controller
{
    public function index()
    {
        if (!auth()->user()->can('clinic.access_module')) {
            abort(403, 'Unauthorized action.');
        }

        $businessId = request()->session()->get('user.business_id');
        $today      = Carbon::today();
        $monthStart = $today->copy()->startOfMonth();
        $weekStart  = $today->copy()->startOfWeek();

        // ── Core KPIs ───────────────────────────────────────────────
        $todayAppts     = ClcAppointment::where('business_id', $businessId)->whereDate('appointment_date', $today);
        $todayTotal     = (clone $todayAppts)->count();
        $todayCompleted = (clone $todayAppts)->where('status', 'completed')->count();
        $todayPending   = (clone $todayAppts)->whereIn('status', ['pending', 'confirmed'])->count();
        $todayNoShow    = (clone $todayAppts)->where('status', 'no_show')->count();

        $weekAppts      = ClcAppointment::where('business_id', $businessId)
                            ->whereBetween('appointment_date', [$weekStart, $today->copy()->endOfWeek()]);
        $weekTotal      = (clone $weekAppts)->count();
        $weekCompleted  = (clone $weekAppts)->where('status', 'completed')->count();

        $monthAppts     = ClcAppointment::where('business_id', $businessId)
                            ->whereBetween('appointment_date', [$monthStart, $today->copy()->endOfMonth()]);
        $monthTotal     = (clone $monthAppts)->count();

        $totalPets      = ClcPatient::where('business_id', $businessId)->active()->count();
        $newPetsMonth   = ClcPatient::where('business_id', $businessId)->where('created_at', '>=', $monthStart)->count();

        $overdueVax     = ClcVaccination::where('business_id', $businessId)
                            ->whereIn('taken_status', ['taken_in', 'taken_out'])
                            ->where('next_due_date', '<', $today)->count();
        $dueSoonVax     = ClcVaccination::where('business_id', $businessId)
                            ->whereIn('taken_status', ['taken_in', 'taken_out'])
                            ->whereBetween('next_due_date', [$today, $today->copy()->addDays(30)])->count();

        $pendingTotal   = ClcAppointment::where('business_id', $businessId)->where('status', 'pending')->count();
        $confirmedTotal = ClcAppointment::where('business_id', $businessId)->where('status', 'confirmed')->count();

        // Completion rate this week
        $completionRate = $weekTotal > 0 ? round(($weekCompleted / $weekTotal) * 100) : 0;

        // No-show rate last 7 days
        $last7Base      = ClcAppointment::where('business_id', $businessId)
                            ->whereBetween('appointment_date', [$today->copy()->subDays(6), $today]);
        $last7Total     = (clone $last7Base)->count();
        $last7NoShow    = (clone $last7Base)->where('status', 'no_show')->count();
        $noShowRate     = $last7Total > 0 ? round(($last7NoShow / $last7Total) * 100) : 0;

        $stats = compact(
            'todayTotal', 'todayCompleted', 'todayPending', 'todayNoShow',
            'weekTotal', 'weekCompleted',
            'monthTotal',
            'totalPets', 'newPetsMonth',
            'overdueVax', 'dueSoonVax',
            'pendingTotal', 'confirmedTotal',
            'completionRate', 'noShowRate'
        );

        // ── Today's Schedule ────────────────────────────────────────
        $today_appointments = ClcAppointment::with(['pet', 'owner', 'doctor', 'department'])
            ->where('business_id', $businessId)
            ->whereDate('appointment_date', $today)
            ->orderBy('appointment_time')
            ->get();

        // ── Vaccination Alerts ──────────────────────────────────────
        $overdue_vaccinations = ClcVaccination::with(['pet.owner', 'vaccineType'])
            ->where('business_id', $businessId)
            ->whereIn('taken_status', ['taken_in', 'taken_out'])
            ->where('next_due_date', '<', $today)
            ->orderBy('next_due_date')
            ->limit(8)
            ->get();

        $due_soon_vaccinations = ClcVaccination::with(['pet.owner', 'vaccineType'])
            ->where('business_id', $businessId)
            ->whereIn('taken_status', ['taken_in', 'taken_out'])
            ->whereBetween('next_due_date', [$today, $today->copy()->addDays(30)])
            ->orderBy('next_due_date')
            ->limit(8)
            ->get();

        // ── 14-day Appointment Trend ────────────────────────────────
        $chart_labels = [];
        $chart_data   = [];
        for ($i = 13; $i >= 0; $i--) {
            $day            = $today->copy()->subDays($i);
            $chart_labels[] = $day->format('D d');
            $chart_data[]   = ClcAppointment::where('business_id', $businessId)
                ->whereDate('appointment_date', $day)->count();
        }

        // ── Status Distribution (donut) ─────────────────────────────
        $statusDist = ClcAppointment::where('business_id', $businessId)
            ->whereBetween('appointment_date', [$today->copy()->subDays(29), $today])
            ->selectRaw('status, COUNT(*) as cnt')
            ->groupBy('status')
            ->pluck('cnt', 'status')
            ->toArray();

        // ── Species Distribution (donut) ────────────────────────────
        $speciesDist = ClcPatient::where('business_id', $businessId)->active()
            ->selectRaw('LOWER(species) as species, COUNT(*) as cnt')
            ->groupBy('species')
            ->orderByDesc('cnt')
            ->limit(6)
            ->pluck('cnt', 'species')
            ->toArray();

        // ── Smart Insights ──────────────────────────────────────────
        $insights = [];

        if ($overdueVax > 0) {
            $insights[] = ['type' => 'danger', 'icon' => 'fa-exclamation-circle',
                'msg' => $overdueVax . ' vaccination' . ($overdueVax > 1 ? 's are' : ' is') . ' overdue and need immediate follow-up.'];
        }
        if ($dueSoonVax > 0) {
            $insights[] = ['type' => 'warning', 'icon' => 'fa-clock',
                'msg' => $dueSoonVax . ' vaccination' . ($dueSoonVax > 1 ? 's are' : ' is') . ' due within the next 30 days.'];
        }
        if ($todayNoShow > 0) {
            $insights[] = ['type' => 'warning', 'icon' => 'fa-user-times',
                'msg' => $todayNoShow . ' patient' . ($todayNoShow > 1 ? 's' : '') . ' did not show up for today\'s appointments.'];
        }
        if ($pendingTotal > 5) {
            $insights[] = ['type' => 'info', 'icon' => 'fa-calendar',
                'msg' => $pendingTotal . ' appointments are pending confirmation — consider reviewing the schedule.'];
        }
        if ($noShowRate >= 20) {
            $insights[] = ['type' => 'warning', 'icon' => 'fa-chart-line',
                'msg' => 'No-show rate over the last 7 days is ' . $noShowRate . '% — consider sending reminders.'];
        }
        if ($completionRate >= 80 && $weekTotal > 0) {
            $insights[] = ['type' => 'success', 'icon' => 'fa-trophy',
                'msg' => 'Great week! ' . $completionRate . '% of this week\'s appointments were completed.'];
        }
        if ($newPetsMonth > 0) {
            $insights[] = ['type' => 'success', 'icon' => 'fa-paw',
                'msg' => $newPetsMonth . ' new pet' . ($newPetsMonth > 1 ? 's' : '') . ' registered this month.'];
        }
        if (empty($insights)) {
            $insights[] = ['type' => 'success', 'icon' => 'fa-check-circle',
                'msg' => 'Everything looks good — no urgent actions required.'];
        }

        // ── Doctors on duty today ───────────────────────────────────
        $doctorsToday = ClcDoctor::where('business_id', $businessId)->active()
            ->withCount(['appointments' => fn($q) => $q->whereDate('appointment_date', $today)])
            ->orderByDesc('appointments_count')
            ->limit(6)
            ->get();

        return view('clinicCore::dashboard.index', compact(
            'stats', 'today_appointments', 'overdue_vaccinations', 'due_soon_vaccinations',
            'chart_labels', 'chart_data', 'statusDist', 'speciesDist',
            'insights', 'doctorsToday'
        ));
    }
}
