<?php

namespace App\Models;

use App\Enums\Currency;
use App\Enums\PaymentStatus;
use App\Enums\SaleOrigin;
use App\Enums\SaleType;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Spatie\Activitylog\LogOptions;
use Spatie\Activitylog\Traits\LogsActivity;

class Sale extends Model
{
    use HasFactory, LogsActivity;

    protected $fillable = [
        'client_id',
        'owner_user_id',
        'seller_user_id',
        'created_by_user_id',
        'origin',
        'sale_type',
        'title',
        'description',
        'sale_date',
        'currency',
        'fixed_amount',
        'hourly_rate',
        'hours_quantity',
        'gross_amount',
        'platform_fee',
        'sales_commission_pct',
        'collected_amount_cached',
        'payment_status',
        'expected_collect_date',
        'expected_collect_note',
        'last_follow_up_date',
        'follow_up_note',
        'external_source',
        'external_id',
    ];

    protected function casts(): array
    {
        return [
            'origin'         => SaleOrigin::class,
            'sale_type'      => SaleType::class,
            'currency'       => Currency::class,
            'payment_status' => PaymentStatus::class,
            'sale_date'                => 'date',
            'expected_collect_date'    => 'date',
            'last_follow_up_date'      => 'date',
            'fixed_amount'             => 'decimal:2',
            'hourly_rate'              => 'decimal:2',
            'hours_quantity'           => 'decimal:2',
            'gross_amount'             => 'decimal:2',
            'platform_fee'             => 'decimal:2',
            'sales_commission_pct'     => 'decimal:2',
            'collected_amount_cached'  => 'decimal:2',
        ];
    }

    public function getActivitylogOptions(): LogOptions
    {
        return LogOptions::defaults()
            ->logFillable()
            ->logOnlyDirty()
            ->dontSubmitEmptyLogs();
    }

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

    public function owner(): BelongsTo
    {
        return $this->belongsTo(User::class, 'owner_user_id');
    }

    public function seller(): BelongsTo
    {
        return $this->belongsTo(User::class, 'seller_user_id');
    }

    public function createdBy(): BelongsTo
    {
        return $this->belongsTo(User::class, 'created_by_user_id');
    }

    public function payments(): HasMany
    {
        return $this->hasMany(Payment::class);
    }

    // Neto esperado a cobrar (descontando fee de plataforma)
    public function getNetExpectedAttribute(): float
    {
        return (float) $this->gross_amount - (float) $this->platform_fee;
    }

    // Saldo pendiente de cobro (sobre el neto esperado)
    public function getBalanceAttribute(): float
    {
        return $this->net_expected - (float) $this->collected_amount_cached;
    }

    // Días de antigüedad desde la venta
    public function getAgingDaysAttribute(): int
    {
        return (int) now()->diffInDays($this->sale_date, false) * -1;
    }

    // % de comisión efectivo (el de la venta o el default de configuración)
    public function getEffectiveSalesCommissionPctAttribute(): float
    {
        if ($this->sales_commission_pct !== null) {
            return (float) $this->sales_commission_pct;
        }
        return (float) SystemSetting::current()->sales_commission_pct;
    }
}
