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

class Users extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->library('form_validation');
        // $this->load->library('session');
        $this->load->model('Authentication_model');
         ($this->verify_min_level(1)) ? '' : redirect('login');
         ($this->auth_level!=5) ? '' : redirect('logout');
    }


    public function index(){
        $view_data['records']=$this->mcommon->records_all('users',array('auth_level<'=>9));
        // echo $this->auth_level;
        // exit;
        $view_data['auth_level']=$this->session->auth_level;
        $data = array(
            'title' => 'Users',
            'page' => 'Users',
            'content' => $this->load->view('user/show', $view_data, true),
        );
        $this->load->view('base/main_template', $data);
    }

    public function users_add(){
        if (isset($_POST["submit"])){
            $username=$this->input->post('username');
            $name=$this->input->post('name');
            $mobile=$this->input->post('mobile');
            $email=$this->input->post('email');
            $password=$this->input->post('password');
            $this->form_validation->set_rules('username','username','required');
            $this->form_validation->set_rules('name','name','required');
            $this->form_validation->set_rules('mobile','mobile','required');
            $this->form_validation->set_rules('email','email','required');
            $this->form_validation->set_rules(
                'password',
                'Password',
                'required|min_length[8]|regex_match[/^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[@#$%^&+=!*_]).*$/]',
                array(
                    'required' => 'The password field is required.',
                    'min_length' => 'The password must be at least 8 characters long.',
                    'regex_match' => 'The password must contain at least one uppercase letter, one lowercase letter, one number, and one special character.'
                )
            );
                        if ($this->form_validation->run() == true) {
            $password=$this->hash_passwd($password);
            $insert_array=array(
                'username'=>$username,
                'name'=>$name,
                'mobile'=>$mobile,
                'email'=>$email,
                'passwd'=>$password,
                'auth_level'=>1,
                'created_at'=>date('d-m-Y'),
                'banned'=>0
            );

            $insert=$this->mcommon->common_insert('users',$insert_array);
            if($insert){
                $this->session->set_flashdata('alert_success','User Added successfully');
                redirect('Users');
            }
        }

        }

        $data = array(
            'title' => 'Users',
            'page' => 'Users',
            'content' => $this->load->view('user/add', $view_data, true),
        );
        $this->load->view('base/main_template', $data);

    }

    public function users_edit(){
        $id=$this->uri->segment(3);
        if (isset($_POST["submit"])){
            $user_id=$this->input->post('id');
            $username=$this->input->post('username');
            $name=$this->input->post('name');
            $mobile=$this->input->post('mobile');
            $email=$this->input->post('email');
            $this->form_validation->set_rules('username','username','required');
            $this->form_validation->set_rules('name','name','required');
            $this->form_validation->set_rules('mobile','mobile','required');
            $this->form_validation->set_rules('email','email','required');
            if($this->input->post('password')!== ""){
            $this->form_validation->set_rules(
                'password',
                'Password',
                'required|min_length[8]|regex_match[/^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[@#$%^&+=!*_]).*$/]',
                array(
                    'required' => 'The password field is required.',
                    'min_length' => 'The password must be at least 8 characters long.',
                    'regex_match' => 'The password must contain at least one uppercase letter, one lowercase letter, one number, and one special character.'
                )
            );
        }
            if ($this->form_validation->run() == true) {
            $old_password=$this->mcommon->specific_row_value('users',array('user_id'=>$user_id),'passwd');
            $password=$this->input->post('password')?$this->input->post('password'):$old_password;
            $password=$this->hash_passwd($password);

            $update_array=array(
                'username'=>$username,
                'name'=>$name,
                'mobile'=>$mobile,
                'email'=>$email,
                'passwd'=>$password,
                'auth_level'=>1
            );

            $update=$this->mcommon->common_edit('users',$update_array,array('user_id'=>$user_id));
            if($update){
            $this->session->set_flashdata('alert_warning','User Edited successfully');
            redirect('Users');
            }
        }
            
        }
        $view_data['users']=$this->mcommon->specific_row('users',array('user_id'=>$id)); 
        $data = array(
            'title' => 'Users',
            'page' => 'Users',
            'content' => $this->load->view('user/edit', $view_data, true),
        );
        $this->load->view('base/main_template', $data);
    
}

    public function users_delete(){
        $id=$this->uri->segment(3);
        $this->db->where('user_id',$id);
        $delete=$this->db->delete('users');
        if($delete){
            $this->session->set_flashdata('alert_danger','User Deleted successfully');
        }
        redirect('users');
    }

    public function hash_passwd($password, $random_salt = '')
    {
        // If no salt provided for older PHP versions, make one
        if (!is_php('5.5') && empty($random_salt)) {
            $random_salt = $this->random_salt();
        }

        // PHP 5.5+ uses new password hashing function
        if (is_php('5.5')) {
            return password_hash($password, PASSWORD_BCRYPT, ['cost' => 11]);
        }

        // PHP < 5.5 uses crypt
        else {
            return crypt($password, '$2y$10$' . $random_salt);
        }
    }

    public function valid_password($password = '')
    {
        $password = trim($password);
        $regex_lowercase = '/[a-z]/';
        $regex_uppercase = '/[A-Z]/';
        $regex_number = '/[0-9]/';
        $regex_special = '/[!@#$%^&*()\-_=+{};:,<.>§~]/';
        if (empty($password)) {
            $this->form_validation->set_message('valid_password', 'The {field} field is required.');
            return false;
        }
        if (preg_match_all($regex_lowercase, $password) < 1) {
            $this->form_validation->set_message('valid_password', 'The {field} field must be at least one lowercase letter.');
            return false;
        }
        if (preg_match_all($regex_uppercase, $password) < 1) {
            $this->form_validation->set_message('valid_password', 'The {field} field must be at least one uppercase letter.');
            return false;
        }
        if (preg_match_all($regex_number, $password) < 1) {
            $this->form_validation->set_message('valid_password', 'The {field} field must have at least one number.');
            return false;
        }
        if (preg_match_all($regex_special, $password) < 1) {
            $this->form_validation->set_message('valid_password', 'The {field} field must have at least one special character.' . ' ' . htmlentities('!@#$%^&*()\-_=+{};:,<.>§~'));
            return false;
        }
        if (strlen($password) < 8) {
            $this->form_validation->set_message('valid_password', 'The {field} field must be at least 8 characters in length.');
            return false;
        }
        if (strlen($password) > 32) {
            $this->form_validation->set_message('valid_password', 'The {field} field cannot exceed 32 characters in length.');
            return false;
        }
        return true;
    }

    public function view_details(){
        $id=$this->uri->segment(3);
        $view_data['users']=$this->mcommon->specific_row('users',array('user_id'=>$id)); 
        $data = array(
            'title' => 'Users',
            'page' => 'Users',
            'content' => $this->load->view('user/user_details', $view_data, true),
        );
        $this->load->view('base/main_template', $data);
    }
}