<?php
namespace WpBookingProAdminWooPanel\app\models;
defined('_WPBOOKINGPRO_EXEC') or die;

use WpBookingPro\Factory;
use WpBookingPro\Mvc\Model\ModelForm;
use WpBookingPro\Filesystem\File as FileAlias;
use WpBookingPro\Mvc\Model\Model;
use WpBookingPro\Form\Form;
use WpBookingPro\Mvc\Model\ModelList;
use WpBookingPro\Registry\Registry;
use WpBookingProAdmin\app\helpers\AdminHelper;
use WpBookingProAdmin\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
        $list_service_id = isset($data['service_id'])?$data['service_id']:array();
        $db  = Factory::getDBO();
        $query = $db->getQuery(true);
        $query->clear()
            ->delete($this->getTableName('service_coupon'))
            ->where('service_id='.(int)$item->id)
        ;
        $db->setQuery($query)->execute();
        foreach ($list_service_id as $service_id) {
            $query->clear()
                ->insert($this->getTableName('service_coupon'))
                ->set('service_id='.(int)$service_id)
                ->set('coupon_id='.(int)$item->id)
            ;
            $db->setQuery($query)->execute();
        }
        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 service.id')
                ->from($this->getTableName('service').' AS service')
                ->leftJoin($this->getTableName('service_coupon').' AS service_coupon ON service_coupon.service_id=service.id')
                ->where('service_coupon.coupon_id='.(int)$coupon->id)
            ;
            $coupon->service_id=$this->_db->setQuery($query)->loadColumn();
        }

        return $coupon;
    }


}
