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

class Users extends front_end {

	function __construct()
        {            
            parent::__construct();
            $this->load->helper('url');	
            $this->load->helper('form');
            $this->load->library('session');
            $this->load->library("form_validation");
            $this->form_validation->CI =& $this;
            // $this->load_lang('form_validation');
            
            $this->load->model("new_user_model","new_user");
	}
	
	function index()
	{
            $this->overview();
          /*  $this->load->model('main_model');
	    $data['rows'] = $this->main_model->main_q();
				
            $is_done  = $this->main_model->main_q();
            if($is_done){
                $data['check'] = TRUE;
                $data['rows'] = $this->main_model->main_q();	
                $data['rows1'] = $this->main_model->main_q1();	
                $data['rows2'] = $this->main_model->main_q2();	
                $data['rows3'] = $this->main_model->main_q3();	
                $data['rows4'] = $this->main_model->main_q4();	
                $data['rows5'] = $this->main_model->main_q5();	
                $data['rows6'] = $this->main_model->main_q6();
                $data['rows7'] = $this->main_model->main_q7();
            }else{
                $data['check']= FALSE;
            }
            $this->load->view('user/index',$data);*/
        }
        
        function overview($row=0)
        {
            $this->load->model('user_model');
            $this->load->library('pagination');
            $config['base_url']=base_url()."users/overview/";
            $config['total_rows']=$this->user_model->getNumUsers();
            $config['per_page']= '5';
           // $config['uri_segment'] = 4;
            $this->pagination->initialize($config);
            $data['users'] = $this->user_model->get_all_users($row);
            $data['row']=$row;
            $data['total_rows']=$this->user_model->getNumUsers();
            $data['links']=$this->pagination->create_links();
            $this->view('site/user_all', $data);
        }
        
        function view_member($id)
        {
            $this->load->model('user_model');
            $data['rows'] = $this->user_model->viewDetails($id);
            /*echo "<pre>";
            print_r($data['rows']);
            echo "</pre>";
            exit;*/
            $this->view('site/my_info',$data);
        }
        
        function view_user_articles($id)
        {
            $this->load->model('user_model');
            $data['rows'] = $this->user_model->viewDetails($id);            
            $this->view('site/user_articles',$data);
        }
      
        
        function User_login()
        {
            $this->load->model('User_login_model');
            $is_logged_in  = $this->User_login_model-> verifyUser($_POST['username'],$_POST['password']);

            if($is_logged_in)
            {
                $this->session->set_userdata('ustate', 'valid');
                $this->User_login_model->log_state($_POST['username'],$_POST['password']);
                $data['rows'] = $this->User_login_model->verifyUser($_POST['username'],$_POST['password']);                    
                $this->load->view('user/mypage',$data);
            }else{
                $this->load->view('user/error_login');
            }					
	}
	function login()
        {               
            $this->load->model("login_model","login");
            $data['user']=$this->login->get_user();
            $user = $data['user'];
            if($user)
            {
                if($user->user_state == 1){
                    $uid=$user->user_id;  
                    $uemail=$user->user_email;
                    $user_name=$this->input->post('username');
                    $this->load->database('default',TRUE);
                    $newdata = array(
                           'username'  => $user_name,
                           'uemail'  => $uemail,
                           'ustate'     => 'valid',
                           'uid'     => $uid,
                           'logged_in' => TRUE
                       );

                    $this->session->set_userdata($newdata);
                    redirect(base_url());
                }else{           
                    $data['msg'] = "عفوا لا يمكنك تسجيل الدخول حتى يتم تفعيل عضويتك من الإدارة";
                    $data['msgType'] = "error";
                    $this->view('theme/msg',$data);
                }
            }else{               
                $data['msg'] = "يوجد خطأ في اسم المستخدم أو رمز المرور .. من فضلك حاول مرة أخرى أو قم بالتسجيل اولا";
                $data['msgType'] = "error";
                $this->view('theme/msg',$data);
            }

        }
        
        function mypage()
        {
            $this->load->model("login_model","login");
            $data['ver_user']=$this->login->verify_user();
            $this->view('site/mypage',$data);			
	}	
        
        function logout()
        {           
            $this->session->sess_destroy();
            $newdata = array(
               'ustate'     => 'unvalid',
               'logged_in' => FAlSE
            );
            $this->session->set_userdata($newdata);
            
            redirect('site');
        }
       /* function logout()
        {
            $this->load->model('User_login_model');
            $id= $this->session->userdata('uid');
            $this->User_login_model->log_out_state($id);
            $this->session->sess_destroy();
            $udata = array('id' => '-1', 'logged_in' => FALSE);
            $this->session->set_userdata($udata);
            $this->session->set_userdata('ustate', 'notvalid');
            $this->session->unset_userdata('ustate', 'valid');
            redirect('user');
				
	}*/
	
