<?php

namespace App\Models;

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

class RequisitionMaster extends BaseModel
{
    use HasFactory;

    protected $guarded = [];

    public function RequsitionDetailes()
    {
        return $this->hasMany(RequisitionDetailes::class, 'requisition_masters_id', 'id')->with('attribute');
    }

    public function shop()
    {
        return $this->hasOne(Warehouse::class, 'id', 'shop_id');
    }

    public function toLocation()
    {
        return $this->hasOne(Warehouse::class, 'id', 'location_id');
    }

    public function user()
    {
        return $this->belongsTo(User::class, 'created_by', 'id');
    }
    public function client()
    {
        return $this->hasOne(Client::class, 'id', 'client_id');
    }

    public function branch()
    {
        return $this->hasOne(CustomerBranch::class, 'id', 'branch_id');
    }

    public function department()
    {
        return $this->hasOne(Department::class, 'id', 'department_id');
    }

    public function contactPerson()
    {
        return $this->hasOne(ClientContactPerson::class, 'id', 'contact_person_id');
    }

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

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

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

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

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

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