<?php

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

/**

 *

 * @property CI_DB_active_record $db

 * @property CI_Input $input


 * @property CI_Pagination $pagination

 * @author Mohamed Mahdy <eng.mohamed.php@gmail.com>

 * @copyright Copyright (c) 2011, Web Developer <Mohamed Mahdy>

 */
class users_model extends CI_Model {

    /**

     *

     * static ids cannot be deleted

     *

     * admin = 1

     *

     * @var integer

     *

     */
    private $publisher_group_static_id;

    function __construct() {

        parent::__construct();

        $this->publisher_group_static_id = 2;
    }

    /*  This function get all users in database sort by order asc. */

    function get_users($row, $userdata = "") {
        $query = "SELECT *,d_groups.gr_name as gn FROM d_users , d_groups 
                                 WHERE d_users.user_group_id = d_groups.gr_id ";
        if (isset($userdata) && $userdata != "") {
            $query .= "AND (d_users.user_username LIKE '%{$userdata}%' OR d_users.user_email = '{$userdata}') ";
            $query .= "ORDER BY user_id DESC";
        } else {
            $query .= "ORDER BY user_id DESC LIMIT $row, 10";
        }

        $result = $this->db->query($query);

        return $result->result_array();
    }

    function getNumUsersAdmin() {
        $query = $this->db->query("select * from d_users");
        return $query->num_rows();
    }

    /**

     *

     * @param integer $group_id

     *

     */
    function get_users_by_group($group_id) {

        $this->db->where('user_group_id', $group_id);

        return $this->db->get('users')->result_array();
    }

    function get_groups() {

        $this->db->select('groups.*');

        $this->db->from('groups');

        $result = $this->db->get();

        return $result->result_array();
    }

    function get_groups_edit() {

        $this->db->select('groups.*');

        $this->db->from('groups');

        $this->db->where('gr_id !=', $this->publisher_group_static_id);

        $result = $this->db->get();

        return $result->result_array();
    }

    function create() {

// insert user informtion

        $this->db->set('user_username', $this->input->post('user_name'));

        $this->db->set('user_password', md5($this->input->post('user_pass')));

        $this->db->set('user_full_name', $this->input->post('name'));

        $this->db->set('user_email', $this->input->post('email'));

        $this->db->set('user_group_id', $this->input->post('group_id'));

        $this->db->set('user_state', '1');
        if ($this->input->post('group_id') == 2) {
            $this->db->set('user_sales_email', '1');
        }

        $this->db->set("user_created_date", @date('Y-m-d') . ' ' . $this->input->post('user_created_date'));

        $this->db->insert('users');



// connect users with user group

        $id = $this->db->insert_id();

        $this->db->set('ug_user_id', $id);

        $this->db->set('ug_group_id', $this->input->post('group_id'));

        $this->db->insert('d_user_groups');



// if it was publisher insert new row in d_publishing table

        if ($this->input->post('group_id') == $this->publisher_group_static_id) { // publisher
            $this->db->set('pub_name', $this->input->post('name'));

            $this->db->set('pub_user_id', $id);

            $this->db->insert('publishing');

            log_message('debug', 'data inserted in d_publishing');
        }
    }

    /**

     * @param integer $id

     */
    function update($id) {

        $this->db->where('user_id', $id);

        $this->db->set('user_username', $this->input->post('user_name'));

        if ($this->input->post('user_pass')) {

            $this->db->set('user_password', md5($this->input->post('user_pass')));
        }

        $this->db->set('user_full_name', $this->input->post('name'));

        $this->db->set('user_email', $this->input->post('email'));

        $this->db->set('user_group_id', $this->input->post('group_id'));

        $this->db->update('users');



        $this->db->where('ug_user_id', $id);

        $this->db->set('ug_group_id', $this->input->post('group_id'));

        $this->db->update('d_user_groups');

        log_message('debug', 'user data updated for id =' . $id);
    }

    function check_email() {
        $email = $this->input->post('email');

        $query = $this->db->query("select user_id,user_email from d_users where user_email = '{$email}'");
        return $query->row();
    }

    function check_username() {
        $username = $this->input->post('user_name');

        $query = $this->db->query("select user_id,user_username from d_users where user_username = '{$username}'");
        return $query->row();
    }

