<?php
namespace TourOperatorProFrontend\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 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;
    }
    public function getItemByCode($code = "",$tour_id)
    {
        $db=$this->_db;
        $query=$db->getQuery(true);
        $query->select('coupon.*')
            ->from($this->getTableName('coupon').' AS coupon')
            ->where('coupon.code='.$query->quote($code));
        $coupon=$this->_db->setQuery($query)->loadObject();
        if (isset($coupon->id) && $coupon->id!=0 && $coupon->published == 1){
            $query->clear()
                ->select('DISTINCT tour_property.tour_id')
                ->from($this->getTableName('tourproperty'.' AS tour_property'))
                ->where('object_id='.(int)$coupon->id)
                ->where('tour_id='.(int)$tour_id)
                ->where('type='.$query->quote(AdminHelper::getTourCouponKey()));
            $list_tour=$this->_db->setQuery($query)->loadColumn();
            $coupon->tour_id=$list_tour;
        }
        if (empty($coupon->tour_id)){
            return false;
        }
        return true;
    }


}
