<?php

namespace App\Http\Controllers;

use App\Models\Branch;
use App\Models\Organization;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Illuminate\View\View;

class BranchController extends Controller
{
    public function index(): View
    {
        return view('admin.branches.index', [
            'branches' => Branch::query()->with('organization')->withTrashed()->orderByDesc('is_headquarters')->orderBy('name')->get(),
        ]);
    }

    public function create(): View
    {
        return view('admin.branches.form', [
            'branch' => new Branch(),
            'organizations' => Organization::query()->where('is_active', true)->get(),
            'parents' => Branch::query()->where('is_active', true)->get(),
        ]);
    }

    public function store(Request $request): RedirectResponse
    {
        $data = $this->validated($request);
        $data['is_headquarters'] = $request->boolean('is_headquarters');
        $data['is_active'] = $request->boolean('is_active', true);
        Branch::query()->create($data);

        return redirect()->route('admin.branches.index')->with('success', 'Filial criada com sucesso.');
    }

    public function edit(Branch $branch): View
    {
        return view('admin.branches.form', [
            'branch' => $branch,
            'organizations' => Organization::query()->where('is_active', true)->get(),
            'parents' => Branch::query()->where('is_active', true)->whereKeyNot($branch->id)->get(),
        ]);
    }

    public function update(Request $request, Branch $branch): RedirectResponse
    {
        $data = $this->validated($request, $branch);
        $data['is_headquarters'] = $request->boolean('is_headquarters');
        $data['is_active'] = $request->boolean('is_active');
        $branch->update($data);

        return redirect()->route('admin.branches.index')->with('success', 'Filial actualizada com sucesso.');
    }

    public function destroy(Branch $branch): RedirectResponse
    {
        if ($branch->is_headquarters) {
            return back()->with('warning', 'A sede principal não pode ser arquivada enquanto mantiver essa classificação.');
        }

        $branch->update(['is_active' => false]);
        $branch->delete();

        return back()->with('success', 'Filial arquivada e preservada no histórico.');
    }

    private function validated(Request $request, ?Branch $branch = null): array
    {
        return $request->validate([
            'organization_id' => ['required', 'exists:organizations,id'],
            'parent_id' => ['nullable', 'exists:branches,id'],
            'code' => ['required', 'string', 'max:30', Rule::unique('branches')->ignore($branch?->id)],
            'name' => ['required', 'string', 'max:255'],
            'type' => ['required', Rule::in(['sede', 'filial'])],
            'province' => ['required', 'string', 'max:100'],
            'municipality' => ['nullable', 'string', 'max:100'],
            'address' => ['nullable', 'string', 'max:255'],
            'phone' => ['nullable', 'string', 'max:40'],
            'email' => ['nullable', 'email', 'max:255'],
        ]);
    }
}
