<?php

namespace App\Http\Controllers\Web\Admin;

use App\Http\Controllers\Controller;
use App\Models\Market;
use App\Models\Neighborhood;
use App\Models\Fiscal;
use App\Models\Province;
use App\Models\Municipality;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Illuminate\Http\RedirectResponse;

class MercadosController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(): View
    {
        $provinces = Province::orderBy('name')->get();
        $municipalities = Municipality::orderBy('name')->get();

        return view('admin.mercado.mercados.index', compact('provinces', 'municipalities'));
    }

    /**
     * Get table data for DataTables Server-side
     */
    public function getTableData(Request $request)
    {
        $columns = ['name', 'location', 'status', 'capacity', 'contact_phone', 'id'];

        $query = Market::query()->with(['neighborhood.municipality.province']);

        // Filtros
        if ($request->filled('province_id')) {
            $query->whereHas('neighborhood.municipality.province',
                fn($q) => $q->where('provinces.id', $request->province_id));
        }

        if ($request->filled('municipality_id')) {
            $query->whereHas('neighborhood.municipality',
                fn($q) => $q->where('municipalities.id', $request->municipality_id));
        }

        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        if ($request->filled('search') && !empty($request->search['value'])) {
            $search = $request->search['value'];
            $query->where(function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                  ->orWhere('location', 'like', "%{$search}%")
                  ->orWhere('contact_phone', 'like', "%{$search}%")
                  ->orWhere('contact_email', 'like', "%{$search}%");
            });
        }

        // Ordenação
        if ($request->has('order')) {
            $orderColumn = $columns[$request->order[0]['column']] ?? 'name';
            $orderDirection = $request->order[0]['dir'] ?? 'asc';
            $query->orderBy($orderColumn, $orderDirection);
        } else {
            $query->orderBy('name', 'asc');
        }

        $totalRecords = $query->count();
        $start = $request->input('start', 0);
        $length = $request->input('length', 15);
        $mercados = $query->skip($start)->take($length)->get();

        $data = [];
        foreach ($mercados as $mercado) {
            $statusClasses = [
                'active' => 'badge-success',
                'inactive' => 'badge-danger',
            ];
            $statusTexts = [
                'active' => 'Ativo',
                'inactive' => 'Inativo',
            ];

            $data[] = [
                'name' => $mercado->name,
                'location' => $mercado->location,
                'province' => $mercado->neighborhood->municipality->province->name ?? '-',
                'municipality' => $mercado->neighborhood->municipality->name ?? '-',
                'status' => sprintf(
                    '<span class="badge %s"><i class="fas %s"></i> %s</span>',
                    $statusClasses[$mercado->status] ?? 'badge-neutral',
                    $mercado->status === 'active' ? 'fa-check-circle' : 'fa-ban',
                    $statusTexts[$mercado->status] ?? $mercado->status
                ),
                'capacity' => $mercado->capacity ?? '-',
                'occupation_rate' => $mercado->occupation_rate . '%',
                'actions' => $this->getActionButtons($mercado),
            ];
        }

        return response()->json([
            'draw' => intval($request->draw),
            'recordsTotal' => $totalRecords,
            'recordsFiltered' => $totalRecords,
            'data' => $data,
        ]);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create(): View
    {
        $provinces = Province::with('municipalities.neighborhoods')->orderBy('name')->get();

        return view('admin.mercado.mercados.create', compact('provinces'));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request): RedirectResponse
    {
        $validated = $request->validate([
            'neighborhood_id' => 'required|exists:neighborhoods,id',
            'name' => 'required|string|max:255',
            'location' => 'required|string|max:255',
            'address' => 'nullable|string',
            'capacity' => 'nullable|integer|min:0',
            'contact_phone' => 'nullable|string|max:50',
            'contact_email' => 'nullable|email|max:255',
            'administration' => 'nullable|array',
            'status' => 'required|in:active,inactive',
            'metadata' => 'nullable|array',
        ]);

        $mercado = Market::create($validated);

        return redirect()->route('mercado.mercados.show', $mercado)
            ->with('success', 'Mercado criado com sucesso.');
    }

    /**
     * Display the specified resource.
     */
    public function show(Market $mercado): View
    {
        $mercado->load(['neighborhood.municipality.province', 'stalls']);

        // Contagem de fiscais ativos - especificando a tabela correta
        $activeFiscals = $mercado->fiscals()
            ->where('fiscals.status', 'active')
            ->count();

        $statistics = [
            'total_stalls' => $mercado->stalls()->count(),
            'occupied_stalls' => $mercado->stalls()->where('status', 'occupied')->count(),
            'available_stalls' => $mercado->stalls()->where('status', 'available')->count(),
            'maintenance_stalls' => $mercado->stalls()->where('status', 'maintenance')->count(),
            'occupation_rate' => $mercado->occupation_rate,
            'active_fiscals' => $activeFiscals,
            'monthly_revenue' => $mercado->stalls()->sum('monthly_fee'),
        ];

        return view('admin.mercado.mercados.show', compact('mercado', 'statistics'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Market $mercado): View
    {
        $provinces = Province::with('municipalities.neighborhoods')->orderBy('name')->get();
        $mercado->load(['neighborhood.municipality.province']);

        return view('admin.mercado.mercados.edit', compact('mercado', 'provinces'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, Market $mercado): RedirectResponse
    {
        $validated = $request->validate([
            'neighborhood_id' => 'required|exists:neighborhoods,id',
            'name' => 'required|string|max:255',
            'location' => 'required|string|max:255',
            'address' => 'nullable|string',
            'capacity' => 'nullable|integer|min:0',
            'contact_phone' => 'nullable|string|max:50',
            'contact_email' => 'nullable|email|max:255',
            'administration' => 'nullable|array',
            'status' => 'required|in:active,inactive',
            'metadata' => 'nullable|array',
        ]);

        $mercado->update($validated);

        return redirect()->route('mercado.mercados.show', $mercado)
            ->with('success', 'Mercado atualizado com sucesso.');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Market $mercado): RedirectResponse
    {
        // Verificar se existem bancadas associadas
        if ($mercado->stalls()->count() > 0) {
            return redirect()->back()
                ->with('error', 'Não é possível excluir um mercado que possui bancadas.');
        }

        $mercado->delete();

        return redirect()->route('mercado.mercados.index')
            ->with('success', 'Mercado removido com sucesso.');
    }

    /**
     * Activate market
     */
    public function activate(Market $mercado): RedirectResponse
    {
        $mercado->update(['status' => 'active']);

        return redirect()->back()->with('success', 'Mercado ativado com sucesso.');
    }

    /**
     * Inactivate market
     */
    public function inactivate(Market $mercado): RedirectResponse
    {
        $mercado->update(['status' => 'inactive']);

        return redirect()->back()->with('success', 'Mercado inativado com sucesso.');
    }

    /**
     * Get fiscals assigned to market
     */
    public function fiscais(Market $mercado): View
    {
        $fiscais = $mercado->fiscals()->paginate(15);
        $availableFiscals = Fiscal::where('status', 'active')
            ->whereDoesntHave('markets', fn($q) => $q->where('market_id', $mercado->id))
            ->get();

        return view('admin.mercado.mercados.fiscais', compact('mercado', 'fiscais', 'availableFiscals'));
    }

    /**
     * Assign fiscal to market
     */
    public function assignFiscal(Request $request, Market $mercado): RedirectResponse
    {
        $request->validate([
            'fiscal_id' => 'required|exists:fiscals,id',
            'primary_fiscal' => 'boolean',
            'assigned_zones' => 'nullable|array',
            'start_date' => 'required|date',
            'end_date' => 'nullable|date|after:start_date',
        ]);

        $mercado->fiscals()->attach($request->fiscal_id, [
            'assigned_zones' => json_encode($request->assigned_zones ?? []),
            'primary_fiscal' => $request->primary_fiscal ?? false,
            'start_date' => $request->start_date,
            'end_date' => $request->end_date,
            'status' => 'active',
            'assigned_by' => auth()->id(),
        ]);

        return redirect()->back()->with('success', 'Fiscal atribuído com sucesso.');
    }

    /**
     * Remove fiscal from market
     */
    public function removeFiscal(Request $request, Market $mercado): RedirectResponse
    {
        $request->validate([
            'fiscal_id' => 'required|exists:fiscals,id',
        ]);

        $mercado->fiscals()->updateExistingPivot($request->fiscal_id, [
            'status' => 'inactive',
            'end_date' => now(),
        ]);

        return redirect()->back()->with('success', 'Fiscal removido com sucesso.');
    }

    /**
     * Get market statistics
     */
    /**
 * Get market statistics
 */
public function statistics(Market $mercado, Request $request): View
{
    $year = $request->get('year', date('Y'));

    // Dados mensais para o gráfico (exemplo - ajuste conforme sua estrutura)
    $monthlyRevenue = [];
    for ($month = 1; $month <= 12; $month++) {
        // Buscar receita por mês (ajuste conforme sua tabela de pagamentos)
        $revenue = \App\Models\Payment::whereHas('merchant.stalls', function($q) use ($mercado) {
                $q->where('market_id', $mercado->id);
            })
            ->whereYear('payment_date', $year)
            ->whereMonth('payment_date', $month)
            ->sum('amount');
        $monthlyRevenue[] = $revenue;
    }

    // Top comerciantes (exemplo)
    $topMerchants = \App\Models\Merchant::whereHas('stalls', function($q) use ($mercado) {
            $q->where('market_id', $mercado->id);
        })
        ->withSum(['payments' => function($q) use ($year) {
            $q->whereYear('payment_date', $year);
        }], 'amount')
        ->orderBy('payments_sum_amount', 'desc')
        ->limit(5)
        ->get()
        ->map(fn($m) => ['name' => $m->full_name, 'total' => $m->payments_sum_amount ?? 0]);

    // Top fiscais (exemplo)
    $topFiscals = \App\Models\Fiscal::whereHas('payments', function($q) use ($mercado, $year) {
            $q->whereHas('merchant.stalls', fn($sq) => $sq->where('market_id', $mercado->id))
              ->whereYear('payment_date', $year);
        })
        ->withSum(['payments' => function($q) use ($mercado, $year) {
            $q->whereHas('merchant.stalls', fn($sq) => $sq->where('market_id', $mercado->id))
              ->whereYear('payment_date', $year);
        }], 'amount')
        ->orderBy('payments_sum_amount', 'desc')
        ->limit(5)
        ->get()
        ->map(fn($f) => ['name' => $f->full_name, 'total' => $f->payments_sum_amount ?? 0]);

    $stats = [
        'total_stalls' => $mercado->stalls()->count(),
        'occupied_stalls' => $mercado->stalls()->where('status', 'occupied')->count(),
        'available_stalls' => $mercado->stalls()->where('status', 'available')->count(),
        'maintenance_stalls' => $mercado->stalls()->where('status', 'maintenance')->count(),
        'occupation_rate' => $mercado->occupation_rate,
        'total_merchants' => $mercado->merchants()->count(),
        'total_fiscals' => $mercado->fiscals()->count(),
        'monthly_revenue' => array_sum($monthlyRevenue),
    ];

    return view('admin.mercado.mercados.statistics', compact('mercado', 'stats', 'monthlyRevenue', 'topMerchants', 'topFiscals', 'year'));
}

    /**
     * Get stalls from market
     */
    public function bancadas(Market $mercado): View
    {
        $stalls = $mercado->stalls()->with('merchant')->paginate(15);

        return view('admin.mercado.mercados.bancadas', compact('mercado', 'stalls'));
    }

    /**
     * Get merchants from market
     */
    public function comerciantes(Market $mercado): View
    {
        $merchants = $mercado->merchants()->paginate(15);

        return view('admin.mercado.mercados.comerciantes', compact('mercado', 'merchants'));
    }

    private function getActionButtons($mercado): string
    {
        $buttons = '<div class="d-flex gap-1 justify-content-center">';
        $buttons .= '<a href="' . route('mercado.mercados.show', $mercado) . '" class="btn-action btn-view" title="Ver Detalhes"><i class="fas fa-eye"></i></a>';
        $buttons .= '<a href="' . route('mercado.mercados.edit', $mercado) . '" class="btn-action btn-edit" title="Editar"><i class="fas fa-edit"></i></a>';
        $buttons .= '<a href="' . route('mercado.mercados.fiscais', $mercado) . '" class="btn-action btn-primary" title="Fiscais"><i class="fas fa-user-shield"></i></a>';
        $buttons .= '<a href="' . route('mercado.mercados.statistics', $mercado) . '" class="btn-action btn-info" title="Estatísticas"><i class="fas fa-chart-bar"></i></a>';

        if ($mercado->status === 'active') {
            $buttons .= '<form action="' . route('mercado.mercados.inactivate', $mercado) . '" method="POST" class="d-inline">';
            $buttons .= csrf_field();
            $buttons .= '<button type="submit" class="btn-action btn-warning" title="Inativar"><i class="fas fa-ban"></i></button>';
            $buttons .= '</form>';
        } else {
            $buttons .= '<form action="' . route('mercado.mercados.activate', $mercado) . '" method="POST" class="d-inline">';
            $buttons .= csrf_field();
            $buttons .= '<button type="submit" class="btn-action btn-success" title="Ativar"><i class="fas fa-check-circle"></i></button>';
            $buttons .= '</form>';
        }

        $buttons .= '<form action="' . route('mercado.mercados.destroy', $mercado) . '" method="POST" class="d-inline" onsubmit="return confirm(\'Remover este mercado?\')">';
        $buttons .= csrf_field();
        $buttons .= method_field('DELETE');
        $buttons .= '<button type="submit" class="btn-action btn-delete" title="Remover"><i class="fas fa-trash"></i></button>';
        $buttons .= '</form></div>';

        return $buttons;
    }
}
