<?php

namespace App\Modules\PLATFORM\Settings\Models;

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

class Company extends Model
{
    use HasFactory;

    protected $table = 'companies';

    protected $fillable = [
        'company_code',
        'legal_name',
        'display_name',
        'registration_number',
        'tax_number',
        'industry_type',
        'company_type',
        'base_currency_id',
        'fiscal_year_start',
        'time_zone_id',
        'address_line1',
        'address_line2',
        'city_id',
        'postal_code',
        'originating_bank',
        'originating_branch',
        'originating_account',
        'originating_account_name',
        'epf_reg_no',
        'zone_code',
        'status',
        'api_key',
        'external_id',
        'enabled_modules',
        'modules_synced_at',
        'logo',
    ];

    protected $casts = [
        'fiscal_year_start' => 'date',
        'status' => 'boolean',
        'enabled_modules' => 'array',
        'modules_synced_at' => 'datetime',
    ];

    /* ================= Relationships ================= */

    public function baseCurrency()
    {
        return $this->belongsTo(Currency::class, 'base_currency_id');
    }

    public function timeZone()
    {
        return $this->belongsTo(TimeZone::class);
    }

    public function city()
    {
        return $this->belongsTo(City::class);
    }

    /* ================= Module Methods ================= */

    /**
     * Check if the company has access to a specific module.
     */
    public function hasModule(string $module): bool
    {
        $modules = $this->enabled_modules;

        if (is_string($modules)) {
            $modules = json_decode($modules, true);
        }
        return in_array($module, $modules, true);
    }


    /**
     * Sync enabled modules from external API.
     */
    public function syncModulesFromApi(array $modules): void
    {
        $this->update([
            'enabled_modules' => $modules,
            'modules_synced_at' => now(),
        ]);
    }
}
