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

use WpBookingPro\Factory;
use WpBookingPro\Mvc\Model\ModelForm;
use WpBookingPro\Form\Form;
use WpBookingPro\Mvc\Model\ModelList;
use WpBookingPro\Registry\Registry;
use WpBookingProFrontend\app\helpers\FrontendHelper;

class CouponsModel extends ModelList
{
    /**
     * @var string
     */
    public $context = "coupons";
    /**
     * @var string
     */
    public $table_name = "coupon";

    public function getListQuery()
    {
        $input = Factory::getInput();
        $user_id  = $input->getInt('user_id',0);

        $query=$this->db->getQuery(true);
        $query->select("a.*")
            ->from($this->getTableName().' AS a')

        ;
        if($user_id > 0) {
            $query->where('a.user_id='.(int)$user_id);
        }
        $query->order($this->getState('list.ordering', 'a.ordering') . ' ' . $this->getState('list.direction', 'ASC'));

        return $query;
    }

    public function getList()
    {
        $list_coupon =  parent::getList(); // TODO: Change the autogenerated stub
        foreach ($list_coupon as &$coupon) {
            $query = $this->_db->getQuery(true);
            $query->clear()
                ->select('DISTINCT service.*')
                ->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->list_service=$this->_db->setQuery($query)->loadObjectList();
        }
        return $list_coupon;
    }

}
