<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Branch;
use App\Models\User;
use Illuminate\Http\Request;

class BranchController extends Controller
{
    public function __construct()
    {
        //
    }

    public function index()
    {
        if (!auth()->user()->isAdmin()) {
            return abort(403);
        }

        $branches = Branch::withCount(['employees', 'cars', 'rentals'])
            ->orderBy('created_at', 'desc')
            ->paginate(15);

        return view('admin.branches.index', compact('branches'));
    }

    public function create()
    {
        if (!auth()->user()->isAdmin()) {
            return abort(403);
        }

        $managers = User::whereHas('roles', function ($q) {
            $q->whereIn('name', ['Manager', 'Super Admin']);
        })->get();

        return view('admin.branches.create', compact('managers'));
    }

    public function store(Request $request)
    {
        if (!auth()->user()->isAdmin()) {
            return abort(403);
        }
        $validated = $request->validate([
            'name' => 'required|string|unique:branches',
            'code' => 'required|string|unique:branches',
            'phone' => 'required|string',
            'email' => 'required|email|unique:branches',
            'address' => 'required|string',
            'city' => 'required|string',
            'region' => 'required|string',
            'latitude' => 'nullable|numeric',
            'longitude' => 'nullable|numeric',
            'manager_id' => 'nullable|exists:users,id',
            'description' => 'nullable|string',
        ]);

        Branch::create($validated);

        return redirect()->route('admin.branches.index')
            ->with('success', app()->getLocale() == 'ar' ? 'تم إنشاء الفرع بنجاح' : 'Branch created successfully');
    }

    public function show(Branch $branch)
    {
        if (!auth()->user()->isAdmin()) {
            return abort(403);
        }

        $branch->load('manager', 'employees', 'cars', 'rentals');

        return view('admin.branches.show', compact('branch'));
    }

    public function edit(Branch $branch)
    {
        if (!auth()->user()->isAdmin()) {
            return abort(403);
        }
        $managers = User::whereHas('roles', function ($q) {
            $q->whereIn('name', ['Manager', 'Super Admin']);
        })->get();

        return view('admin.branches.edit', compact('branch', 'managers'));
    }

    public function update(Request $request, Branch $branch)
    {
        if (!auth()->user()->isAdmin()) {
            return abort(403);
        }

        $validated = $request->validate([
            'name' => 'required|string|unique:branches,name,' . $branch->id,
            'code' => 'required|string|unique:branches,code,' . $branch->id,
            'phone' => 'required|string',
            'email' => 'required|email|unique:branches,email,' . $branch->id,
            'address' => 'required|string',
            'city' => 'required|string',
            'region' => 'required|string',
            'latitude' => 'nullable|numeric',
            'longitude' => 'nullable|numeric',
            'manager_id' => 'nullable|exists:users,id',
            'status' => 'required|in:active,inactive',
            'description' => 'nullable|string',
        ]);

        $branch->update($validated);

        return redirect()->route('admin.branches.show', $branch)
            ->with('success', app()->getLocale() == 'ar' ? 'تم تحديث الفرع بنجاح' : 'Branch updated successfully');
    }

    public function destroy(Branch $branch)
    {
        if (!auth()->user()->isAdmin()) {
            return abort(403);
        }

        if ($branch->cars()->exists() || $branch->employees()->exists()) {
            return back()->with('error', app()->getLocale() == 'ar' 
                ? 'لا يمكن حذف فرع يحتوي على سيارات أو موظفين' 
                : 'Cannot delete a branch with vehicles or employees');
        }

        $branch->delete();

        return redirect()->route('admin.branches.index')
            ->with('success', app()->getLocale() == 'ar' ? 'تم حذف الفرع بنجاح' : 'Branch deleted successfully');
    }

    public function stats(Branch $branch)
    {
        if (!auth()->user()->isAdmin()) {
            return abort(403);
        }

        $stats = [
            'total_cars' => $branch->cars()->count(),
            'available_cars' => $branch->cars()->where('rental_status', 'available')->count(),
            'rented_cars' => $branch->cars()->where('rental_status', 'rented')->count(),
            'maintenance_cars' => $branch->cars()->where('rental_status', 'maintenance')->count(),
            'total_employees' => $branch->employees()->count(),
            'active_rentals' => $branch->rentals()->where('status', 'open')->count(),
            'today_revenue' => $branch->rentals()->where('status', 'closed')->whereDate('end_date', today())->sum('total_amount'),
            'month_revenue' => $branch->rentals()->where('status', 'closed')->whereMonth('end_date', now()->month)->sum('total_amount'),
        ];

        return response()->json($stats);
    }
}
