<?php

namespace App\Http\Controllers;

use App\Models\BusinessDebt;
use Illuminate\Http\Request;

class DebtController extends Controller
{
    /**
     * Display a listing of business debts.
     */
    public function index()
    {
        $debts = BusinessDebt::latest('due_date')->get();
        return view('debts.index', compact('debts'));
    }

    /**
     * Show the form for creating a new debt.
     */
    public function create()
    {
        return view('debts.create');
    }

    /**
     * Store a newly created business debt and its installments.
     */
    public function store(Request $request)
    {
        $request->validate([
            'provider_name'      => 'required|string|max:255',
            'description'        => 'nullable|string',
            'total_amount'       => 'required|numeric|min:0',
            'due_date'           => 'required|date', // Initial due date (first installment)
            'installments'       => 'required|integer|min:1',
            'frequency'          => 'required|in:diario,semanal,quincenal,mensual',
        ]);

        try {
            DB::beginTransaction();

            $debt = BusinessDebt::create([
                'provider_name'      => $request->provider_name,
                'description'        => $request->description,
                'total_amount'       => $request->total_amount,
                'remaining_balance'  => $request->total_amount,
                'due_date'           => $request->due_date,
                'total_installments' => $request->installments,
                'frequency'          => $request->frequency,
                'status'             => 'pending',
            ]);

            // Generate installments
            $this->generateInstallments($debt, $request->installments, $request->frequency, $request->due_date, $request->total_amount);

            DB::commit();

            return redirect()->route('debts.index')->with('success', 'Deuda y cronograma de cuotas registrados con éxito.');
        } catch (\Exception $e) {
            DB::rollBack();
            return back()->with('error', 'Error al registrar la deuda: ' . $e->getMessage());
        }
    }

    /**
     * Internal: Helper to generate installment records.
     */
    private function generateInstallments($debt, $count, $frequency, $startDate, $totalAmount)
    {
        $installmentAmount = $totalAmount / $count;
        $currentDate       = \Carbon\Carbon::parse($startDate);

        for ($i = 1; $i <= $count; $i++) {
            $debt->installments()->create([
                'installment_number' => $i,
                'amount'             => $installmentAmount,
                'due_date'           => $currentDate->copy(),
                'status'             => 'pending',
            ]);

            // Avanzar fecha según frecuencia
            switch ($frequency) {
                case 'diario':
                    $currentDate->addDay();
                    break;
                case 'semanal':
                    $currentDate->addWeek();
                    break;
                case 'quincenal':
                    $currentDate->addDays(15);
                    break;
                case 'mensual':
                    $currentDate->addMonth();
                    break;
            }
        }
    }

    /**
     * Display the installment schedule of a debt.
     */
    public function installments(BusinessDebt $debt)
    {
        $installments = $debt->installments()->orderBy('installment_number')->get();
        return view('debts.installments', compact('debt', 'installments'));
    }

    /**
     * AJAX/POST: Update an installment status.
     */
    public function payInstallment(\App\Models\BusinessDebtInstallment $installment)
    {
        if ($installment->status === 'paid') {
            return back()->with('error', 'Esta cuota ya ha sido pagada.');
        }

        try {
            DB::beginTransaction();

            $installment->update(['status' => 'paid']);
            $debt = $installment->businessDebt;
            $debt->decrement('remaining_balance', $installment->amount);

            if ($debt->remaining_balance <= 0) {
                $debt->update(['status' => 'paid']);
            }

            DB::commit();

            return back()->with('success', 'Cuota pagada con éxito.');
        } catch (\Exception $e) {
            DB::rollBack();
            return back()->with('error', 'Error al procesar el pago.');
        }
    }

    /**
     * Update the debt status or record a payment.
     */
    public function update(Request $request, BusinessDebt $debt)
    {
        $request->validate([
            'amount' => 'required|numeric|min:0.01|max:' . $debt->remaining_balance,
        ]);

        $debt->decrement('remaining_balance', $request->amount);

        if ($debt->remaining_balance <= 0) {
            $debt->update(['status' => 'paid']);
        }

        return redirect()->route('debts.index')->with('success', 'Pago registrado. Pendiente: S/ ' . number_format($debt->remaining_balance, 2));
    }

    /**
     * Remove the specified debt from storage.
     */
    public function destroy(BusinessDebt $debt)
    {
        $debt->delete();
        return redirect()->route('debts.index')->with('success', 'Deuda eliminada del sistema.');
    }
}
