<?php
class Directory_Category extends MY_Model
{
    const DB_TABLE = 'directory_categories';
    const DB_TABLE_PK = 'category_id';

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

        return $query->result();
    }

    function LoadByParentID($id)
    {
        $query = $this->db->query("SELECT * FROM directory_categories AS c WHERE " . ($id > 0 ? "parent_id=?" : "parent_id IS NULL") . " ORDER BY `category_name`", array($id));

        return $query->result();
    }

    function LoadByCompanyID($id)
    {
        $query = $this->db->query("SELECT cat.*, cc.directory_company_category_id AS link_id, IF(cc.company_id IS NULL, 0, 1) AS `active`
            FROM directory_categories AS cat
            LEFT JOIN directory_companies_categories AS cc ON (cat.category_id=cc.category_id AND cc.company_id=?)
            ORDER BY `category_name`",
            array($id));

        return $query->result();
    }

    function loadByURL($site_id, $url)
    {
        $query = $this->db->query("SELECT *
                                  FROM directory_categories AS c
                                  WHERE site_id=? AND " . (is_numeric($url) ? "category_id=?" : "url=?"),
                                  array($site_id, $url));

        if($query->num_rows() > 0)
        {
            foreach($query->result() as $row)
            {
                //return the first item
                return $this->Load($row->category_id);
            }
        }
        else
        {
            return false;
        }
    }
}
