<?php

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

require APPPATH . '/libraries/REST_Controller.php';

/*
 * Changes:
 * 1. This project contains .htaccess file for windows machine.
 *    Please update as per your requirements.
 *    Samples (Win/Linux): http://stackoverflow.com/questions/28525870/removing-index-php-from-url-in-codeigniter-on-mandriva
 *
 * 2. Change 'encryption_key' in application\config\config.php
 *    Link for encryption_key: http://jeffreybarke.net/tools/codeigniter-encryption-key-generator/
 * 
 * 3. Change 'jwt_key' in application\config\jwt.php
 *
 */

class user_management extends REST_Controller
{
    /**
     * URL: http://localhost/CodeIgniter-JWT-Sample/auth/token
     * Method: GET
     */

     function __construct()
    {
        // Construct the parent class
        parent::__construct();
        $this->load->model('user_management_model');
       
    }



    public function csrUserRegistration_post()
    {

        $user_data = $this->post();
        $user_id = null;
        $user_data['password'] = md5($user_data['password']);
        $org_info = array_key_exists('org_info', $user_data) && count($user_data['org_info']) ? $user_data['org_info'] : array();
        unset($user_data['org_info']);

        if($user_data['id'] != "" || $user_data['id'] != null)
        {
             $user_id = $this->user_management_model->updateRecords($user_data,CSR_USER,array('id' => $user_data['id']));
             if($user_id)
             {
                  $org_info['user_id'] = $user_data['id'];
                if(isset($org_info['id']))
                {
                     if(($org_info['id'] != "" || $org_info['id'] != null))
                     {
                          // $org_info['updated_by'] = $user_data['updated_by'] ;
                           $org_id = $this->user_management_model->updateRecords($org_info,CSR_USER_ORG,array('id' => $org_info['id']));
                     }
                     else
                     {
                         $org_info['created_by'] = $user_data['updated_by'] != "" ? $user_data['updated_by'] : $user_data['created_by']; 
                         $org_id = $this->user_management_model->saveRecords($org_info,CSR_USER_ORG);
                     }
                 }
             }
        }
        else
        {
         

          $user_id = $this->user_management_model->saveRecords($user_data,CSR_USER);
          if($user_id && count($org_info))
          {
             $org_info['user_id'] = $user_id;
             $org_info['created_by'] = $user_data['created_by'];
  
             $org_id = $this->user_management_model->saveRecords($org_info,CSR_USER_ORG);

             //trigger Reg sucessfull Mail

             $mail_configs = $this->user_management_model->selectCustomRecords(array('*'),array('mail_code' => 'REG'),CSR_MAIL_CONTENTS);
             $fromMail = $mail_configs[0]['from_mail'];
             $display_name = $mail_configs[0]['display_name'];
             $subject = $mail_configs[0]['subject'];
             $tomail = $user_data['email'];
             $content = $mail_configs[0]['content'];
             $content = str_replace('{{user}}',$user_data['name'],$content);
             $this->load->helper('mymail');
             MYMAIL::sendmyMail($fromMail,$display_name, $tomail,$subject,$content);
   
          }
        }

        if(($user_id))
        {
                $data['dataStatus'] = true;
                $data['status'] = REST_Controller::HTTP_OK;
                $data['records'] = $user_id;
                $this->response($data,REST_Controller::HTTP_OK);
        }   
        else
        {
                $data['dataStatus'] = false;
                $data['status'] = REST_Controller::HTTP_NOT_FOUND;
                $data['msg'] = 'Try Later!';
                $this->response($data,REST_Controller::HTTP_OK);
        }
    }

    public function csrUserLogin_post()
    {
        $login_data = $this->post();
        $email = trim($login_data['email']);
        $password = trim($login_data['password']);

        $user = $this->db->SELECT('id,name,email,mobile,user_type')->FROM(CSR_USER.' as CSR_USER')->WHERE('CSR_USER.email',$email)->WHERE('CSR_USER.password',md5($password))->WHERE('CSR_USER.isactive',1)->GET()->row(); 
        //print_r($this->db->last_query());
       // print_r($user);die();
        if(($user))
        {
                $iat = time();
                $one_month_time = (60 * 60 * 24 * 30);
                $exp = $iat + $one_month_time;
                $tokenData = array();
                $tokenData['userid'] = $user->id; 
                $tokenData['username'] = $user->name; 
                $tokenData['iss'] = 'https://www.emis.com'; 
                $tokenData['iat'] = $iat; 
                $tokenData['exp'] = $exp; 
                $tokenData['sub'] = 'csr_app'; 
                $tokenData['user_type'] = $user->user_type ; 
                $output['token'] = AUTHORIZATION::generateToken($tokenData);
                $output['userdata'] = $user;
                $output['dataStatus'] = true;
                $this->set_response($output, REST_Controller::HTTP_OK);
        }
        else
        {

                $data['dataStatus'] = false;
                $data['status'] = REST_Controller::HTTP_NOT_FOUND;
                $data['msg'] = 'Invalid login credentials!';
                $this->response($data,REST_Controller::HTTP_OK);
        }
       
    }


