<?php

namespace App\Http\Controllers;

use App\Models\Debt;
use App\Models\DebtPayment;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class DebtController extends Controller
{
    /**
     * Update the specified debt.
     */
    public function update(Request $request, Debt $debt)
    {
        // Ensure debt belongs to current merchant
        // No merchant filtering needed for single-tenant app

        $request->validate([
            'due_date' => 'nullable|date',
            'notes' => 'nullable|string|max:1000',
            'status' => 'required|in:pending,partial,paid',
        ]);

        try {
            DB::transaction(function () use ($request, $debt) {
                $debt->update([
                    'due_date' => $request->due_date,
                    'notes' => $request->notes,
                    'status' => $request->status,
                ]);
            });

            return redirect()->route('debts.show', $debt)
                ->with('success', 'Dette mise à jour avec succès.');
        } catch (\Exception $e) {
            return redirect()->back()
                ->with('error', 'Erreur lors de la mise à jour: ' . $e->getMessage())
                ->withInput();
        }
    }

    /**
     * Add a payment to the specified debt.
     */
    public function addPayment(Request $request, Debt $debt)
    {
        // Ensure debt belongs to current merchant
        // No merchant filtering needed for single-tenant app

        $request->validate([
            'amount' => 'required|numeric|min:0.01|max:' . $debt->remaining_amount,
            'payment_method' => 'required|in:cash,bank_transfer,mobile_money,other',
            'payment_date' => 'required|date|before_or_equal:today',
            'reference' => 'nullable|string|max:255',
            'notes' => 'nullable|string|max:1000',
        ]);

        try {
            DB::transaction(function () use ($request, $debt) {
                // Create the payment
                $payment = $debt->payments()->create([
                    'user_id' => Auth::id(),
                    'amount' => $request->amount,
                    'payment_date' => $request->payment_date,
                    'payment_method' => $request->payment_method,
                    'reference' => $request->reference,
                    'notes' => $request->notes,
                ]);

                // Update debt amounts and status
                $debt->paid_amount += $request->amount;
                $debt->updateStatus();
            });

            return redirect()->route('debts.show', $debt)
                ->with('success', 'Paiement enregistré avec succès.');
        } catch (\Exception $e) {
            return redirect()->back()
                ->with('error', 'Erreur lors de l\'enregistrement du paiement: ' . $e->getMessage())
                ->withInput();
        }
    }

    /**
     * Remove the specified debt from storage.
     */
    public function destroy(Debt $debt)
    {
        // Ensure debt belongs to current merchant
        // No merchant filtering needed for single-tenant app

        // Only allow deletion if no payments have been made
        if ($debt->paid_amount > 0) {
            return redirect()->back()
                ->with('error', 'Impossible de supprimer une dette qui a des paiements enregistrés.');
        }

        try {
            DB::transaction(function () use ($debt) {
                $debt->delete();
            });

            return redirect()->route('debts.index')
                ->with('success', 'Dette supprimée avec succès.');
        } catch (\Exception $e) {
            return redirect()->back()
                ->with('error', 'Erreur lors de la suppression: ' . $e->getMessage());
        }
    }
}
