<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Agency extends Model
{
    protected $table = 'agency';
    protected $primaryKey = 'Agency_ID';
    
    public $timestamps = false;

    protected $fillable = [
        'Agency_Name',
        'Tax_ID',
        'Address',
        'Address_Sent',
        'Address_Test',
        'Address_Eng',
        'Office_Number',
        'Web_Name',
        'CusIns_ID',
        'CusUdp_ID',
        'DtmIns',
        'DtmUdp',
        'active',
        'Note',
        'Edit_Agency',
        'New_Agency'
    ];

    protected $casts = [
        'DtmIns' => 'datetime',
        'DtmUdp' => 'datetime',
        'active' => 'boolean',
    ];

    // Relationships
    public function customers()
    {
        return $this->hasMany(Customer::class, 'Agency_ID', 'Agency_ID');
    }

    public function customersMany()
    {
        return $this->belongsToMany(Customer::class, 'agency_customer', 'Agency_ID', 'Customer_ID');
    }

    // Accessors
    public function getNameAttribute()
    {
        return $this->Agency_Name;
    }

    // Mutators
    public function setNameAttribute($value)
    {
        $this->Agency_Name = $value;
    }

    // Scopes
    public function scopeByName($query, $name)
    {
        return $query->whereRaw('LOWER(Agency_Name) = ?', [strtolower($name)]);
    }

    public function scopeByNameLike($query, $name)
    {
        return $query->whereRaw('LOWER(Agency_Name) LIKE ?', ['%' . strtolower($name) . '%']);
    }

    // Static methods
    public static function findByName($name)
    {
        return static::whereRaw('LOWER(Agency_Name) = ?', [strtolower($name)])->first();
    }

    public static function findByNameLike($name)
    {
        return static::whereRaw('LOWER(Agency_Name) LIKE ?', ['%' . strtolower($name) . '%'])->get();
    }
}
