<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Facades\Auth;
use Spatie\Activitylog\LogOptions;
use Spatie\Activitylog\Traits\LogsActivity;

class OrderFinance extends Model
{
    use HasFactory, LogsActivity;

    protected $fillable = [
        'order_id',
        'order_requirement_id',
        'count',
        'capacity',
        'execution_duration',
        'company_name',
        'offer_price',
        'additional_fees',
        'operation_cost_percentage',
        'operation_cost',
        'created_by',
    ];

    protected $casts = [
        'count' => 'integer',
        'execution_duration' => 'integer',
        'offer_price' => 'decimal:2',
        'additional_fees' => 'decimal:2',
        'operation_cost_percentage' => 'decimal:2',
        'operation_cost' => 'decimal:2',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];

    protected $appends = [
        'approved_price',
        'expected_operation_cost',
    ];

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

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

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

    /**
     * Get the approved price (offer_price + additional_fees)
     * قيمة عرض السعر المعتمد
     */
    public function getApprovedPriceAttribute(): ?float
    {
        if ($this->offer_price === null || $this->additional_fees === null) {
            return null;
        }

        return $this->offer_price + $this->additional_fees;
    }

    /**
     * Get the expected operation cost ((approved_price * operation_cost_percentage) / 100)
     * قيمة وتكلفة التشغيل
     */
    public function getExpectedOperationCostAttribute(): ?float
    {
        if ($this->approved_price === null || $this->operation_cost_percentage === null) {
            return null;
        }

        return ($this->approved_price * $this->operation_cost_percentage) / 100;
    }

    protected static function booted(): void
    {
        static::creating(function (OrderFinance $orderFinance) {
            // Validate that the order_requirement belongs to the same order
            if ($orderFinance->order_requirement_id && $orderFinance->order_id) {
                $orderRequirement = OrderRequirement::find($orderFinance->order_requirement_id);
                if ($orderRequirement && $orderRequirement->order_id !== $orderFinance->order_id) {
                    throw new \InvalidArgumentException(
                        'The order requirement must belong to the same order as the order finance.'
                    );
                }
            }
        });

        static::updating(function (OrderFinance $orderFinance) {
            // Validate that the order_requirement belongs to the same order
            if ($orderFinance->order_requirement_id && $orderFinance->order_id) {
                $orderRequirement = OrderRequirement::find($orderFinance->order_requirement_id);
                if ($orderRequirement && $orderRequirement->order_id !== $orderFinance->order_id) {
                    throw new \InvalidArgumentException(
                        'The order requirement must belong to the same order as the order finance.'
                    );
                }
            }
        });
    }

    public function getActivitylogOptions(): LogOptions
    {
        return LogOptions::defaults()
            ->useLogName('order_finance');
    }

    /**
     * Boot the model
     */
    protected static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            if (Auth::check()) {
                $model->created_by = Auth::id();
            }
        });
    }
}
