<?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 WpBookingPro\Utilities\Utility;

class CategoriesModel extends ModelList
{
    /**
     * @var string
     */
    public $context = "categories";
    /**
     * @var string
     */
    public $table_name = "category";

    public function sorting($list)
    {
        foreach ($list as $item){
            $item=(object)$item;
            $item_sorting=[
                'id'=> $item->id,
                'ordering'=>$item->ordering
            ];
            if(!parent::save($item_sorting)){
                return false;
            }
        }
        return true;
    }

    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_category = parent::getList(); // TODO: Change the autogenerated stub
        $db = Factory::getDBO();
        $query = $db->getQuery(true);
        foreach ($list_category as &$category) {
            $query->clear()
                ->select('service.*')
                ->from($this->getTableName('service').' AS service')
                ->where('service.category_id ='.(int)$category->id)
                ->where('service.published=1')
            ;
            $list_service = $db->setQuery($query)->loadObjectList();
            foreach ($list_service as &$service) {
                $query->clear()
                    ->select('service_employee.*')
                    ->from($this->getTableName('service_employee').' AS service_employee')
                    ->where('service_employee.service_id='.(int)$service->id)
                ;
                $list_employee = $db->setQuery($query)->loadObjectList();
                $service->list_employee = $list_employee;
            }
            $category->list_service = $list_service;
            if(isset($category->user_id) && $category->user_id) {
                $query->clear()
                    ->select('*')
                    ->from($this->getTableName('user'))
                    ->where('id=' . (int)$category->user_id);
                $category->vendor = $db->setQuery($query)->loadObject();
            }
        }


        return $list_category;
    }


}
