<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\AuditLog;
use App\Models\Cobranca;
use App\Models\Contrato;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class FinanceiroController extends Controller
{
    public function index(Request $request)
    {
        $query = Cobranca::with('contrato')->latest('mes_referencia');

        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }
        if ($request->filled('contrato_id')) {
            $query->where('contrato_id', $request->contrato_id);
        }
        if ($request->filled('mes')) {
            $query->whereYear('mes_referencia', substr($request->mes, 0, 4))
                  ->whereMonth('mes_referencia', substr($request->mes, 5, 2));
        }

        // Atualiza vencidas automaticamente
        Cobranca::where('status', 'pendente')
            ->where('mes_referencia', '<', now()->startOfMonth())
            ->update(['status' => 'vencido']);

        $cobrancas = $query->paginate(30)->withQueryString();
        $contratos = Contrato::where('status_workflow', 'Ativo')->orderBy('razao_social')->get();

        $stats = [
            'total_mes'   => Cobranca::whereYear('mes_referencia', now()->year)
                                     ->whereMonth('mes_referencia', now()->month)
                                     ->sum('valor'),
            'a_receber'   => Cobranca::whereIn('status', ['pendente', 'vencido'])->sum('valor'),
            'recebido_mes'=> Cobranca::where('status', 'pago')
                                     ->whereMonth('pago_em', now()->month)
                                     ->whereYear('pago_em', now()->year)
                                     ->sum('valor'),
            'vencidas'    => Cobranca::where('status', 'vencido')->count(),
        ];

        return view('pages.admin.financeiro', compact('cobrancas', 'contratos', 'stats'));
    }

    public function store(Request $request): JsonResponse
    {
        $data = $request->validate([
            'contrato_id'    => 'required|exists:contratos,id',
            'mes_referencia' => 'required|date_format:Y-m',
            'valor'          => 'required|numeric|min:0',
            'observacoes'    => 'nullable|string|max:500',
        ]);

        $data['mes_referencia'] .= '-01';
        $cobranca = Cobranca::create($data);

        AuditLog::record('financeiro.criado', "Cobrança criada: R$ {$cobranca->valor} ref. {$cobranca->mes_referencia->format('m/Y')}", $cobranca);

        return response()->json(['ok' => true, 'id' => $cobranca->id]);
    }

    public function marcarPago(Cobranca $cobranca): JsonResponse
    {
        $cobranca->marcarPago();
        AuditLog::record('financeiro.pago', "Cobrança marcada como paga: R$ {$cobranca->valor}", $cobranca);

        return response()->json(['ok' => true]);
    }

    public function gerarMes(Request $request): JsonResponse
    {
        $mes = $request->input('mes', now()->format('Y-m')) . '-01';

        $contratos = Contrato::where('status_workflow', 'Ativo')
            ->where('honorario', '>', 0)
            ->get();

        $criadas = 0;
        foreach ($contratos as $c) {
            $cob = Cobranca::gerarParaContrato($c, $mes);
            if ($cob->wasRecentlyCreated) $criadas++;
        }

        AuditLog::record('financeiro.geracao', "Geradas {$criadas} cobranças para " . substr($mes, 0, 7));

        return response()->json(['ok' => true, 'criadas' => $criadas]);
    }

    public function destroy(Cobranca $cobranca): JsonResponse
    {
        $cobranca->delete();
        return response()->json(['ok' => true]);
    }
}
