<?php


namespace App\Controllers;

use CodeIgniter\API\ResponseTrait;
use Exception;
use Firebase\JWT\JWT;

class DigiFiBVN extends BaseController
{
    use ResponseTrait;
   // protected $db;

    var $request;

    function __construct()
    {
        $this->request = \Config\Services::request();
    }

    private function verifyOTP($verification_id, $otp): bool{
        $ret = false;
        $sqlC =  "  SELECT * FROM 
                    bvn_checks 
                    WHERE pin ='".$otp."' 
                    AND uid= '".$verification_id."' ";

        $query = $this->db->query($sqlC);
        $results = $query->getResultArray();
        if ( count($results) > 0  ){

            $ret = true;
        }
        return $ret;
    }

    public function completeBVNVerify(){

        $data = $this->request->getPost();
        if ($data['bvn'] != ''
            && $data['verification_id'] !=''
            && $data['otp'] !=''
           ) {
            if (  !$this->verifyOTP($data['verification_id'], $data['otp']) /* $data['otp'] !='12345'*/){
                $response = [
                    'message' => 'Invalid account or OTP',
                    'call_return' => '0',
                    'customer'=> [],
                    "token" =>''
                ];
                return $this->respond($response, 200);
            }

            $customer = [];
            // we need OTP verified here to continue

           $sqlC =  "SELECT * FROM bvn_checks WHERE bvn ='".$data['bvn']."' AND uid='".$data['verification_id']."'";
           $query = $this->db->query($sqlC);
           $results = $query->getResultArray();
           if ( count($results) > 0  ){
              $sqlM = "SELECT * FROM customers WHERE bvn = '".$data['bvn']."' ";
              $qu0 = $this->db->query($sqlM);
              $customer = $qu0->getResultArray();
              if ( count( $customer) == 0 ){
                  // lets create this USER
                  $udata = [
                      'bvn' => $data['bvn'],
                      'firstname' =>'firstname-'.rand(1,1000),
                      'lastname' => 'lastname-'.rand(1,1000)
                  ];

                  $udata = [
                      'bvn' => $data['bvn'],
                      'firstname' => $results[0]["firstname"],
                      'lastname' =>  $results[0]["lastname"],
                  ];

                  $customer =  $this->insert_db('customers',$udata);
                  /** ---  */
                  $sqlM = "SELECT * FROM customers WHERE bvn = '".$data['bvn']."' ";
                  $qu0 = $this->db->query($sqlM);
                  $customer = $qu0->getResultArray();

              }
           }

            $final_out = $data;
            $key = getenv('JWT_SECRET');
            $iat = time(); // current timestamp value
            $exp = $iat + 3600;

            $payload = array(
                "iss" => "Issuer of the JWT",
                "aud" => "Audience that the JWT",
                "sub" => "Subject of the JWT",
                "iat" => $iat, //Time the JWT issued at
                "exp" => $exp, // Expiration time of token
                "user_detail" => $final_out,
            );

            $token = JWT::encode($payload, $key, 'HS256');

            $response = [
                'message' => 'Account Verified',
                'call_return' => '100',
                'customer'=> $customer,
                "token" =>$token
            ];

            return $this->respond($response, 200);
        } else {
            $response = [
                'message' => 'Invalid account found',
                'call_return' => '100',
                'token' => ''
            ];
            return $this->fail($response, 409);
        }
    }

    /*
        "uid" => "3119b744-42ad-4834-bb83-b737588754ca",
        "firstname"=>'Firstname',
        "lastname"=>'lastname',
        "last_login"=> "2024-04-26 13:35:19.750027",
        "test" => $results,
     */

    //+2347032847884
    //
    // sendSMS($smsNumber,$smsMessage)




