<?php
class MenuItem extends MY_Model
{
	const DB_TABLE = 'menu_items';
    const DB_TABLE_PK = 'menu_item_id';

    public function __construct()
	{
		parent::__construct();

		$this->sort 		= 1;
		$this->published 	= 1;
	}

	function LoadByMenuID($id, $parent_id, $user)
	{
		if($user == null)
		{
			// Simulate an admin user
			$user = new User();
			$user->roles = array(3);
		}
		else if(!isset($user->roles) || count($user->roles) == 0)
    	{
    		$user->roles = array(1); // Public
    	}

		$query = $this->db->query("SELECT i.menu_item_id, i.menu_id, i.parent_id, i.title, i.title_tag, i.description, i.icon, i.page_id, IF(i.url != '', i.url, p.url) AS url, i.target, i.sort, i.published, p.title AS page_title
									FROM menus AS m
									INNER JOIN menu_items AS i ON m.menu_id=i.menu_id
									INNER JOIN `acl` AS a USING(menu_item_id)
									LEFT JOIN pages AS p ON i.page_id=p.page_id
									WHERE m.menu_id=?" . ($parent_id == -1 ? "" : ($parent_id != null ? " AND parent_id='$parent_id'" : " AND parent_id IS NULL ")) . "
									AND a.read=1 AND a.acl_role_id IN ?
									GROUP BY i.menu_item_id
                                  	ORDER BY sort",
									array($id, $user->roles));

		return $query->result();
	}

	public function delete_all($menu_id)
    {
    	$this->db->query("DELETE FROM menu_items WHERE menu_id=?", array($menu_id));
    }

    public function delete_others($menu_id, $ids)
    {
    	$this->db->query("DELETE FROM menu_items WHERE menu_id=? AND menu_item_id NOT IN ($ids)", array($menu_id));
    }

    function search($q, $user)
	{
		if($q == null)
		{
			return array();
		}

		if(!isset($user->roles) || count($user->roles) == 0)
    	{
    		$user->roles = array(1); // Public
    	}

		$q = $this->db->escape_str($q);

		$query = $this->db->query("SELECT i.*
		                          FROM menu_items AS i
		                          INNER JOIN `acl` AS a USING(menu_item_id)
		                          WHERE (a.read=1 AND a.acl_role_id IN ?) AND
			                          i.title LIKE '%$q%'
		                          GROUP BY i.menu_item_id
		                          ORDER BY title",
		                          array($user->roles));

		return $query->result();
	}
}
