<?php

namespace App\Http\Controllers\School;

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

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

        $metrics = [
            'loginsToday' => $schoolId ? DB::table('login_logs')->where('school_id', $schoolId)->whereDate('created_at', today())->count() : 0,
            'absencesToday' => $schoolId ? DB::table('attendance_records')->where('school_id', $schoolId)->where('status', 'absent')->whereDate('created_at', today())->count() : 0,
            'smsThisMonth' => $schoolId ? DB::table('sms_messages')->where('school_id', $schoolId)->where('created_at', '>=', now()->startOfMonth())->sum('cost') : 0,
            'exportsThisMonth' => $schoolId ? DB::table('export_jobs')->where('school_id', $schoolId)->where('created_at', '>=', now()->startOfMonth())->count() : 0,
        ];

        $usage = $schoolId
            ? DB::table('user_usage_daily')
                ->where('school_id', $schoolId)
                ->orderByDesc('date')
                ->limit(7)
                ->pluck('active_users')
                ->reverse()
                ->values()
            : collect();

        return Inertia::render('School/Reports', [
            'metrics' => array_map('intval', $metrics),
            'usage' => $usage,
            'availableReports' => [
                'دانش‌آموزان و کاربران',
                'مصرف SMS و wallet',
                'نتایج رأی‌گیری و candidateها',
                'حضور و غیاب ماهانه',
            ],
        ]);
    }
}