        function register()
        {
            $this->view('site/register');			
	}
        
        function resend_mail(){
            $this->load->view('user/resendmail');			
	}
        
        //===============================================
        
        // userdata
        
        
        function View_data()
        {
            $id = $this->session->userdata('uid');
            $this->load->model('user_model');
            $data['rows'] = $this->user_model->viewUserDetails($id);
            $this->view('site/my_info',$data);
        }
        
        function edit_data()
        {
            $this->load->model('user_model');
            $user_id = $this->session->userdata('uid');
            $data['rows'] = $this->user_model->edit_user_inf($user_id);
            $is_done = $this->user_model->edit_user_inf($user_id);
            if($is_done){
                $data['check'] = TRUE;
                $data['rows'] = $this->user_model->edit_user_inf($user_id);	
            }else{
                $data['check']= FALSE;
            }
            $this->view('site/edit_register',$data);
        }
        
        

        function Add_articles(){
            $this->view('site/articles_new');
        }

        function View_articles()
        {
            $this->load->model('user_model');
            $user_id = $this->session->userdata('uid');
            $data['rows'] = $this->user_model->myArticles($user_id);
            $is_done  = $this->user_model->myArticles($user_id);
            if($is_done){
                $data['check'] = TRUE;
                $data['rows'] = $this->user_model->myArticles($user_id);	
            }else{
                $data['check']= FALSE;
            }
            $this->view('site/myarticles',$data);
        }

        function View_tree()
        {
            $this->load->view('user/mytree');
        }


        function Add_news(){
            $this->load->view('user/addnews');
        }			

        function View_news()
        {
            $this->load->model('user_model');
            $user_id = $this->session->userdata('uid');
            $data['rows'] = $this->user_model->myNews($user_id);
            $is_done  = $this->user_model->myNews($user_id);
            if($is_done){
                $data['check'] = TRUE;
                $data['rows'] = $this->user_model->myNews($user_id);	
            }else{
                $data['check']= FALSE;
            }
            $this->view('site/mynews',$data);
        }

        function View_photo()
        {
            $this->load->model('user_model');
            $user_id = $this->session->userdata('uid');
            $data['rows'] = $this->user_model->myPhoto($user_id);
            $is_done  = $this->user_model->myPhoto($user_id);
            if($is_done){
                $data['check'] = TRUE;
                $data['rows'] = $this->user_model->myPhoto($user_id);	
            }else{
                $data['check']= FALSE;
            }
            $this->view('site/myphoto',$data);
        }
        //////////////////////////////////////////////////////////////////////////////////
        
        
    function add_photo()
    {
        $this->load->library('form_validation');
        $this->load->model('user_model');
        $data['photos_category']=$this->user_model->get_categories();
        if($data['photos_category']==NULL){
           // echo "ahmed"; exit;
            $this->session->set_flashdata('notice_msg', 'من فضلك ادخل القسم أولا');
            redirect('users/add_photo/');
        }else{
            $data['photos_category'] = $this->user_model->get_photos_category();
            $this->form_validation->set_rules('photos_name', $this->lang->line('photos_name'), 'trim|required|xss_clean|htmlspecialchars');

            if ($this->form_validation->run() == FALSE)
            {
                //echo "ahmed"; exit;print_r($data['photos_category']);
                $this->view('site/addphoto',$data);
            }else{
                if(!empty($_FILES['userfile']['name']))
                    $photos_url = $this->upload_photos('userfile');
                   else
                    $photos_url = NULL;

                $this->user_model->create_photos($photos_url);
                $this->session->set_flashdata('success_msg', 'تم إضافة الصورة بنجاح');
                redirect('users/mypage');
            }
        }
    }
    
    
    
    function upload_photos($file)
    {
        $upload_cfg['upload_path'] = 'global/uploads/';
        $upload_cfg['encrypt_name'] = TRUE;
        $upload_cfg['allowed_types'] = 'gif|jpg|png';
        $this->upload->initialize($upload_cfg);
        if ($this->upload->do_upload($file))
        {
            $photos = $this->upload->data();
            return $photos['file_name'];
        }
        else
        {
            return false;
        }

    }  

