<?php

if (!defined('BASEPATH')) {
    exit('No direct script access allowed');
}

class Photo_Model extends MY_Model {

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

    public function get_employee_list() {
        $this->db->select('E.*');
        $this->db->from('employees AS E');
        $this->db->join('users AS U', 'U.id = E.user_id', 'left');
        $this->db->where('E.status', '1');
        if ($this->session->userdata('role_id') == SUPER_ADMIN) {
            $this->db->where_in('U.role_id', array(SUPER_ADMIN, ADMIN, ACCOUNTANT, RECEPTIONIST));
        } else {
            $this->db->where_in('U.role_id', array(ADMIN, ACCOUNTANT, RECEPTIONIST));
        }
        $this->db->order_by('E.id ', 'DESC');
        return $this->db->get()->result();
    }

    public function get_photo_list($limit, $offset, $keyword, $category_id,  $created_by, $count) {
        $this->db->select('P.*, G.title as category');
        $this->db->from('photos AS P');
        $this->db->join('galleries AS G', 'G.id = P.gallery_id', 'left');
        if ($keyword) {
            $this->db->like('P.title', $keyword, 'both');
            $this->db->or_like('P.bn_title', $keyword, 'both');
            $this->db->or_like('P.description', $keyword, 'both');
            $this->db->or_like('P.bn_description', $keyword, 'both');
            $this->db->or_like('G.title', $keyword, 'both');
        }
        if ($category_id) {
            $this->db->where('P.gallery_id', $category_id);
        }
        if ($created_by) {
            $this->db->where('P.created_by', $created_by);
        }
        $this->db->order_by('P.id', 'DESC');
        if ($count) {
            return $this->db->count_all_results();
        } else {
            $this->db->limit($limit, $offset);
            $query = $this->db->get();

            if ($query->num_rows() > 0) {
                return $query->result();
            }
        }
        return array();
    }

    public function get_single_photo($id) {
        $this->db->select('P.*, G.title as category, C.name as created_by, M.name as modified_by');
        $this->db->from('photos AS P');
        $this->db->join('galleries AS G', 'G.id = P.gallery_id', 'left');
        $this->db->join('employees AS C', 'C.user_id = P.created_by', 'left');
        $this->db->join('employees AS M', 'M.user_id = P.modified_by', 'left');
        $this->db->where('P.id', $id);
        return $this->db->get()->row();
    }

    function duplicate_check($category_id, $title, $id = null) {
        if ($id) {
            $this->db->where_not_in('id', $id);
        }
        $this->db->where('gallery_id ', $category_id);
        $this->db->where('title', $title);
        return $this->db->get('photos')->num_rows();
    }
}
