<?php
namespace TourOperatorProAdmin\app\models;
defined('_TOUROPERATOR_EXEC') or die;

use Exception;
use TourOperatorPro\Factory;
use TourOperatorPro\Language\Text;
use TourOperatorPro\Mvc\Model\ModelForm;
use TourOperatorPro\Form\Form;
use TourOperatorPro\Mvc\Model\ModelList;
use TourOperatorPro\Registry\Registry;
class SmsModel extends ModelForm
{
    /**
     * @var string
     */
    public $context = "sms";
    /**
     * @var string
     */
    public $table_name = "sms";
    public function save($data = array()){
        $query = $this->_db->getQuery(true);
        if ($data['published']==1){
            $query->update($this->getTableName('sms'))
                ->set('published=0');
            $this->_db->setQuery($query)->execute();
        }
       if ($data){
           $err = array();
           if ($data['phone_register'] == '' || $data['phone_register'] == 'Enter your phone register') $err['phone_register'] = 'phone register is required';
           if ($data['auth_token'] == '' || $data['auth_token'] == 'Auth token your email') $err['auth_token'] = 'auth token is required';
           if ($data['account_id'] == '' || $data['account_id'] == 'Account id date your email') $err['account_id'] = 'Account id  is required';
           if (empty($err)){
               $item = parent::save($data);
               if ($item->publish==1){
                   $query->clear()
                       ->update($this->getTableName('smscontent'). 'AS smscontent')
                       ->set('smscontent.sms_suplier_id'.(int)$item->id);
                   $this->_db->setQuery($query)->execute();
               }
           }else{
               $er = (object)$err;
               throw new Exception(Text::_echo(
                   '<div class="alert alert-danger" style="width: 30%; margin: 0 auto; text-align: center">
                        '.((!empty($er->phone_register)) ?'<strong>'.$er->phone_register.'</strong></br>' : false) .'
                        '.((!empty($er->auth_token)) ?'<strong>'.$er->auth_token.'</strong></br>' : false) .'
                        '.((!empty($er->account_id)) ?'<strong>'.$er->account_id.'</strong></br>' : false) .'
                </div>'
               ));
           }
       }
        return $item;
    }
    public function getItem($id = 0)
    {
        $sms =  parent::getItem($id); // TODO: Change the autogenerated stub
        $query = $this->_db->getQuery(true);
        if(!empty((array)$sms)) {
            $query->clear()
                ->select('country.countryname')
                ->from($this->getTableName('country').' AS country')
                ->where('country.phonecode='.(int)$sms->phonecode)
                ->where('country.countrycode='.$query->quote($sms->countrycode))
            ;
            $sms->country_name = $this->_db->setQuery($query)->loadResult();
        }
        return $sms;
    }

}
