<?php
namespace WpBookingEventFrontend\app\models;
defined('_WPBOOKINGEVENT_EXEC') or die;

use WpBookingEvent\Factory;
use WpBookingEvent\Mvc\Model\ModelForm;
use WpBookingEvent\Form\Form;
use WpBookingEvent\Mvc\Model\ModelList;
use WpBookingEvent\Registry\Registry;
use WpBookingEventAdmin\app\helpers\AdminHelper;
use WpBookingEventFrontend\app\Html\HtmlFrontend;

class EventsModel extends ModelList
{
    /**
     * @var string
     */
    public $context = "events";
    /**
     * @var string
     */
    public $table_name = "event";

    public function getListQuery()
    {
        $input=Factory::getInput();
        $data=$input->getData();
        $location_id=$input->getInt('location',0);

        $price_search=$input->getString('price_search',"");
        if($price_search!==""){
            $price_search=(array)json_decode($price_search);
        }

        $eventtype=[];
        if(array_key_exists('eventtype',(array)$data)) {
            $eventtype=$data['eventtype'];
            if(!empty($eventtype)){
                $eventtype=(array)$eventtype;
            }
        }

        $employee=[];
        if(array_key_exists('employee',(array)$data)) {
            $employee=$data['employee'];
            if(!empty($employee)){
                $employee=(array)$employee;
            }
        }
        $query = $this->db->getQuery(true);
        $query->select('event.*')
            ->from($this->getTableName('event') . ' AS event')
            ->where('event.published=1')
            ->leftJoin($this->getTableName('service') . ' AS service ON service.id=event.service_id')
            ->select('service.image as service_image,service.duration as duration, service.price as price')
            ->leftJoin($this->getTableName('location') . ' AS location ON location.id=event.location_id')
            ->select('location.address as location_name')

        ;

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

        if(is_array($price_search) && !empty($price_search)){
            $min=reset($price_search);
            $max=end($price_search);

            $query->where('event.price>='.(float)$min);
            $query->where('event.price<='.(float)$max);
        }
        if(is_array($employee) && !empty($employee)){

            $query
                ->leftJoin($this->getTableName("service_employee").' AS service_employee ON service_employee.service_id=event.service_id')
                ->where('service_employee.employee_id IN ('.implode($employee,",").')')
            ;
        }
        if(is_array($eventtype) && !empty($eventtype)){

            $query
                ->where('event.event_type_id IN ('.implode($eventtype,",").')')
            ;
        }
        $query->group('event.id');
        return $query;
    }
    public function getTotalRecord(){
        $query=$this->getListQuery();
        $db=Factory::getDBO();
        $list_events=$db->setQuery($query)->loadObjectList();
        return count($list_events);
    }

    public function getList()
    {
        $input=Factory::getInput();
        $data=$input->getData();
        $start=0;
        if (isset($data['start']) && $data['start']!==""){
            $start=(int)$data['start'];
        }
        $limit=6;
        if(isset($data['limit']) && $data['limit']!==""){
            $limit=(int)$data['limit'];
        }
        $query=$this->getListQuery();
        $db=Factory::getDBO();
        $list=$db->setQuery($query,$start,$limit)->loadObjectList();
        $query=$this->_db->getQuery(true);
        foreach ($list as &$item) {
            $query->clear()
                ->select("gallery.*")
                ->from($this->getTableName('gallery') . ' AS gallery')
                ->where('gallery.object_id=' . (int)$item->id)
                ->where('gallery.type=' . $query->quote("event"));
            $item->list_image = $this->db->setQuery($query)->loadObjectList();
            $query->clear()
                ->select("employee.*, CONCAT(employee.first_name, ' ' , employee.last_name) AS employee_fullname")
                ->from($this->getTableName('employee') . ' AS employee')
                ->leftJoin($this->getTableName('event_employee') . ' AS event_employee ON event_employee.employee_id=employee.id')
                ->where('event_employee.event_id=' . (int)$item->id);
            $list_employee = $this->_db->setQuery($query)->loadObjectList();
            $item->list_employee = $list_employee;

            $query->clear()
                ->select('location.*')
                ->from($this->getTableName('location') . ' AS location')
                ->where('location.id=' . (int)$item->location_id);
            $item->list_location = $this->_db->setQuery($query)->loadObjectList();

            $query->clear()
                ->select('eventtype.name')
                ->from($this->getTableName('eventtype') . ' AS eventtype')
                ->where('eventtype.id=' . (int)$item->event_type_id);
            $item->eventtype_name = $this->_db->setQuery($query)->loadResult();

            $query->clear()
                ->select('rate.*')
                ->from($this->getTableName('rate') . ' AS rate')
                ->where('rate.object_id=' . (int)$item->id)
                ->where('rate.type=' . $query->quote(AdminHelper::getWpBookingEventKey()));
            $list_rate = $this->db->setQuery($query)->loadObjectList();
            $arrDate = [];
            foreach ($list_rate as &$rate) {
                $arrDate[] = strtotime($rate->from);
                $arrDate[] = strtotime($rate->to);
                $rate->start_time = HtmlFrontEnd::render_date($rate->from,'g:i A' );
                $rate->end_time = HtmlFrontEnd::render_date($rate->to,'g:i A');

            }
            if (!empty($arrDate)) {
                $item->min_day = date('d',min($arrDate));
                $item->min_month = date('F',min($arrDate));
                $item->max_day = date('d',max($arrDate));
                $item->max_month = date('F',max($arrDate));
            } else {
                $item->min_date = 0;
                $item->max_date = 0;
            }
            $item->list_rate = $list_rate;
        }
        return $list;
    }

}
