<?php

/**
 * Currency Model
 *
 * @author Andrew Morgan <andrew.morgan@mtcmedia.co.uk>
 */

namespace Mtc\Core;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;

/**
 * Currency Model
 *
 * @author Andrew Morgan <andrew.morgan@mtcmedia.co.uk>
 */
class Currency extends Model
{
    /**
     * @var string Model table name
     */
    protected $table = 'currencies';

    /**
     * @var array|bool DateTime columns for object
     */
    public $timestamps = false;

    /**
     * @var array The attributes that are mass assignable.
     */
    protected $fillable = [
        'currency',
        'ratio',
        'enabled',
        'symbol',
        'name',
        'country_code',
    ];

    /**
     * Scope - active()
     *
     * @param \Illuminate\Database\Eloquent\Builder $query Query builder object
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public static function scopeActive($query)
    {
        return $query->orderBy('name')->where('enabled', 1);
    }

    /**
     * getEnabledCurrencies()
     * Return all enabled currencies
     *
     * @return array Enabled currencies keyed by currency code (GBP etc.)
     */
    public static function getEnabledCurrencies(): array
    {
        return Cache::remember('currencies:enabled', now()->addHours(12), static function () {
            return self::active()
                ->get()
                ->keyBy('currency')
                ->toArray();
        });
    }

    /**
     * getCurrencyFromCode()
     *
     * Returns an array containing currency object based on the country code
     * you provide.  Will fall back to GBP if a currency is not available in
     * enabled currencies.
     *
     * @param  mixed $currency Country code
     * @return array $format Currency details in an array
     */
    public static function getCurrencyFromCode($country_code = null)
    {
        if (empty($country_code)) {
            $country_code = 'GBP';
        }

        if (
            isset($GLOBALS['enabled_currencies'])
            && is_array($GLOBALS['enabled_currencies'])
            && array_key_exists($country_code, $GLOBALS['enabled_currencies'])
        ) {
            // Try and find currency in table
            $format = self::where('currency', $country_code)
                ->get()
                ->first()
                ->toArray();
        } else {
            $format = self::where('currency', 'GBP')
                ->get()
                ->first()
                ->toArray();
        }

        return $format;
    }
}