        /*function Add_photo()
        {
            $this->load->model('user_model');
            $data['rows'] = $this->user_model->selectdepartPhoto();
            $is_done  = $this->user_model->selectdepartPhoto();
            if($is_done){
                $data['check'] = TRUE;
                $data['rows'] = $this->user_model->selectdepartPhoto();	
            }else{
                $data['check']= FALSE;
            }				
            $this->view('site/addphoto',$data);
        }
        */
        //===================================================================================================
        
        // news
        function News_details()
        {
            $array = $this->uri->uri_to_assoc(4);
            $id=$array['id']; 
            $this->load->model('news_model');
            $data['rows'] = $this->news_model->viewDetails($id);
            $data['rows2'] = $this->news_model->viewComments($id);
            $is_done  = $this->news_model->viewDetails($id);
            if($is_done){
                $data['check'] = TRUE;
                $data['rows'] = $this->news_model->viewDetails($id);
                $data['rows2'] = $this->news_model->viewComments($id);	
            }else{
                $data['check']= FALSE;
            }
            $this->view('site/news_details',$data);
        }
        
        function Insert_photo()
        {
            $this->load->model('user_model');
            $this->user_model->do_upload($_POST['title'],$_POST['section_id']);
            redirect('users/mypage');
        }
        
        // photo 
        //==============================================
        
        function edit_userphoto($user_id) 
        {
            
    //        $this->form_validation->set_error_delimiters("<span class='incorrect'>","</span>");
    //        $this->form_validation->set_rules("image_file_2","ملف الصورة","trim|required|xss_clean");

            if ($this->form_validation->run() == FALSE) {
          // echo $this->input->post('password')." - ".$this->input->post('password');
          // exit;
                $this->view('site/users_editphoto');
            }else{
                $image_file = $this->upload_image('image_file_2');
                $this->new_user->update_userphoto($image_file);
                $this->view('site/edit_msg');
            }
        }
    
    function upload_image($file) 
    {
        $upload_cfg['upload_path'] = "global/uploads";
        $upload_cfg['encrypt_name'] = TRUE;
        $upload_cfg['allowed_types'] = "gif|jpg|png|jpeg";
        $this->load->library("upload",$upload_cfg);
        
        if($this->upload->do_upload($file)){
            $image = $this->upload->data();
            return $image['file_name'];
        }else{
            return FALSE;
        }
    }
    
    function edit_userpass($user_id) 
        {
            
            
            $this->form_validation->set_error_delimiters("<span class='incorrect'>","</span>");
            $this->form_validation->set_rules("oldPass","رمز المرور القديم","required|callback_check_pass|xss_clean");
            $this->form_validation->set_rules("newPass","رمز المرور الجديد","required|min_length[8]|max_length[32]|matches[newPassConf]|xss_clean");
            $this->form_validation->set_rules("newPassConf","تأكيد رمز المرور الجديد","required|xss_clean");

            if ($this->form_validation->run() == FALSE) {             
                $this->view('site/edit_userpass');
            }else{               
                $this->new_user->edit_userpass($user_id);
                $data['msg'] = "تم تعديل كلمة الســر بنجـاح";
                $this->view('theme/msg',$data);
            }

        }
        
    function check_pass()
    {
        $user_username = $this->session->userdata('username');
        $u_pass = base64_encode($this->input->post('oldPass'));
        $check_username = $this->new_user->check_pass($user_username,$u_pass);
        if($check_username){            
            return TRUE;            
        }else{
            $this->form_validation->set_message('check_pass','رمز المرور الذي تم ادخاله غير صحيح');
            return FALSE;
        }
    }
 //================================================================================   
    /**
     * @example delete pic filename form database and remove file from directory
     * @access public
     * @return void
     */
    function delete_pic() {
        
            $pic_name = $this->edit_pic_model->get_data();
            foreach ($pic_name as $data) {
            $pic_path = $data->pic;
            $sex = $data->sex;
            $name = $data->player_name;
            }
            unlink(FCPATH."images/".$pic_path);
            
            if ($sex == "male") {$sex_pic = "male.jpg";} 
            elseif ($sex == "female") {$sex_pic ="female.jpg";}
            $pic = array(
                'pic'=>$sex_pic
            );
             
           if($insert = $this->edit_pic_model->insert_pic($pic)) {
              $this->session->set_flashdata('message',lang('delpic_message')); 
              if ($this->session->userdata('player_name') == $name) {
                    $this->session->set_userdata($pic);
                }
              $page = $this->session->userdata('page');
              $link = base_url()."site/index/$page";
              redirect($link);
           }
      }
        


        
	
       	
}