<?php

namespace Mnv\Models\Shop;

use Mnv\Core\Model;
use Mnv\Http\Request;

/**
 * Class Currencies
 * @package Mnv\Models\Shop
 */
class Currencies extends Model
{

    /** @var string */
    protected string $table = 'shop_currency';

    /** @var string  */
    protected string $primaryKey = 'id';

    /** @var string  */
    protected string $orderBy = 'isDefault DESC, orderBy ASC';

    public $currencyIds = [];

    public function __construct(Request $request)
    {
        $this->id           = $request->get('id');                     //  getRequestVar('id'),
        $this->data         = $request->get('currency', '');    //  getRequestVar('currency', '', true)
        $this->currencyIds  = $request->get('ids', '');         //  getRequestVar('ids', '', true);
    }

    public function currencySelectList(): ?array
    {
        return connect()->table($this->table)->select('id, title')->orderBy('isDefault DESC')->indexKey('id')->valueKey('title')->getAllIndexes('array');
    }


    public function prepare(array $data, int $managerId): bool
    {
        $data['modifiedBy']    = $managerId;
        $data['modifiedOn']    = gmdate('Y-m-d H:i:s');

        if (empty($this->id)) {

            $data['addedBy'] = $managerId;
            $data['addedOn'] = gmdate('Y-m-d H:i:s');
            $data['orderBy'] = $this->getMaxValue('orderBy') + 1;

            if ($this->id = $this->insert($data)) {
                return true;
            }
        } else {
            return $this->update($data);
        }

        return false;
    }

    public static function getDefaultCurrency()
    {
        return connect()->table('shop_currency')->where('isDefault',1)->get('array');
    }


    public function setDefaultCurrency(): bool
    {
        connect()->table($this->table)->where('isDefault',  1)->update(['isDefault' => 0]);
        connect()->table($this->table)->where($this->primaryKey,  $this->id)->update(['isDefault' => 1]);

        return true;
    }

//    public function status(): bool
//    {
//        if (!empty($this->id) && $oldStatus = connect()->table($this->table)->select('status')->where('id', $this->id)->getValue()) {
//            $update['status'] = ($oldStatus == 'V') ? 'H' : 'V';
//            connect()->table($this->table)->where('id', $this->id)->update($update);
//            $this->status = $update['status'];
//
//            return true;
//        }
//
//        return false;
//    }

    public function checkFileName(?string $fileName)
    {
        // TODO: Implement checkFileName() method.
    }

}