<?php

namespace App\Controllers;

use CodeIgniter\API\ResponseTrait;

class WrenchAuth extends BaseController
{
    use ResponseTrait;

    public function promoLogin(){
        //  $in = $this->request->getPostGet();
        $raw_json = file_get_contents('php://input');
        $in = json_decode($raw_json, true);
        $out=[];
        $in["action"] = WRENCHBOARD_PROMO_LOGIN;

        $ret = $this->wrenchboard->wrenchboard_api($in, $out);
        $out['internal_return'] = $ret;
        log_message('critical', "***** ***** WrenchAuth::userLogin Ret = ".$ret );
        if ( $out['internal_return'] ==  100 ){
            $endpoint = "USER_SESSION-". str_pad($out["member_id"], 12, "0", STR_PAD_LEFT) ."-";
            log_message('critical', "***** ***** WrenchAuth::promoLogin USER_SESSION = ".$endpoint );
            $this->saveCache($endpoint,$out,15000);
        }else
        {
        //    log_message('critical', "***** ***** WrenchAuth::userLogin USER_SESSION = ".$fail_endpoint );
           // $this->saveCache($fail_endpoint,$outF,15000);
        }
        return $this->respond( $this->summaryReturnData($in,$out), 200);
    }
    public function userLogin(){
        log_message('critical', "***** ***** WrenchAuth::userLogin ****" );
      //  $in = $this->request->getPostGet();
        $raw_json = file_get_contents('php://input');
        $in = json_decode($raw_json, true);

        $in["action"] = WRENCHBOARD_ACCOUNT_LOGIN;
          if (!isset($in["login_mode"])){
              $in["login_mode"] = MOBILE_LOGIN;
          }


        // make safe for redis
        $outF["username"] = str_replace("@", "_", $in["username"]);
        $outF["username"] = str_replace(".", "_", $outF["username"]);
        $outF["original_username"] =  $in["username"];
        $outF["loc"] = $in["loc"];
        $fail_endpoint = "LOGIN_FAILED-".$outF["username"]."-";
        //===================REDIS DATA IN CASE OF FAIL
        $out_redis = $this->getCache($fail_endpoint); // try find in cache
        if (isset($out_redis["fail_count"]) && $out_redis["fail_count"] > 2){
            // we need stop here
            log_message('critical', "Danger ***** ***** WrenchAuth::userLogin FAIL = ".$out_redis["fail_count"] );
        }else{
            $outF["fail_count"] = isset(  $out_redis["fail_count"] ) ? $out_redis["fail_count"]+1:1;
        }
        $out=[];

            $ret = $this->wrenchboard->wrenchboard_api($in, $out);
            $out['internal_return'] = $ret;
            log_message('critical', "***** ***** WrenchAuth::userLogin Ret = ".$ret );
            if ( $out['internal_return'] ==  100 ){
                $endpoint = "USER_SESSION-". str_pad($out["member_id"], 12, "0", STR_PAD_LEFT) ."-";
                log_message('critical', "***** ***** WrenchAuth::userLogin USER_SESSION = ".$endpoint );
                $this->saveCache($endpoint,$out,15000);
                $this->neatCache($out);
            }else
            {
                log_message('critical', "***** ***** WrenchAuth::userLogin USER_SESSION = ".$fail_endpoint );
                $this->saveCache($fail_endpoint,$outF,15000);
            }

        return $this->respond( $this->summaryReturnData($in,$out), 200);
    }


    public function neatCache($in): int{
        // clean up user cache at start
        $endpoint = "ACCOUNT_HOMEBANNERS-".str_replace("-", "_", $in["uid"]);
        $this->deleteCache($endpoint);

        return 0;
    }
    public function qrLogin(){

        $raw_json = file_get_contents('php://input');
        $in = json_decode($raw_json, true);
        $out = [];

        $in["action"] = WRENCHBOARD_ACCOUNT_QRLOGIN;
        $in["login_mode"] = MOBILE_LOGIN;
        $pieces = explode("@", $in['username']);
        if ( count($pieces) == 3 ){
            $in['member_uid'] = $pieces[0];
            $in['member_username'] = $pieces[1];
            $in['family_uid'] = $pieces[2];
        }

        $outF["username"] =  $in['member_username'] ;
        $fail_endpoint = "QRLOGIN_FAILED-".$outF["username"]."-";
        //===================REDIS DATA IN CASE OF FAIL
        $out_redis = $this->getCache($fail_endpoint); // try find in cache
        if (isset($out_redis["fail_count"]) && $out_redis["fail_count"] > 2){
            // we need stop here
        }else{
            $outF["fail_count"] = isset(  $out_redis["fail_count"] ) ? $out_redis["fail_count"]+1:1;
        }

        log_message('critical', "************************ qrlogin   0001   ".$in['member_uid']);

        $ret = $this->wrenchboard->wrenchboard_api($in, $out);
        $out['internal_return'] = $ret;
        log_message('critical', "***** ***** WrenchAuth::userLogin Ret = ".$ret );
        if ( $out['internal_return'] ==  100 ){
            $endpoint = "QR_SESSION-". str_pad($out["member_id"], 12, "0", STR_PAD_LEFT) ."-";
            log_message('critical', "***** ***** WrenchAuth::qrLogin QR_SESSION = ".$endpoint );
            $this->saveCache($endpoint,$out,15000);
        }else
        {
            log_message('critical', "***** ***** WrenchAuth::qrLogin QR_SESSION = ".$fail_endpoint );
            $this->saveCache($fail_endpoint,$outF,15000);
        }
        return $this->respond( $this->summaryReturnData($in,$out), 200);

    }

    public function passwordReset(){

        $raw_json = file_get_contents('php://input');
        $in = json_decode($raw_json, true);
        $out = [];

        $in["action"] = WRENCHBOARD_RESET_PASSWORD;
        $in["rloc"] =  'WRENCHBOARD_RESET_PASSWORD'.rand(1000,9999);
        $email_string = $this->restringEmailRedis($in['email']);
        $endpoint = "PASS_RESET-". $email_string;
        $out_redis = $this->getCache($endpoint); // try find in cache
        if (isset($out_redis["password_reset_id"]) && $out_redis["password_reset_id"] > 0){
            // we need stop here
            return $this->respond( ["error"=>'Wait and try latter'], 200);
        }



        $ret = $this->wrenchboard->wrenchboard_api($in, $out);
        $out['internal_return'] = $ret;
        log_message('critical', "***** ***** WrenchAuth::passwordReset Ret = ".$ret );
        if ( $out['internal_return'] >=  0 ){
            log_message('critical', "***** ***** WrenchAuth::userLogin USER_SESSION = ".$endpoint );
            $this->saveCache($endpoint,$out,1500);
        }

        return $this->respond( $this->summaryReturnData($in,$out), 200);

    }

    private function restringEmailRedis($str_in){
        $str_out = str_replace("@", "_", $str_in);
        return str_replace(".", "_", $str_out);

    }
}

// WrenchAuth::userLogin