<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class BranchController extends Controller
{
    public function index(Request $request)
    {
        $query = \App\Models\Branch::query();

        if ($request->filled('search')) {
            $search = $request->get('search');
            $query->where(function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                    ->orWhere('code', 'like', "%{$search}%")
                    ->orWhere('address', 'like', "%{$search}%");
            });
        }

        if ($request->filled('is_active')) {
            $query->where('is_active', $request->is_active === 'true');
        }

        $branches = $query->with('manager')->orderBy('created_at', 'desc')->paginate(10);

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

    public function create()
    {
        $managers = \App\Models\User::where('role', 'BRANCH_MANAGER')->get();

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

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'code' => 'required|string|unique:branches,code',
            'address' => 'nullable|string',
            'phone' => 'nullable|string',
            'email' => 'nullable|email',
            'manager_id' => 'nullable|exists:users,id',
            'currency' => 'nullable|string|max:3',
            'timezone' => 'nullable|string',
            'map_lat' => 'nullable|numeric',
            'map_lng' => 'nullable|numeric',
            'google_map_link' => 'nullable|url',
        ]);

        if (! empty($validated['manager_id'])) {
            // Check if manager manages another branch
            if (\App\Models\Branch::where('manager_id', $validated['manager_id'])->exists()) {
                return back()->withErrors(['manager_id' => 'This user already manages another branch.'])->withInput();
            }
        }

        $validated['opening_date'] = now();
        $validated['is_active'] = true;

        \App\Models\Branch::create($validated);

        return redirect()->route('admin.branches.index')->with('success', 'Branch created successfully.');
    }

    public function edit(\App\Models\Branch $branch)
    {
        $managers = \App\Models\User::where('role', 'BRANCH_MANAGER')->get();

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

    public function update(Request $request, \App\Models\Branch $branch)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'code' => 'required|string|unique:branches,code,'.$branch->id,
            'address' => 'nullable|string',
            'phone' => 'nullable|string',
            'email' => 'nullable|email',
            'manager_id' => 'nullable|exists:users,id',
            'currency' => 'nullable|string|max:3',
            'timezone' => 'nullable|string',
            'map_lat' => 'nullable|numeric',
            'map_lng' => 'nullable|numeric',
            'google_map_link' => 'nullable|url',
            'is_active' => 'boolean',
        ]);

        if (! empty($validated['manager_id']) && $validated['manager_id'] != $branch->manager_id) {
            if (\App\Models\Branch::where('manager_id', $validated['manager_id'])->exists()) {
                return back()->withErrors(['manager_id' => 'This user already manages another branch.'])->withInput();
            }
        }

        $branch->update($validated);

        return redirect()->route('admin.branches.index')->with('success', 'Branch updated successfully.');
    }

    public function destroy(\App\Models\Branch $branch)
    {
        $branch->delete();

        return redirect()->route('admin.branches.index')->with('success', 'Branch deleted successfully.');
    }
}
