<?php

namespace Mnv\Models;

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

//INSERT INTO `ls_socials` (`socialId`, `name`, `url`, `icon`, `fileName`, `status`, `orderBy`, `addedBy`, `addedOn`, `modifiedBy`, `modifiedOn`) VALUES
//(1, 'Телеграм', 'https://t.me/', '', 'telegram', 'visible', 1, 1, '2023-01-09 23:23:36', 1, '2023-03-09 23:23:36'),
//(2, 'Facebook', 'https://www.facebook.com/', 'facebook', 'facebook', 'visible', 2, 1, '2023-01-09 23:23:36', 1, '2023-01-09 23:23:36'),
//(3, 'Instagram', 'https://www.instagram.com/', 'instagram', 'instagram', 'visible', 3, 1, '2023-01-09 23:23:36', 1, '2023-01-09 23:23:36'),
//(5, 'Twitter', 'https://twitter.com/', 'twitter', 'twitter', 'hidden', 6, 1, '2023-01-09 23:23:36', 1, '2023-01-09 23:23:36'),
//(6, 'YouTube', 'https://www.youtube.com/', 'youtube', 'youtube', 'hidden', 4, 1, '2023-01-09 23:23:36', 1, '2023-01-09 23:23:36'),
//(4, 'Одноклассники', 'https://ok.ru/', 'ok', 'ok', 'visible', 5, 1, '2023-01-09 23:23:36', 1, '2023-01-09 23:23:36');

/**
 * Class Socials
 * @package Mnv\Models
 */
class Socials extends Model
{
    /** @var string */
    protected string $table = 'socials';

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

    protected string $orderBy = 'orderBy ASC';

    public $socialIds = array();

    public function __construct(Request $request)
    {
        $this->id        = (int) $request->get('id');
        $this->data      = $request->get('social');
        $this->socialIds = $request->get('ids');
    }

    /**
     * Проверка на существование во избежание дублирования
     *
     * @param string $fileName
     * @return bool
     */
    public function checkFileName(string $fileName): bool
    {
        if (!empty($this->id)) connect()->where($this->primaryKey, '<>', $this->id);
        if (connect()->table('socials')->select('socialId')->where('LOWER(fileName)', strtolower($fileName))->get()) return false;

        return true;
    }

    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;
    }

}