<?php

namespace App\Livewire\Debts;

use App\Models\Debt;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Livewire\Attributes\Layout;
use Livewire\Component;

#[Layout('layouts.dashboard')]
class Edit extends Component
{
    public Debt $debt;

    // Form fields
    public $due_date;
    public $notes;
    public $status;

    // Loading and feedback states
    public $loading = false;
    public $success = false;
    public $error = false;
    public $successMessage = '';
    public $errorMessage = '';

    public function mount(Debt $debt)
    {
        // Ensure debt belongs to current merchant
        // No merchant filtering needed for single-tenant app
        
        $this->debt = $debt;
        $this->due_date = $debt->due_date?->format('Y-m-d');
        $this->notes = $debt->notes;
        $this->status = $debt->status;
    }

    public function save()
    {
        $this->reset(['success', 'error', 'successMessage', 'errorMessage']);
        $this->loading = true;

        try {
            DB::transaction(function () {
                $this->debt->update([
                    'due_date' => $this->due_date ?: null,
                    'notes' => $this->notes,
                ]);
            });

            $this->success = true;
            $this->successMessage = 'Dette mise à jour avec succès.';
        } catch (\Exception $e) {
            $this->error = true;
            $this->errorMessage = 'Erreur lors de la mise à jour: ' . $e->getMessage();
        } finally {
            $this->loading = false;
        }
    }

    public function render(): \Illuminate\Contracts\View\View
    {
        $statusOptions = collect([
            (object) ['value' => Debt::STATUS_PENDING, 'label' => 'En attente'],
            (object) ['value' => Debt::STATUS_PARTIAL, 'label' => 'Partiellement payé'],
            (object) ['value' => Debt::STATUS_PAID, 'label' => 'Payé'],
        ]);

        return view('livewire.debts.edit', [
            'statusOptions' => $statusOptions,
        ]);
    }
}
