<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class GrantDepartmentMapping extends Model
{
    use SoftDeletes;

    protected $table = 'grant_department_mapping';
    protected $primaryKey = 'GDM_Id';

    protected $fillable = ['Dept_Id', 'GT_Id', 'Status'];

    protected $casts = [
        'GT_Id' => 'array'
    ];

    public function department()
    {
        return $this->belongsTo(Department::class, 'Dept_Id', 'Dpt_id');
    }

    /**
     * ✅ Get all grant types (same as budgetHeads)
     */
    public function grantTypes()
    {
        if (empty($this->GT_Id)) {
            return collect();
        }

        return \App\Models\GrantTypeMaster::whereIn('GT_Id', $this->GT_Id)->get();
    }

    /**
     * ✅ First Grant Type
     */
    public function getFirstGrantTypeAttribute()
    {
        if (!empty($this->GT_Id)) {
            return \App\Models\GrantTypeMaster::find($this->GT_Id[0] ?? null);
        }

        return null;
    }

    /**
     * ✅ Add GT_Id
     */
    public function addGTId($gtId)
    {
        $ids = $this->GT_Id ?? [];

        if (!in_array($gtId, $ids)) {
            $ids[] = $gtId;
            $this->GT_Id = $ids;
            return $this->save();
        }

        return false;
    }

    /**
     * ✅ Remove GT_Id
     */
    public function removeGTId($gtId)
    {
        $ids = $this->GT_Id ?? [];

        $index = array_search($gtId, $ids);

        if ($index !== false) {
            unset($ids[$index]);
            $this->GT_Id = array_values($ids);
            return $this->save();
        }

        return false;
    }

    public function hasGTId($gtId)
    {
        return in_array($gtId, $this->GT_Id ?? []);
    }
}
