<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Filiale;
use App\Models\User;
use App\Support\ActivityLogger;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use Illuminate\View\View;

class FilialeController extends Controller
{
    public function index(): View
    {
        $filiales = Filiale::with('user')->withCount(['submissions', 'users'])->latest()->paginate(10);

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

    public function create(): View
    {
        return view('admin.filiales.create');
    }

    public function store(Request $request): RedirectResponse
    {
        $validated = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'code' => ['required', 'string', 'max:50', 'unique:filiales,code'],
            'address' => ['nullable', 'string', 'max:500'],
            'phone' => ['nullable', 'string', 'max:50'],
            'user_name' => ['required', 'string', 'max:255'],
            'user_email' => ['required', 'email', 'max:255', 'unique:users,email'],
            'user_password' => ['required', 'string', 'min:8', 'confirmed'],
        ]);

        $filiale = DB::transaction(function () use ($validated) {
            $filiale = Filiale::create([
                'name' => $validated['name'],
                'code' => Str::upper($validated['code']),
                'address' => $validated['address'] ?? null,
                'phone' => $validated['phone'] ?? null,
            ]);

            User::create([
                'name' => $validated['user_name'],
                'email' => $validated['user_email'],
                'password' => Hash::make($validated['user_password']),
                'role' => 'filiale',
                'filiale_id' => $filiale->id,
            ]);

            return $filiale;
        });

        ActivityLogger::log('filiale.created', $filiale, $filiale->name);

        return redirect()->route('admin.filiales.index')
            ->with('success', 'Filiale créée avec succès.');
    }

    public function edit(Filiale $filiale): View
    {
        $filiale->load('user');

        return view('admin.filiales.edit', compact('filiale'));
    }

    public function update(Request $request, Filiale $filiale): RedirectResponse
    {
        $validated = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'code' => ['required', 'string', 'max:50', 'unique:filiales,code,'.$filiale->id],
            'address' => ['nullable', 'string', 'max:500'],
            'phone' => ['nullable', 'string', 'max:50'],
            'is_active' => ['boolean'],
        ]);

        $filiale->update([
            'name' => $validated['name'],
            'code' => Str::upper($validated['code']),
            'address' => $validated['address'] ?? null,
            'phone' => $validated['phone'] ?? null,
            'is_active' => $request->boolean('is_active'),
        ]);

        ActivityLogger::log('filiale.updated', $filiale, $filiale->name);

        return redirect()->route('admin.filiales.index')
            ->with('success', 'Filiale mise à jour.');
    }

    public function destroy(Filiale $filiale): RedirectResponse
    {
        $name = $filiale->name;
        $filiale->delete();

        ActivityLogger::log('filiale.deleted', $filiale, $name);

        return redirect()->route('admin.filiales.index')
            ->with('success', 'Filiale supprimée.');
    }
}
