<?php

namespace App\Http\Controllers;

use App\Http\Requests\Merchant\StoreMerchantRequest;
use App\Http\Requests\Merchant\UpdateMerchantRequest;
use App\Models\BusinessType;
use App\Models\Merchant;
use App\Services\MerchantService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class MerchantController extends Controller
{
    protected MerchantService $merchantService;

    public function __construct(MerchantService $merchantService)
    {
        $this->merchantService = $merchantService;
    }

    /**
     * Display a listing of the resource.
     */
    public function index(): View
    {
        $merchants = Merchant::with(['businessType', 'approvedBy'])->paginate(15);

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

    /**
     * Show the form for creating a new resource.
     */
    public function create(): View
    {
        // Assumir que há BusinessType model
        $businessTypes = BusinessType::all();

        return view('admin.merchants.create', compact('businessTypes'));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(StoreMerchantRequest $request): RedirectResponse
    {
        try {
            $this->merchantService->createMerchant($request->validated());

            return redirect()->route('merchants.index')
                ->with('success', 'Comerciante criado com sucesso. Aguardando aprovação.');
        } catch (\Exception $e) {
            return redirect()->back()
                ->withInput()
                ->with('error', 'Erro ao criar comerciante: '.$e->getMessage());
        }
    }

    /**
     * Display the specified resource.
     */
    public function show(Merchant $merchant): View
    {
        $merchant->load(['businessType', 'approvedBy', 'stalls', 'payments']);

        return view('admin.merchants.show', compact('merchant'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Merchant $merchant): View
    {
        $businessTypes = BusinessType::all();

        return view('admin.merchants.edit', compact('merchant', 'businessTypes'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(UpdateMerchantRequest $request, Merchant $merchant): RedirectResponse
    {
        try {
            $this->merchantService->updateMerchant($merchant->id, $request->validated());

            return redirect()->route('merchants.show', $merchant)
                ->with('success', 'Comerciante atualizado com sucesso.');
        } catch (\Exception $e) {
            return redirect()->back()
                ->withInput()
                ->with('error', 'Erro ao atualizar comerciante: '.$e->getMessage());
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Merchant $merchant): RedirectResponse
    {
        // Verificar se pode deletar (não tem pagamentos, etc.)
        if ($merchant->payments()->exists()) {
            return redirect()->back()
                ->with('error', 'Não é possível excluir comerciante com pagamentos registrados.');
        }

        $merchant->delete();

        return redirect()->route('merchants.index')
            ->with('success', 'Comerciante excluído com sucesso.');
    }

    /**
     * Aprovar comerciante
     */
    public function approve(Request $request, Merchant $merchant): RedirectResponse
    {
        $request->validate([
            'approved_by' => 'required|exists:users,id',
        ]);

        try {
            $this->merchantService->approveMerchant($merchant->id, $request->approved_by);

            return redirect()->route('merchants.show', $merchant)
                ->with('success', 'Comerciante aprovado com sucesso.');
        } catch (\Exception $e) {
            return redirect()->back()
                ->with('error', 'Erro ao aprovar comerciante: '.$e->getMessage());
        }
    }

    /**
     * Bloquear comerciante
     */
    public function block(Merchant $merchant): RedirectResponse
    {
        try {
            $this->merchantService->blockMerchant($merchant->id);

            return redirect()->route('merchants.show', $merchant)
                ->with('success', 'Comerciante bloqueado com sucesso.');
        } catch (\Exception $e) {
            return redirect()->back()
                ->with('error', 'Erro ao bloquear comerciante: '.$e->getMessage());
        }
    }

    /**
     * Desbloquear comerciante
     */
    public function unblock(Merchant $merchant): RedirectResponse
    {
        try {
            $this->merchantService->unblockMerchant($merchant->id);

            return redirect()->route('merchants.show', $merchant)
                ->with('success', 'Comerciante desbloqueado com sucesso.');
        } catch (\Exception $e) {
            return redirect()->back()
                ->with('error', 'Erro ao desbloquear comerciante: '.$e->getMessage());
        }
    }
}