    public function startBVNVerify()
    {
        $data = $this->request->getPost();
        $data['verify_mode'] = 100;
        $data['firstname'] = "John";
        $data['lastname'] = "Doe";
        $data['dob'] = "04-04-1944";

        if ($data['bvn'] != '') {
            if ( $data['verify_mode'] != 100 ){
                $data['bvn'] = "10000000001";  //overwrite for test
            }

            $bvnData = $this->APIcall("POST", "http://10.10.10.48:6332/api/verify/bvn", json_encode($data));
            // send SMS HERE
            $pin =  rand(10000, 99999);
//2347036251482
        //   $smsSend =  $this->sendSMS("2347032847884", "This is your pin number ". $pin);
        //    $smsSend =  $this->sendSMS("2347036251482", "This is your pin number ". $pin);
        //    $smsSend =  $this->sendSMS("+2347036251482", "This is your pin number ". $pin);
        //    $smsSend =  $this->sendSMS("2349063572875", "This is your pin number ". $pin);
            $smsSend =  $this->sendSMS("+2349063572875", "This is your OTP number ". $pin);

            //+2347032847884
            //
            // sendSMS($smsNumber,$smsMessage)

            /*
               SMS API PORTAL
                https://accounts.termii.com/#/
                Email - mdigifi@gmail.com
                Password - Clust@r24
             */

            $udata = [
                'bvn' => $data['bvn'],
                'pin' => $pin
            ];
           $addedData =  $this->insert_db('bvn_checks',$udata);

            if(  $addedData["uid"] ==''){
                $response = [
                    'message' => 'Failure',
                    'call_return' => '100',
                    'token' => '',
                    'test_bvn' => $bvnData
                ];
                return $this->fail($response, 500);
            }

            $workingUID = $addedData["uid"];

            /*
             *|            Type             | Collation | Nullable |                Default
-------------+-----------------------------+-----------+----------+----------------------------------------
 id          | integer                     |           | not null | nextval('bvn_checks_id_seq'::regclass)
 uid         | uuid                        |           |          | uuid_generate_v4()
 bvn         | character varying(15)       |           | not null |
 status      | integer                     |           |          | 1
 added       | timestamp without time zone |           |          | now()
 updated     | timestamp without time zone |           |          | now()
 firstname   | character varying(35)       |           |          |
 lastname    | character varying(35)       |           |          |
 middlename  | character varying(35)       |           |          |
 gender      | character varying(5)        |           |          |
 birthdate   | timestamp without time zone |           |          |
 phone       | character varying(35)       |           |          |
 nationality | character varying(15)       |           |          |
Indexes:
    "bvn_checks_id_key" UNIQUE CONSTRAINT, btree (id)

                   "bvn": "10000000001",
        "firstname": "John",
        "lastname": "Doe",
        "middlename": "Favor",
        "phone": "080000000001",
        "birthdate": "1944-04-04",
        "gender": "m",
        "nationality": "Nigerian",

             */
            $bvn = $data['bvn'];

            $firstname =  $bvnData["res"]["data"]["firstname"];
            $lastname =  $bvnData["res"]["data"]["lastname"];
            $middlename =  $bvnData["res"]["data"]["middlename"];
            $phone =  $bvnData["res"]["data"]["phone"];
            $birthdate =  $bvnData["res"]["data"]["birthdate"];
            $gender =  $bvnData["res"]["data"]["gender"];
            $nationality =  $bvnData["res"]["data"]["nationality"];



            $sqlUpdate = "UPDATE bvn_checks 
                        SET firstname ='$firstname', 
                            lastname='$lastname', 
                            middlename='$middlename' , 
                            phone='$phone' , 
                            birthdate='$birthdate' ,
                            gender='$gender' , 
                            nationality='$nationality' 
                        WHERE bvn = '$bvn' 
                        AND uid::text = '".$workingUID."' ";
            log_message('critical', "BVN UPDATE URL FINAL =>  ".$sqlUpdate );
            $query = $this->db->query($sqlUpdate);

            $response = [
                'message' => 'Verification text sent to user',
                'call_return' => '100',
                'sms_send' => $smsSend,
                'verification_id' => $addedData["uid"],
                'status' => $bvnData["res"]["status"],
                'test_bvn' => $bvnData["res"]["data"]
            ];

            return $this->respond($response, 200);
        } else {
            $response = [
                'message' => 'Failure',
                'call_return' => '100',
                'token' => ''
            ];
            return $this->fail($response, 409);
        }


        //return json_encode( $response );

    }
}
