<?php
class Metadata_Page extends MY_Model
{
	const DB_TABLE = 'metadata_pages';
    const DB_TABLE_PK = 'metadata_id';

    private static $results = null;

    private function init($site_id)
    {
    	$key = "metadata_pages:" . $site_id;

    	if(($query = $this->cache->get($key)) === false)
    	{
    		$query = $this->db->query("SELECT * FROM metadata_pages WHERE site_id=?", array($site_id));
    		$query = $query->result();
    		$this->cache->save($key, $query, 86400);
    	}

	  	Metadata_Page::$results = $query;
    }

    function LoadByURL($site_id, $url, $page_id=0)
	{
	  	if(is_null(Metadata_Page::$results))
		{
			$this->init($site_id);
		}

		foreach(Metadata_Page::$results as $result)
		{
			if($result->url == $url && ($page_id == 0 || ($page_id > 0 && $result->page_id == $page_id)))
			{
				return $result;
			}
		}

		return false;
	}

    function LoadBySiteID($id)
	{
		$query = $this->db->query("SELECT * FROM metadata_pages WHERE site_id=? ORDER BY `url`", array($id));

		return $query->result();
	}

    function LoadAllPagesBySiteID($id)
	{
		$query = $this->db->query("SELECT metadata_id, site_id, page_id, url, title, description, ('0') AS sort
								  FROM metadata_pages WHERE site_id=?
		                          UNION
		                          SELECT ('') AS metadata_id, p.site_id AS site_id, p.page_id AS page_id, p.url AS url, p.title AS title, p.description AS description, ('1') AS sort
		                          FROM pages AS p
		                          LEFT JOIN metadata_pages AS m ON p.page_id=m.page_id
		                          WHERE p.site_id=? AND m.metadata_id IS NULL
		                          ORDER BY sort, `url` ASC",
		                          array($id, $id));

		return $query->result();
	}
}