    /**

     *

     * @param integer $id userid

     * @return true if data deleted other wise return false

     */
    function delete($id) {

        $this->db->where('user_id', $id);

        $this->db->delete('users');

        $this->db->delete('d_user_groups', 'ug_user_id =' . $id);
    }

    /**

     *

     * delete publisher information

     *

     * @param integer $id userid

     *

     */
    function delete_publishing($id) {

        $user = $this->get_user_one($id);

        if ($user->user_group_id == $this->publisher_group_static_id) {

            $publisher = $this->db->query("SELECT pub_user_id,pub_id FROM d_publishing WHERE pub_user_id = '" . $user->user_id . "'")->row();

            Modules::run('bookstore/admin_d_publishing/remove_d_publishing', $publisher->pub_id); // remove via publisher id

            $this->db->delete('section_bridge', "sec_b_user_id = '$user->user_id'");

            log_message('debug', 'data deleted from publishing for id = ' . $id);
        }
    }

    function is_valid_visitor($id) {

        $this->db->where('e_id', $id);

        $this->db->from('employee');

        if ($this->db->count_all_results() > 0) {

            return TRUE;
        } else {

            return FALSE;
        }
    }

    function is_valid_page($id) {

        $this->db->where('e_id', $id);

        $this->db->from('employee');

        if ($this->db->count_all_results() > 0) {

            return TRUE;
        } else {

            return FALSE;
        }
    }

    function get_page($id) {

        $this->db->where('e_id', $id);

        $result = $this->db->get('employee');

        if ($result->num_rows() > 0) {

            return $result->row_array();
        } else {

            return FALSE;
        }
    }

    function get_user_one($id) {

        $result = $this->db->query("select * 

                                    from d_users                                  

                                    where user_id='$id'");

        return $result->row();
    }

    function get_user_sales($limit, $id = '') {
        return $this->db->query("SELECT DISTINCT  d_sales. * , d_book.bo_name ,  d_book.bo_num_pages , 
                            ( SELECT MIN( d_book_pages.b_pag_created_date ) 
                              FROM  d_book_pages 
                              WHERE  d_book_pages.b_pag_bo_id =  d_sales.sal_bo_id 
                              AND d_book_pages.b_pag_num = d_book.bo_num_pages
                              AND d_book_pages.b_pag_stop = 1
                            ) AS created_date, 
                            ( SELECT MAX(  d_book_pages.b_pag_num ) 
                              FROM  d_book_pages 
                              WHERE  d_book_pages.b_pag_bo_id =  d_sales.sal_bo_id
                            ) AS last_page 
                        FROM d_sales
                        LEFT JOIN  d_book ON  d_book.bo_id =  d_sales.sal_bo_id 
                        LEFT JOIN  d_book_pages ON  d_book_pages.b_pag_bo_id =  d_sales.sal_bo_id 
                        AND  d_book_pages.b_pag_stop =1
                        WHERE  sal_user_id =  '{$id}'
                        ORDER BY  sal_ord DESC 
                        LIMIT {$limit} , 10")->result_array();
    }

    function get_user_visits($limit, $id = '') {

        $this->db->order_by("pa_vi_time", "DESC");

        $this->db->where('pa_vi_userid', $id);

        $this->db->limit($this->pagination->per_page, $limit);

        return $this->db->get('pages_visits')->result_array();
    }

    function get_user_sales_rows($user_id) {

        $this->db->where('sal_user_id', $user_id);

        $result = $this->db->get('sales');

        return $result->num_rows();
    }

    function get_user_visits_rows($user_id) {

        $this->db->where('pa_vi_userid', $user_id);

        $result = $this->db->get('d_pages_visits');

        return $result->num_rows();
    }

//    function get_user_one($id) {
//        $result = $this->db->query("select * from d_users where user_id='$id'");
//        return $result->row();
//    }



    function operation() {

        if (!empty($_POST['check_nf'])) {

            $elements = $_POST['check_nf'];

            for ($i = 0; $i <= count($elements) - 1; $i++) {

                switch ($_POST['operation']) {

                    case "delete":

                        $this->delete($elements[$i]);
                        $this->session->set_flashdata('success_msg', $this->lang->line('success_msg_del_all'));
                        break;
                }
            }
        }
    }

    function get_visitor() {

        $name = $this->input->post('name');

        $email = $this->input->post('email');

        $s = $this->db->query("select * from employee where e_name='$name' and e_email='$email'");

        return $s = $s->result_array();
    }

}

