<?php
namespace App\Models;

use CodeIgniter\Model;

class userSignUp extends baseModel
{
   // protected $db;

    public function __construct()
    {
        parent::__construct();
    }
/*
 CREATE TABLE members_pending (
		id SERIAL,
		uuid UUID DEFAULT (gen_random_uuid()),
		username VARCHAR(50) NOT NULL, 
		firstname VARCHAR(50), 
		lastname VARCHAR(50), 
		email VARCHAR(50), 
		password VARCHAR(100)  NOT NULL,
		random_text VARCHAR(15),
		status INT DEFAULT 0,
		updated timestamp without time zone DEFAULT now(),
		added timestamp without time zone DEFAULT now()
	);
*/
public function startSignUp($in)
{
    $signup_mode = $in['mode'];
    switch($signup_mode){
      case 'START':
        return $this-> registerAccount($in);
        break;

        case 'VERIFY':
            return $this-> verifyAccount($in);
            break;

    }
  
}

public function verifyAccount($in)
{
    $insert_id=0;
    $error_msg='';
    $status=0;
    $valid_call = true;
    $sqlQ = "";
    $dat=[];

    $username = $in['username'];
    $uuid = $in['pend_uid'];
    $randomText = $in['random_text'];

    log_message('critical',  $username );

    

    if( $username=='' ||  $uuid =='' || $randomText =='' ){
        $valid_call=false;
        $error_msg='Invalid call for verify';
        $status=-1;
    }

    $sqlQ = "SELECT * FROM members WHERE username='".$in["username"]."' ";
    $query = $this->db->query($sqlQ);
    if($query &&  count($query->getResultArray())== 0  ){
    
    }
    else{
        $valid_call=false;
        $error_msg='Unable to continue';
        $status=-1;  
    }
    if ($valid_call){
        $sqlQ = "SELECT * FROM members_pending WHERE username='".$username."' AND random_text='$randomText'  AND uuid='$uuid' AND status IN(0,1)";
        $query = $this->db->query($sqlQ);
        if($query){
            $dat = $query->getResultArray()[0];
            // let see if we already have this account 
            $inData =[
                'username'=> $username,
                'email'=> $dat["email"],
                'password'=> $dat["password"],
                'firstname'=> $dat["firstname"],
                'lastname'=> $dat["lastname"]
            ];
            $sqlQ = "UPDATE members_pending SET status = 1  WHERE username='".$username."' AND status IN(0)";
            $this->db->query($sqlQ);
            $insert_id = $this->insert_db($inData, 'members');
            if( $insert_id>=0){ // for now 

                $status=100;
                $sqlQ = "UPDATE members_pending SET status = 5  WHERE username='".$username."' AND status IN(0,1)";
                $this->db->query($sqlQ);
            }

        }
    }

   // $passEnr =  $this->encryptmd5($in["password"]);
   // $randomText =  rand(1010101,999999);// rand(1010101,999999);
    // $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_pending 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;
    // }
    /*
    mermsemr_dev=> \d members
                                        Table "public.members"
   Column   |            Type             | Collation | Nullable |               Default
------------+-----------------------------+-----------+----------+-------------------------------------
 id         | integer                     |           | not null | nextval('members_id_seq'::regclass)
 username   | character varying(50)       |           | not null |
 firstname  | character varying(50)       |           |          |
 lastname   | character varying(50)       |           |          |
 email      | character varying(50)       |           |          |
 phone      | character varying(25)       |           |          |
 password   | character varying(100)      |           |          |
 status     | integer                     |           |          | 1
 added      | timestamp without time zone |           |          | now()
 loc        | inet                        |           |          |
 last_login | timestamp without time zone |           |          |
 acc_link   | character varying(15)       |           |          |
 gender     | character varying(2)        |           |          | 'U'::character varying
 dob        | timestamp without time zone |           |          |
 uuid       | uuid                        |           |          | gen_random_uui
    */
     return $inx = [
        'status' => $status,
        'error_msg' => $error_msg,
        'raw_data' => $in,
    ];

}
    public function registerAccount($in)
    {
        $insert_id=0;
        $uuid='';
        $status=0;
        $passEnr =  $this->encryptmd5($in["password"]);
        $randomText =  rand(101010,999999);// rand(1010101,999999);
        $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_pending 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' => $insert_id,
            'uuid' => $uuid,
            'status' => $status,
            'error_msg' => '',
            'raw_data' => $in,
        ];

    }

    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'];
    }

    public function tempCodes(){
        $sqlQ = "SELECT id AS insert_id,uuid,username,random_text FROM members_pending ORDER BY id DESC LIMIT 10";
        $query = $this->db->query($sqlQ);
       return $query->getResultArray();
    }

}

/*
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);*/
