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

use Exception;
use WpBookingHotel\Factory;
use WpBookingHotel\Language\Text;
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 WpBookingHotel\Utilities\Utility;
use WpBookingHotelAdmin\app\helpers\AdminHelper;
use WpBookingHotelAdmin\app\helpers\DiscountHelper;

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


    public function save($data = array())
    {
        $item= parent::save($data); // TODO: Change the autogenerated stub
        $key_discount=AdminHelper::getWpBookingDiscountKey();
        if(isset($data['hotel_id'])) {
            $list_hotel = $data['hotel_id'];
            foreach ($list_hotel as $hotel_id) {
                AdminHelper::deletePropertyByKey($key_discount,$hotel_id);
                $data_hotel_id=array();
                $data_hotel_id[]=$hotel_id;
                DiscountHelper::insertNewPropertyByKey($key_discount,$data_hotel_id, $item->id);
            }

        }
        return $item;
    }
    public function getItem($id = 0)
    {
        $db=$this->_db;
        $query=$db->getQuery(true);
        $discount= parent::getItem($id); // TODO: Change the autogenerated stub
        if (isset($discount->id) && $discount->id!=0){
            $query->clear()
                ->select('DISTINCT hotel_property.hotel_id')
                ->from($this->getTableName('hotelproperty'.' AS hotel_property'))
                ->where('object_id='.(int)$discount->id)
                ->where('type='.$query->quote(AdminHelper::getWpBookingDiscountKey()))
            ;
            $list_hotel=$this->_db->setQuery($query)->loadColumn();
            $discount->hotel_id=$list_hotel;
        }
        return $discount;
    }


}
