<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\Ride;
use App\Models\Booking;
use App\Models\Vehicle;
use App\Models\City;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class AdminController extends Controller
{
    /**
     * Show admin login page
     */
    public function showLogin()
    {
        if (Auth::check() && Auth::user()->is_admin) {
            return redirect()->route('admin.dashboard');
        }
        return view('admin.login');
    }

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

        $credentials = $request->only('email', 'password');

        if (Auth::attempt($credentials)) {
            $user = Auth::user();
            
            if (!$user->is_admin) {
                Auth::logout();
                return back()->withErrors(['email' => 'You do not have admin access.']);
            }

            $request->session()->regenerate();
            return redirect()->route('admin.dashboard');
        }

        return back()->withErrors(['email' => 'Invalid credentials.']);
    }

    /**
     * Logout admin
     */
    public function logout(Request $request)
    {
        Auth::logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();
        return redirect()->route('admin.login');
    }

    /**
     * Admin Dashboard
     */
    public function dashboard()
    {
        if (!Auth::check() || !Auth::user()->is_admin) {
            return redirect()->route('admin.login');
        }

        $stats = [
            'total_users' => User::count(),
            'total_drivers' => User::whereIn('user_type', ['driver', 'both'])->count(),
            'total_passengers' => User::whereIn('user_type', ['passenger', 'both'])->count(),
            'total_rides' => Ride::count(),
            'active_rides' => Ride::where('ride_status', 'scheduled')->where('departure_datetime', '>', now())->count(),
            'total_bookings' => Booking::count(),
            'total_vehicles' => Vehicle::count(),
            'verified_users' => User::where('is_verified', true)->count(),
            'pending_kyc' => User::whereNotNull('verification_document')->where('is_verified', false)->count(),
            'revenue' => Booking::where('payment_status', 'paid')->sum('total_price') * 280,
        ];

        $recent_users = User::latest()->take(5)->get();
        $recent_bookings = Booking::with(['ride.route.fromCity', 'ride.route.toCity', 'passenger'])->latest()->take(5)->get();
        $recent_rides = Ride::with(['driver', 'route.fromCity', 'route.toCity', 'vehicle'])->latest()->take(5)->get();

        return view('admin.dashboard', compact('stats', 'recent_users', 'recent_bookings', 'recent_rides'));
    }

    /**
     * Users list
     */
    public function users()
    {
        if (!Auth::check() || !Auth::user()->is_admin) {
            return redirect()->route('admin.login');
        }

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

    /**
     * Verify user KYC
     */
    public function verifyUser($id)
    {
        if (!Auth::check() || !Auth::user()->is_admin) {
            return redirect()->route('admin.login');
        }

        $user = User::findOrFail($id);
        $user->update(['is_verified' => true]);
        return back()->with('success', 'User verified successfully!');
    }

    /**
     * Toggle admin status
     */
    public function toggleAdmin($id)
    {
        if (!Auth::check() || !Auth::user()->is_admin) {
            return redirect()->route('admin.login');
        }

        $user = User::findOrFail($id);
        
        // Prevent removing own admin status
        if ($user->id === Auth::id()) {
            return back()->with('error', 'Cannot remove your own admin status.');
        }
        
        $user->update(['is_admin' => !$user->is_admin]);
        return back()->with('success', 'Admin status updated!');
    }

    /**
     * Delete user
     */
    public function deleteUser($id)
    {
        if (!Auth::check() || !Auth::user()->is_admin) {
            return redirect()->route('admin.login');
        }

        $user = User::findOrFail($id);
        
        if ($user->id === Auth::id()) {
            return back()->with('error', 'Cannot delete your own account.');
        }
        
        $user->delete();
        return back()->with('success', 'User deleted successfully!');
    }

    /**
     * Rides list
     */
    public function rides()
    {
        if (!Auth::check() || !Auth::user()->is_admin) {
            return redirect()->route('admin.login');
        }

        $rides = Ride::with(['driver', 'route.fromCity', 'route.toCity', 'vehicle'])->latest()->paginate(20);
        return view('admin.rides', compact('rides'));
    }

    /**
     * Bookings list
     */
    public function bookings()
    {
        if (!Auth::check() || !Auth::user()->is_admin) {
            return redirect()->route('admin.login');
        }

        $bookings = Booking::with(['ride.route.fromCity', 'ride.route.toCity', 'passenger', 'ride.driver'])->latest()->paginate(20);
        return view('admin.bookings', compact('bookings'));
    }

    /**
     * Vehicles list
     */
    public function vehicles()
    {
        if (!Auth::check() || !Auth::user()->is_admin) {
            return redirect()->route('admin.login');
        }

        $vehicles = Vehicle::with('driver')->latest()->paginate(20);
        return view('admin.vehicles', compact('vehicles'));
    }

    /**
     * Verify vehicle
     */
    public function verifyVehicle($id)
    {
        if (!Auth::check() || !Auth::user()->is_admin) {
            return redirect()->route('admin.login');
        }

        $vehicle = Vehicle::findOrFail($id);
        $vehicle->update(['is_verified' => true]);
        return back()->with('success', 'Vehicle verified successfully!');
    }

    /**
     * Settings page
     */
    public function settings()
    {
        if (!Auth::check() || !Auth::user()->is_admin) {
            return redirect()->route('admin.login');
        }

        return view('admin.settings');
    }

    /**
     * Show create user form
     */
    public function createUser()
    {
        if (!Auth::check() || !Auth::user()->is_admin) {
            return redirect()->route('admin.login');
        }

        $user = new User();
        return view('admin.user-edit', compact('user'));
    }

    /**
     * Store new user
     */
    public function storeUser(Request $request)
    {
        if (!Auth::check() || !Auth::user()->is_admin) {
            return redirect()->route('admin.login');
        }

        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:users,email',
            'password' => 'required|min:8|confirmed',
            'phone' => 'nullable|string|max:20',
            'user_type' => 'required|in:passenger,driver,both',
        ]);

        User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
            'phone' => $request->phone,
            'user_type' => $request->user_type,
            'cnic' => $request->cnic,
            'address' => $request->address,
            'is_verified' => $request->has('is_verified'),
            'is_admin' => $request->has('is_admin'),
        ]);

        return redirect()->route('admin.users')->with('success', 'User created successfully!');
    }

    /**
     * Show edit user form
     */
    public function editUser($id)
    {
        if (!Auth::check() || !Auth::user()->is_admin) {
            return redirect()->route('admin.login');
        }

        $user = User::findOrFail($id);
        return view('admin.user-edit', compact('user'));
    }

    /**
     * Update user
     */
    public function updateUser(Request $request, $id)
    {
        if (!Auth::check() || !Auth::user()->is_admin) {
            return redirect()->route('admin.login');
        }

        $user = User::findOrFail($id);

        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:users,email,' . $id,
            'password' => 'nullable|min:8|confirmed',
            'phone' => 'nullable|string|max:20',
            'user_type' => 'required|in:passenger,driver,both',
        ]);

        $data = [
            'name' => $request->name,
            'email' => $request->email,
            'phone' => $request->phone,
            'user_type' => $request->user_type,
            'cnic' => $request->cnic,
            'address' => $request->address,
            'is_verified' => $request->has('is_verified'),
            'is_admin' => $request->has('is_admin'),
        ];

        if ($request->filled('password')) {
            $data['password'] = Hash::make($request->password);
        }

        $user->update($data);

        return redirect()->route('admin.users')->with('success', 'User updated successfully!');
    }

    /**
     * Payments management page
     */
    public function payments()
    {
        if (!Auth::check() || !Auth::user()->is_admin) {
            return redirect()->route('admin.login');
        }

        $stats = [
            'total_revenue' => Booking::where('payment_status', 'paid')->sum('total_price') * 280,
            'paid_bookings' => Booking::where('payment_status', 'paid')->count(),
            'pending_payments' => Booking::where('payment_status', 'pending')->count(),
            'mobile_payments' => Booking::whereIn('payment_status', ['paid'])->whereNotNull('created_at')->count(),
        ];

        $recent_payments = Booking::with(['ride.route.fromCity', 'ride.route.toCity', 'passenger'])
            ->latest()
            ->take(20)
            ->get();

        return view('admin.payments', compact('stats', 'recent_payments'));
    }

    /**
     * Update payment gateway settings
     */
    public function updatePaymentSettings(Request $request)
    {
        if (!Auth::check() || !Auth::user()->is_admin) {
            return redirect()->route('admin.login');
        }

        // In a real app, save these to database or config
        // For now, just return success
        return back()->with('success', 'Payment gateway settings updated!');
    }

    /**
     * Update pricing settings
     */
    public function updatePricing(Request $request)
    {
        if (!Auth::check() || !Auth::user()->is_admin) {
            return redirect()->route('admin.login');
        }

        // In a real app, save these to database or config
        return back()->with('success', 'Pricing settings updated!');
    }

    /**
     * Verify payment
     */
    public function verifyPayment($id)
    {
        if (!Auth::check() || !Auth::user()->is_admin) {
            return redirect()->route('admin.login');
        }

        $booking = Booking::findOrFail($id);
        $booking->update(['payment_status' => 'paid']);

        return back()->with('success', 'Payment verified successfully!');
    }

    /**
     * KYC Verification page
     */
    public function kyc()
    {
        if (!Auth::check() || !Auth::user()->is_admin) {
            return redirect()->route('admin.login');
        }

        $pending_users = User::whereNotNull('verification_document')
            ->where('is_verified', false)
            ->latest()
            ->get();

        $verified_users = User::where('is_verified', true)
            ->latest()
            ->take(20)
            ->get();

        $pending_count = User::whereNotNull('verification_document')->where('is_verified', false)->count();
        $verified_count = User::where('is_verified', true)->count();
        $rejected_count = 0; // Would need a rejected status field
        $total_submitted = User::whereNotNull('verification_document')->count();

        return view('admin.kyc', compact(
            'pending_users', 
            'verified_users', 
            'pending_count', 
            'verified_count', 
            'rejected_count', 
            'total_submitted'
        ));
    }

    /**
     * Approve KYC
     */
    public function approveKyc($id)
    {
        if (!Auth::check() || !Auth::user()->is_admin) {
            return redirect()->route('admin.login');
        }

        $user = User::findOrFail($id);
        $user->update(['is_verified' => true]);

        return back()->with('success', 'KYC approved for ' . $user->name . '!');
    }

    /**
     * Reject KYC
     */
    public function rejectKyc($id)
    {
        if (!Auth::check() || !Auth::user()->is_admin) {
            return redirect()->route('admin.login');
        }

        $user = User::findOrFail($id);
        $user->update([
            'verification_document' => null,
            'is_verified' => false
        ]);

        return back()->with('success', 'KYC rejected for ' . $user->name . '. User will need to resubmit.');
    }

    /**
     * Revoke verification
     */
    public function revokeKyc($id)
    {
        if (!Auth::check() || !Auth::user()->is_admin) {
            return redirect()->route('admin.login');
        }

        $user = User::findOrFail($id);
        $user->update(['is_verified' => false]);

        return back()->with('success', 'Verification revoked for ' . $user->name . '.');
    }
}
