<?php
namespace WpBookingProFrontend\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 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;
    }

    public function getListCouponByUser(){
        if(is_user_logged_in()) {
            $user = wp_get_current_user();
            $db = Factory::getDBO();
            $query = $db->getQuery(true);
            $query->clear()
                ->select('user.id')
                ->from($this->getTableName('user') .' AS user')
                ->where('user.open_source_user_id	='.(int)$user->ID)
            ;
            $user_id_plugin = $db->setQuery($query)->loadResult();
            $query->clear()
                ->select('*')
                ->from($this->getTableName('coupon'))
                ->where('user_id='.(int)$user_id_plugin)
            ;
            $list_coupon = $db->setQuery($query)->loadObjectList();
            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;
        }
        return array();
    }

}
