<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class productQuotationMaster extends BaseModel
{
    use HasFactory;

    protected $fillable = [
        'date', 'customer_id', 'product_quotation_setting_id', 'quotation_number', 'delivery_lead_time', 'validity_period', 'payment_term', 'tax_exclude_include', 'approval_status',
    ];

    protected static function boot()
    {
        parent::boot(); // always call the parent boot

        static::addGlobalScope('typeScope', function ($builder) {
            if (auth()->check() && auth()->user()->shop_id != null) {
                $builder->where('transition_location_id', auth()->user()->shop_id);
            }
        });

        static::creating(function ($model) {
            if (auth()->check()) {
                $user = auth()->user();
                $model->transition_location_id = $user->shop_id;
                $model->transition_create_by = $user->id;
            }
        });

        static::updating(function ($model) {
            if (auth()->check()) {
                $model->transition_update_by = auth()->id(); // use user ID here
            }
        });

        // Delete associated documents when quotation is deleted
        static::deleting(function ($quotation) {
            foreach ($quotation->documents as $document) {
                // Delete physical file
                $filePath = public_path($document->file_path);
                if (file_exists($filePath)) {
                    unlink($filePath);
                }
                // Delete database record
                $document->delete();
            }
        });
    }

    public function productQuotationDetails()
    {
        return $this->hasMany(productQuotationDetails::class, 'product_quotation_master_id')->with('product', 'attribute');
    }

    public function productQuotationSetting()
    {
        return $this->belongsTo(ProductQuotationSetting::class, 'product_quotation_setting_id');
    }

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

    /**
     * Get all documents for this quotation.
     */
    public function documents()
    {
        return $this->morphMany(Document::class, 'documentable');
    }

    /**
     * Get the approval for this quotation (singular - latest or current).
     */
    public function approval()
    {
        return $this->morphOne(Approval::class, 'approvable')->latestOfMany();
    }

    /**
     * Get all approvals for this quotation.
     */
    public function approvals()
    {
        return $this->morphMany(Approval::class, 'approvable');
    }
}
