<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Attendance;
use App\Models\Location;
use App\Models\User;
use Illuminate\Http\Request;

class DashboardController extends Controller
{
    public function index()
    {
        $stats = [
            'total_users'       => User::count(),
            'total_teachers'    => User::where('role', 'teacher')->count(),
            'total_students'    => User::where('role', 'student')->count(),
            'total_locations'   => Location::count(),
            'total_scans'       => Attendance::count(),
            'today_scans'       => Attendance::whereDate('created_at', today())->count(),
            'flagged_scans'     => Attendance::where('is_flagged', true)->count(),
            'offline_scans'     => Attendance::where('scan_mode', 'offline')->count(),
        ];

        $recentAttendance = Attendance::with(['user', 'location'])
            ->latest()
            ->limit(10)
            ->get();

        $flaggedAttendance = Attendance::with(['user', 'location'])
            ->where('is_flagged', true)
            ->latest()
            ->limit(5)
            ->get();

        $dailyScans = Attendance::selectRaw('DATE(created_at) as date, COUNT(*) as count')
            ->where('created_at', '>=', now()->subDays(7))
            ->groupBy('date')
            ->orderBy('date')
            ->get();

        return view('admin.dashboard', compact('stats', 'recentAttendance', 'flaggedAttendance', 'dailyScans'));
    }

    public function attendanceReport(Request $request)
    {
        $query = Attendance::with(['user', 'location'])->latest();

        if ($request->date) {
            $query->whereDate('created_at', $request->date);
        }
        if ($request->location_id) {
            $query->where('location_id', $request->location_id);
        }
        if ($request->role) {
            $query->where('role', $request->role);
        }
        if ($request->flagged) {
            $query->where('is_flagged', true);
        }

        $attendances = $query->paginate(25)->withQueryString();
        $locations   = Location::orderBy('name')->get();

        return view('admin.attendance-report', compact('attendances', 'locations'));
    }

    public function users()
    {
        $users = User::latest()->paginate(20);
        return view('admin.users', compact('users'));
    }

    public function updateUserRole(Request $request, User $user)
    {
        $request->validate(['role' => 'required|in:admin,teacher,student']);
        $user->update(['role' => $request->role]);
        return back()->with('success', 'User role updated.');
    }
}
