<?php
defined('_WPBOOKINGPRO_EXEC') or die;
use WooBooking\CMS\Form\Form;
use WooBooking\CMS\Utilities\Utility;
if(!class_exists("WpBookingPro_EventsModel")) {
    /**
     * Class WpBookingPro_EventsModel
     */
    class WpBookingPro_EventsModel extends WoobookingModelList
    {
        /**
         * @var string
         */
        public $context = "events";
        /**
         * @var string
         */
        public $table_name = "event";

        /**
         * @return \WooBooking\CMS\Database\DatabaseQuery
         */
        public function getListQuery()
        {
            $query = $this->db->getQuery(true);
            $query->select('event.*')
                ->from($this->getTableName('event') . ' AS event')
                ->where('event.published=1');;
            $query->order($this->getState('list.ordering', 'event.ordering') . ' ' . $this->getState('list.direction',
                    'ASC'));
            return $query;
        }

        /**
         * @return array
         */
        public function getHeader()
        {
            return array();
        }

        /**
         * @param $list_rate_id
         * @return mixed
         */
        public function getListEventByListRateId($list_rate_id)
        {
            $db = Factory::getDBO();
            $query = $db->getQuery(true);
            $query->select("*")
                ->from($this->getTableName('event') . ' AS event')
                ->leftJoin($this->getTableName('rate') . ' AS rate ON rate.object_id=event.id')
                ->where('rate.id IN(' . implode(",", $list_rate_id) . ')')
                ->where('rate.type=' . $query->quote(WpBookingPro_RateHelper::getEventName()));
            $list = $db->setQuery($query)->loadObjectList();
            return $list;
        }

        /**
         * @return void|\WooBooking\CMS\Database\DatabaseQuery
         */
        public function buildQuery()
        {
            $query = $this->db->getQuery(true)
                ->select('event.*')
                ->from($this->getTableName() . ' AS event ')
                ->leftJoin($this->getTableName('service') . ' AS service ON service.id=event.service_id')
                ->select('service.disable_payment_online');
            return $query;
        }

        /**
         * @return mixed
         */
        public function getList()
        {
            $db = Factory::getDBO();
            $query = $this->getListQuery();
            $list = $db->setQuery($query)->loadObjectList();
            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.*")
                    ->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();
                foreach ($list_employee as &$employee) {
                    $employee->full_name = Utility::getFullName($employee->first_name, $employee->last_name);
                }
                $item->list_employee = $list_employee;
            }
            foreach ($list as &$item) {
                $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();
            }
            foreach ($list as &$item) {
                $query->clear()
                    ->select('rate.*')
                    ->from($this->getTableName('rate') . ' AS rate')
                    ->where('rate.object_id=' . (int)$item->id)
                    ->where('rate.type=' . $query->quote(WpBookingPro_RateHelper::getEventName()));
                $list_rate = $this->db->setQuery($query)->loadObjectList();
                $arrDate = [];
                $dateView = '';
                foreach ($list_rate as &$rate) {
                    $arrDateFrom = date_parse_from_format('Y-m-d H:i:s', $rate->from);
                    $arrDateTo = date_parse_from_format('Y-m-d H:i:s', $rate->to);
                    $dateFromTs = mktime(0, 0, 0, $arrDateFrom['month'], $arrDateFrom['day'], $arrDateFrom['year']);
                    $dateToTs = mktime(0, 0, 0, $arrDateTo['month'], $arrDateTo['day'], $arrDateTo['year']);
                    $timeFromTs = mktime($arrDateFrom['hour'], $arrDateFrom['minute'], $arrDateFrom['second'],
                        $arrDateFrom['month'], $arrDateFrom['day'], $arrDateFrom['year']);
                    $timeToTs = mktime($arrDateTo['hour'], $arrDateTo['minute'], $arrDateTo['second'], $arrDateTo['month'],
                        $arrDateTo['day'], $arrDateTo['year']);
                    $dateFrom = date('F j, Y', $dateFromTs);
                    $dateTo = date('F j, Y', $dateToTs);
                    $timeFrom = date('g:i a', $timeFromTs);
                    $timeTo = date('g:i a', $timeToTs);
                    if ($dateFromTs != $dateToTs) {
                        $dateView .= ' , ' . $dateFrom . ' - ' . $dateTo . ' ' . $timeFrom . ' - ' . $timeTo;
                    } else {
                        $dateView .= ' , ' . $dateFrom . ' ' . $timeFrom . ' - ' . $timeTo;
                    }
                    $arrDate[] = $dateFromTs;
                    $arrDate[] = $dateToTs;
                    $rate->start_time = date('g:i A', $timeFromTs);
                    $rate->end_time = date('g:i A', $timeToTs);

                }
                $item->date_view = $dateView;
                if (!empty($arrDate)) {
                    $item->min_date = min($arrDate);
                    $item->max_date = max($arrDate);
                } else {
                    $item->min_date = 0;
                    $item->max_date = 0;
                }
                $item->list_rate = $list_rate;
            }
            return $list;
        }

        /**
         * @return bool|Form
         */
        public function getFormBooking()
        {
            Form::addFieldPath(WPBOOKINGPRO_PATH_ROOT . '/lib/Form/Field');
            Form::addFieldPath(WPBOOKINGPRO_PATH_ROOT . '/lib/WooBooking/form/fields');
            Form::addFormPath(WPBOOKINGPRO_PATH_COMPONENT . '/models/forms');
            try {
                $form = Form::getInstance("events_booking_form");
                $user = Factory::getUser();
                // Load the data into the form after the plugins have operated.
                $form->bind($user);
            } catch (\Exception $e) {
                wpbookingpro_render_content($e->getMessage());
                die;
                $this->setError($e->getMessage());
                return false;
            }
            return $form;
        }

        /**
         * @return bool|Form
         */
        public function getFormField()
        {
            Form::addFieldPath(WPBOOKINGPRO_PATH_ROOT . '/lib/Form/Field');
            Form::addFieldPath(WPBOOKINGPRO_PATH_ROOT . '/lib/WooBooking/form/fields');
            Form::addFormPath(WPBOOKINGPRO_PATH_COMPONENT . '/models/forms');
            try {
                $form = Form::getInstance("events_form_field");
                // Load the data into the form after the plugins have operated.
            } catch (\Exception $e) {
                wpbookingpro_render_content($e->getMessage());
                die;
                $this->setError($e->getMessage());
                return false;
            }
            return $form;
        }
    }
}
