<?php
namespace WpBookingHotelFrontend\app\models;
defined('_WPBOOKINGHOTEL_EXEC') or die;

use WpBookingHotel\Factory;
use WpBookingHotel\Mvc\Model\ModelForm;
use WpBookingHotel\Filesystem\File as FileAlias;
use WpBookingHotel\Mvc\Model\Model;
use WpBookingHotel\Form\Form;
use WpBookingHotel\Mvc\Model\ModelList;
use WpBookingHotel\Registry\Registry;
use WpBookingHotelAdmin\app\helpers\AdminHelper;
use WpBookingHotelAdmin\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 hotel_property.hotel_id')
                ->from($this->getTableName('hotelproperty'.' AS hotel_property'))
                ->where('object_id='.(int)$coupon->id)
                ->where('type='.$query->quote(AdminHelper::gethotelcouponKey()))
                ;
            $list_hotel=$this->_db->setQuery($query)->loadColumn();
            $coupon->hotel_id=$list_hotel;
        }
        return $coupon;
    }
    public function getItemByCode($code = "",$hotel_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){
            $query->clear()
                ->select('DISTINCT hotel_property.hotel_id')
                ->from($this->getTableName('hotelproperty'.' AS hotel_property'))
                ->where('object_id='.(int)$coupon->id)
                ->where('hotel_id='.(int)$hotel_id)
                ->where('type='.$query->quote(AdminHelper::getHotelCouponKey()))
                ;
            $list_hotel=$this->_db->setQuery($query)->loadColumn();
            $coupon->hotel_id=$list_hotel;
        }
        if (empty($coupon->hotel_id)){
            return false;
        }
        return $coupon;
    }


}
