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

use TourOperatorPro\Factory;
use TourOperatorPro\Mvc\Model\ModelForm;
use TourOperatorPro\Filesystem\File as FileAlias;
use TourOperatorPro\Mvc\Model\Model;
use TourOperatorPro\Form\Form;
use TourOperatorPro\Mvc\Model\ModelList;
use TourOperatorPro\Registry\Registry;
use TourOperatorProAdmin\app\helpers\AdminHelper;
use TourOperatorProAdmin\app\helpers\couponHelper;

class CouponModel extends ModelForm
{
    /**
     * @var string
     */
    public $context = "coupon";
    /**
     * @var string
     */
    public $table_name = "coupon";

    public function save($data = array())
    {

        $item= parent::save($data); // TODO: Change the autogenerated stub
        $key_coupon=AdminHelper::getTourcouponKey();
        if(isset($data['tour_id'])) {
            AdminHelper::deletePropertyByKey($key_coupon,$item->id);
            $data_tour_id=$data['tour_id'];
            CouponHelper::insertNewPropertyByKey($key_coupon,$data_tour_id, $item->id);
            $item->{$key_tour}=$item->id;
        }
        return $item;
    }
    public function getItem($id = 0)
    {
        $db=$this->_db;
        $query=$db->getQuery(true);
        $coupon= parent::getItem($id); // TODO: Change the autogenerated stub
        if (isset($coupon->id) && $coupon->id!=0){
            $query->clear()
                ->select('DISTINCT tour_property.tour_id')
                ->from($this->getTableName('tourproperty'.' AS tour_property'))
                ->where('object_id='.(int)$coupon->id)
                ->where('type='.$query->quote(AdminHelper::getTourcouponKey()))
                ;
            $list_tour=$this->_db->setQuery($query)->loadColumn();
            $coupon->tour_id=$list_tour;
        }
        return $coupon;
    }


}
