<?php
namespace App\Models;

use CodeIgniter\Model;

class usersResetPass extends baseModel
{
   // protected $db;

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

public function resetPass($in)
{
    $change_state = $in['stage'];

    switch ($change_state) {
        case START_PASS_CHANGE:
           return $this->startPassReset($in);
            break;

        case CONFIRM_PASS_PIN:
            return $this->verifyPassReset($in);
            break;

        case CONFIRM_PASS_CHANGE:
            return $this->completePassReset($in);
            break;
    }

    return 
        [
        'error_mode'=>-1
        ];
} 

private function completePassReset($in){

    $status   = -1;
    $error_msg= '';
    $msg = '';
    $username =    isset($in['username'])?   $in['username']:   '';
    $reset_uuid =  isset($in['reset_uuid'])? $in['reset_uuid']: ''; 
    $random_text = isset($in['random_text'])?$in['random_text']:'';
    $member_uid =  isset($in['member_uid'])? $in['member_uid']: '';

   $selectData=['*'];
   $whereAray=[
        'uuid'=>$reset_uuid ,
        'username' =>$username,
        'random_text'=>$random_text,
        'member_uid'=> $member_uid
   ];
  
    $first_check =  $this->select_db($selectData,$whereAray, 'members_password_reset');

    if ($first_check['status']> 0 && $first_check['record_count']> 0){
       $status = 1;
       $msg='Ready to reset password';
    }  else{
        $error_msg ="Unable to continue";
        $status =  0;
    }


    return $inx = [
        'username' => $username,
        'reset_uuid' => $reset_uuid ,
        'member_uid' => $member_uid,
        'status' => $status,
        'msg' => $msg,
        'error_msg' => $error_msg,
        'raw_data' => $in,
    ];
    
   /* return 0;*/
}
private function verifyPassReset($in){

    $member_uid = '';
    $error_msg='';
    $status = -1;
    $username =  isset($in['username'])?$in['username']:'';
    $reset_uuid =  isset($in['reset_uuid'])?$in['reset_uuid']:''; 
    $random_text =  isset($in['random_text'])?$in['random_text']:'';
   // $random_text =  isset($inx['random_text'])?$inx['random_text']:'';

   $selectData=['*'];
   $whereAray=[
        'uuid'=>$reset_uuid ,
        'username' =>$username,
        'random_text'=>$random_text,
   ];
  
    $first_check =  $this->select_db($selectData,$whereAray, 'members_password_reset');

    if ($first_check['status']> 0 && $first_check['record_count']> 0){
       $member_uid = $first_check['result'][0]['member_uid'];
       $status = 1;
    }
    else{
        $error_msg ="Unable to continue";
        $status =  0;
    }

    return $inx = [
        'username' => $username,
        'reset_uuid' => $reset_uuid ,
        'member_uid' => $member_uid,
        'status' => $status,
        'error_msg' => $error_msg,
        'raw_data' => $in,
    ];
}
    private function startPassReset($in)
    {
        $insert_id=0;
        $uuid='';
        $status=0;
        $passEnr = '';// $this->encryptmd5($in["password"]);
        $randomText =  rand(101010,999999);// rand(1010101,999999);
        $pdata =[];
        $username= trim($in["username"]);

        $sqlQ = "SELECT id AS member_id,uuid FROM members WHERE username='".$in["username"]."' ";
        $query = $this->db->query($sqlQ);
        $data['user_data'] = $query->getResultArray();

        if (count($data['user_data']) == 1) {
            $userData = $data['user_data'][0];
            $pdata = [
                'username'=> $in["username"],
                'member_uid'=> $userData["uuid"],
                'random_text' =>  $randomText,
                'status'=>1
            ];

            $insert_id = $this->insert_db($pdata, 'members_password_reset');
            if( $insert_id>=0){ 
                // for now 
                $sqlQ = "SELECT * FROM members_password_reset WHERE username='$username' AND random_text='$randomText' ";
                $query = $this->db->query($sqlQ);
                $new_add = $query->getResultArray()[0];
                return $inx = [
                    'insert_id' => $new_add['id'],
                    'uuid' => $new_add['uuid'],
                    'error_msg' => '',
                    'raw_data' => $in,
                ];
            }
        }

 
/*
 CREATE TABLE members_password_reset (
		id SERIAL,
		uuid UUID DEFAULT (gen_random_uuid()),
		username VARCHAR(50) NOT NULL, 
		member_uid VARCHAR(50), 
		random_text VARCHAR(15),
		status INT DEFAULT 0,
		updated timestamp without time zone DEFAULT now(),
		added timestamp without time zone DEFAULT now()
	);

        $inData =[
            'username'=> $in["username"],
            'email'=> $in["email"],
            'password'=> $passEnr,
            'firstname'=> $in["firstname"],
            'lastname'=> $in["lastname"],
            'random_text' => $randomText
        ];

        $insert_id = $this->insert_db($inData, 'members_pending');
        if( $insert_id>=0){ // for now 
            $sqlQ = "SELECT id AS insert_id,uuid FROM members WHERE username='".$in["username"]."' AND random_text='$randomText'  AND password='$passEnr' LIMIT 1";
            $query = $this->db->query($sqlQ);
            $dat = $query->getResultArray();
            $insert_id = $dat[0]['insert_id'];
            $uuid = $dat[0]['uuid'];
            $status=1;
        }
        */

        return $inx = [
            'insert_id' => '0',
            'uuid' => '',
            'error_msg' => 'Unable to continue',
            'raw_data' => $in,
        ];

    }

    public function tempCodes(){
        $sqlQ = "SELECT username,uuid,member_uid,random_text FROM members_password_reset WHERE status = 1 ORDER BY id DESC LIMIT 10";
        $query = $this->db->query($sqlQ);
       return $query->getResultArray();
    }

    private function encryptmd5($rwStstr){

        $sqlQ = "SELECT md5('$rwStstr') AS md5_string";
        log_message('critical', "encryptmd5-Entered".$sqlQ  );
        $query = $this->db->query($sqlQ);
        $data = $query->getResultArray();
        return $data[0]['md5_string'];
    }



}

/*
CREATE TABLE members_login_hx (
	id SERIAL,
	member_id INT REFERENCES members(id) NOT NULL,	
	channel VARCHAR(15), 
	added timestamp without time zone DEFAULT now(),
	loc INET
	);
ALTER TABLE ONLY members_login_hx
    ADD CONSTRAINT members_login_hx_id_key UNIQUE (id);*/
