<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class DebtPayment extends Model
{
    protected $guarded = [];

    // --- FITUR OTOMATIS: ISI BRANCH_ID ---
    protected static function booted()
    {
        static::creating(function ($payment) {
            // Jika branch_id sudah diisi manual, biarkan.
            if (!empty($payment->branch_id)) return;

            // 1. Jika ini Pembayaran ke Supplier (Purchase)
            if (!empty($payment->purchase_id)) {
                $purchase = Purchase::find($payment->purchase_id);
                if ($purchase) {
                    $payment->branch_id = $purchase->branch_id;
                }
            }

            // 2. Jika ini Pembayaran dari Pelanggan (Sale)
            if (!empty($payment->sale_id)) {
                $sale = Sale::find($payment->sale_id);
                if ($sale) {
                    $payment->branch_id = $sale->branch_id;
                }
            }
            
            // 3. Fallback terakhir (jika masih kosong, pakai user login)
            if (empty($payment->branch_id) && auth()->check()) {
                $payment->branch_id = auth()->user()->branch_id;
            }
        });
    }
    // -------------------------------------

    public function sale(): BelongsTo
    {
        return $this->belongsTo(Sale::class);
    }

    public function purchase(): BelongsTo
    {
        return $this->belongsTo(Purchase::class);
    }

    public function branch(): BelongsTo
    {
        return $this->belongsTo(Branch::class);
    }

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }
}