    public function getMyProfile_get()
    {
        $userid = $this->uri->segment(2);
        if($userid != "" && is_numeric($userid))
        {

            $user_data = $this->user_management_model->getProfileData($userid);

            $contribution_data = $this->user_management_model->getContributionData($userid);

            $kt_contribution_data = $this->user_management_model->getKTContributionData($userid);

            if($user_data)
            {
                $data['dataStatus'] = true;
                $data['status'] = REST_Controller::HTTP_OK;
                $data['records'] = array('user_data' => $user_data,'contribution_data' => $contribution_data);
                $this->response($data,REST_Controller::HTTP_OK);
            }
            else
            {
                $data['dataStatus'] = false;
                $data['status'] = REST_Controller::HTTP_NOT_FOUND;
                $data['msg'] = 'User not Found..!';
                $this->response($data,REST_Controller::HTTP_OK);
            }

        }
        else
        {
                $data['dataStatus'] = false;
                $data['status'] = REST_Controller::HTTP_NOT_FOUND;
                $data['msg'] = 'In Appropriate Call...';
                $this->response($data,REST_Controller::HTTP_OK);
        }
    }

    public function forgetPwd_post()
    {
        $mail = $this->post('mail');
        $mobile = $this->post('mobile');
         
        $user = $this->user_management_model->selectCustomRecords(array('*'),array('mobile' => $mobile,'email' => $mail),CSR_USER);
        // print_r($this->db->last_query());die();
        if(count($user))
        {
                $new_pwd = $this->generateRandomPwd();
                $update = $this->user_management_model->updateRecords(array('password' => md5($new_pwd)),CSR_USER,array('id' => $user[0]['id']));
                if($update){ log_message("ERROR",('Pwd changed to'.$mail)); }
                $mail_configs = $this->user_management_model->selectCustomRecords(array('*'),array('mail_code' => 'FORGRTPWD'),CSR_MAIL_CONTENTS);
             $fromMail = $mail_configs[0]['from_mail'];
             $display_name = $mail_configs[0]['display_name'];
             $subject = $mail_configs[0]['subject'];
             $tomail = $user[0]['email'];
             $content = $mail_configs[0]['content'];
             $content = str_replace('{{user}}',$user[0]['name'],$content);
             $content = str_replace('{{newpwd}}',$new_pwd,$content);
             $this->load->helper('mymail');
             MYMAIL::sendmyMail($fromMail,$display_name, $tomail,$subject,$content);

             $data['dataStatus'] = true;
             $data['status'] = REST_Controller::HTTP_OK;
             $data['msg'] = 'Password changed successfully..! Check Your Registerd Mail.';
             $this->response($data,REST_Controller::HTTP_OK);
                
        }
        else
        {
                $data['dataStatus'] = false;
                $data['status'] = REST_Controller::HTTP_NOT_FOUND;
                $data['msg'] = 'No User Detail Found..!';
                $this->response($data,REST_Controller::HTTP_OK);
        }
    }

    function generateRandomPwd()
    {
         $alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
         $pass = array(); //remember to declare $pass as an array
            $alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
            for ($i = 0; $i < 8; $i++) {
                $n = rand(0, $alphaLength);
                $pass[] = $alphabet[$n];
            }
            return implode($pass); 
    }

    public function checkExistCredentials_post()
    {
        $field = $this->post('key');
        $field_data = $this->post('data');
        $display_text =  array('mobile' =>'Mobile number already taken.','email' => 'Email ID already taken.');   
        $user = $this->user_management_model->selectCustomRecords(array('*'),array($field => $field_data),CSR_USER);

        if(count($user))
        {
             $data['dataStatus'] = false;
             $data['status'] = REST_Controller::HTTP_OK;
             $data['msg'] = $display_text[ $field ];
             $this->response($data,REST_Controller::HTTP_OK);
        }
        else
        {
             $data['dataStatus'] = true;
             $data['status'] = REST_Controller::HTTP_OK;
             $data['msg'] = ($field . ' is ready to occupy');
             $this->response($data,REST_Controller::HTTP_OK);
        }
    }
    

}