<?php

namespace App\Http\Controllers\School;

use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Inertia\Inertia;
use Inertia\Response;

class DashboardController extends Controller
{
    public function redirectByRole(Request $request): RedirectResponse
    {
        return match ($request->user()?->role_key) {
            'super_admin' => redirect()->route('super-admin.dashboard'),
            'teacher' => redirect()->route('teacher.dashboard'),
            'student' => redirect()->route('student.dashboard'),
            default => redirect()->route('school.dashboard'),
        };
    }

    public function index(Request $request): Response
    {
        $schoolId = $this->currentSchoolId($request);

        $metrics = [
            'students' => $schoolId ? DB::table('students')->where('school_id', $schoolId)->count() : 0,
            'teachers' => $schoolId ? DB::table('teachers')->where('school_id', $schoolId)->count() : 0,
            'classes' => $schoolId ? DB::table('classrooms')->where('school_id', $schoolId)->count() : 0,
            'smsBalance' => $schoolId ? (int) DB::table('sms_wallets')->where('school_id', $schoolId)->value('balance') : 0,
            'activeExams' => $schoolId ? DB::table('exams')->where('school_id', $schoolId)->where('status', 'published')->count() : 0,
            'absencesToday' => $schoolId ? DB::table('attendance_records')->where('school_id', $schoolId)->where('status', 'absent')->whereDate('created_at', today())->count() : 0,
        ];

        $tasks = [
            [
                'title' => 'تایید SMS غیبت‌ها',
                'count' => $schoolId ? DB::table('attendance_approval_requests')->where('school_id', $schoolId)->where('status', 'pending')->count() : 0,
                'tone' => 'warning',
            ],
            [
                'title' => 'تکمیل اطلاعات دانش‌آموزان',
                'count' => $schoolId ? DB::table('students')->where('school_id', $schoolId)->where(function ($query): void {
                    $query->whereNull('father_mobile')->orWhereNull('mother_mobile')->orWhereNull('home_phone')->orWhereNull('address');
                })->count() : 0,
                'tone' => 'info',
            ],
            [
                'title' => 'خروجی گزارش ماهانه',
                'count' => $schoolId ? DB::table('export_jobs')->where('school_id', $schoolId)->where('status', 'pending')->count() : 0,
                'tone' => 'default',
            ],
        ];

        $modules = $schoolId
            ? DB::table('school_modules')
                ->join('modules', 'modules.id', '=', 'school_modules.module_id')
                ->where('school_modules.school_id', $schoolId)
                ->where('school_modules.enabled', true)
                ->pluck('modules.name_fa')
                ->values()
            : collect();

        $license = $schoolId
            ? DB::table('licenses')
                ->where('school_id', $schoolId)
                ->where('status', 'active')
                ->orderByDesc('expires_at')
                ->first(['expires_at'])
            : null;

        $licenseExpiresAt = $license?->expires_at;
        $licenseWarning = null;
        if ($licenseExpiresAt) {
            $daysLeft = (int) now()->diffInDays($licenseExpiresAt, false);
            if ($daysLeft <= 30 && $daysLeft >= 0) {
                $licenseWarning = "مجوز مدرسه تا {$daysLeft} روز دیگر منقضی می‌شود.";
            } elseif ($daysLeft < 0) {
                $licenseWarning = 'مجوز مدرسه منقضی شده است. با پشتیبانی تماس بگیرید.';
            }
        }

        $importantAnnouncements = $schoolId
            ? DB::table('announcements')
                ->where('school_id', $schoolId)
                ->where('is_important', true)
                ->where('created_at', '>=', now()->subDays(7))
                ->orderByDesc('created_at')
                ->get(['id', 'title', 'body', 'audience', 'created_at'])
                ->map(fn ($a): array => [
                    'id' => (int) $a->id,
                    'title' => $a->title,
                    'body' => $a->body,
                    'createdAt' => $this->jalaliDate($a->created_at),
                ])
                ->values()
            : collect()->values();

        return Inertia::render('Dashboard/Index', [
            'metrics' => array_map('intval', $metrics),
            'tasks' => $tasks,
            'activeModules' => $modules,
            'importantAnnouncements' => $importantAnnouncements,
            'licenseWarning' => $licenseWarning,
        ]);
    }
}
