<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
use App\Models\Ride;
use App\Models\Wallet;
use App\Models\Driver;

class AdminWebController extends Controller
{
    /**
     * Show admin login form.
     */
    public function showLoginForm()
    {
        if (Auth::guard('admin')->check()) {
            return redirect()->route('admin.dashboard');
        }
        return view('admin.login');
    }

    /**
     * Handle admin login.
     */
    public function login(Request $request)
    {
        $credentials = $request->validate([
            'email' => 'required|email',
            'password' => 'required|string',
        ]);

        if (Auth::guard('admin')->attempt($credentials)) {
            $request->session()->regenerate();
            return redirect()->route('admin.dashboard');
        }

        return back()->withErrors([
            'email' => 'The provided credentials do not match our records.',
        ]);
    }

    /**
     * Show admin dashboard.
     */
    public function dashboard()
    {
        $stats = [
            'total_users' => User::count(),
            'total_drivers' => Driver::count(),
            'total_rides' => Ride::count(),
            'ongoing_rides' => Ride::where('status', 'ongoing')->count(),
            'ecosystem_balance' => (float)Wallet::sum('balance'),
        ];

        $recentRides = Ride::with(['rider', 'driver'])->orderBy('created_at', 'desc')->limit(10)->get();
        $recentUsers = User::orderBy('created_at', 'desc')->limit(10)->get();

        return view('admin.dashboard', compact('stats', 'recentRides', 'recentUsers'));
    }

    /**
     * List all users.
     */
    public function usersIndex()
    {
        $users = User::with(['wallet', 'driver'])->orderBy('created_at', 'desc')->paginate(20);
        return view('admin.users.index', compact('users'));
    }

    /**
     * List all drivers and candidates.
     */
    public function driversIndex()
    {
        $drivers = Driver::with('user')->orderBy('created_at', 'desc')->paginate(20);
        return view('admin.drivers.index', compact('drivers'));
    }

    /**
     * Approve a driver.
     */
    public function approveDriver(Driver $driver)
    {
        $driver->update(['is_verified' => true, 'status' => 'active']);
        
        // Update user type if not already driver
        $driver->user->update(['user_type' => 'driver']);

        return back()->with('success', 'Driver approved successfully!');
    }

    /**
     * Handle logout.
     */
    public function logout(Request $request)
    {
        Auth::guard('admin')->logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return redirect()->route('admin.login');
    }
}
