<?php

namespace App\Controllers;

use CodeIgniter\API\ResponseTrait;

class Users extends BaseController
{

    use ResponseTrait;

    var $request;

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

    private function assignInternalEmail($id, $uid){
        $intE = "message+".str_pad($id, 12, "0", STR_PAD_LEFT)."@chiefsoft.com";
        $mysql =  "UPDATE customers SET internal_email='".$intE."' WHERE internal_email IS NULL AND id = $id AND uid = '".$uid."'";
        $this->db->query($mysql);
        return $this->readCustomer($uid);
    }
    public function userAddCard(){
        $in =  $this->request->getPost();

        $loan_uid = $in["application_uid"];
//        $userUid = trim($in["uid"]);
//        $mysql ="SELECT id,internal_email from customers where uid ='"+$userUid+"'";
//        $query = $this->db->query($mysql);
        $row   = $this->readCustomer($in["uid"]);
        $userID =  0;
        $CustomerCode = '';
        if (count($row)> 0){
            $userID = $row["id"];
            if (  $row["internal_email"] == '' ){
                  $row = $this->assignInternalEmail($userID, $in["uid"]);
            }
            $userID = $row["id"];
            $userInternalEmail = $row["internal_email"];
            $CustomerCode  =  $row["customer_code"];
        }


        if ( $CustomerCode  == ''){

            $in_data = [
                "email" => $userInternalEmail,
            ];

            $createUserResult = $this->APIcall("POST", "http://10.10.10.48:6334/create-customer", json_encode($in_data));
            $CustomerCode  =  $createUserResult["customer_code"];
            $mysql  = "UPDATE customers SET  customer_code = '".$CustomerCode."' WHERE id = $userID AND uid = '".$in["uid"]."' ";
            $this->db->query($mysql);
           // $CustomerCode = $createUserResult["customer_code"];
        }

        $in_data = [
            "email" => $userInternalEmail,
            "amount" => 500,
            "plan" => "PLN_qh2dasmlhweqa1l",
        ];
        $initResult = $this->APIcall("POST", "http://10.10.10.48:6334/initialize-transaction-with-plan", json_encode($in_data));

        $data = [
            'call_return' => '100',
            'customer_code' => $createUserResult["customer_code"],
            'redirect_url' =>  $initResult['authorization_url'],
        ];
        //    'init_subscription' =>  $initResult
        return $this->respond($data, 200);
    }
    public function userDash(){
        $statusDetail[2] =[
            "text" => "Pending",
            "button" => false,
            "advise" => 'Awaiting employers verification'
        ];
        $statusDetail[4] =[
            "text" => "Add Card",
            "button" => true,
             "advise" => 'Add payment card to continue'
        ];

        $statusDetail[7] =[
            "text" => "Canceled",
            "button" => false,
            "advise" => 'Application is cancelled'
        ];

        $in =  $this->request->getGet();
        $data = [];
        if ($in['uid'] !=''){
            $query = $this->db->query("SELECT * FROM customers WHERE uid = '".$in['uid']."' ");

            $row   = $query->getRowArray();

            $loanResult  = $this->userLoan($in['uid']);
            $processLoan = [];
            foreach ($loanResult as $value) {
                $value["status_text"] = $statusDetail[ $value["status"] ];
                $processLoan[] = $value;
            }

            $data = [
                'call_return' => '100',
                'customer' =>  $row,
                'loans' => $processLoan,
            ];
            return $this->respond($data, 200);
            //'loans' => $loanResult,
        }
        else{
            return $this->respond(['error'=>'empty uid'], 400);
        }

        //return $this->respond([], 400);
    }

    /*
 digifi_db=# SELECT c.added,c.loan_amount,c.payment_month,a.status,a.loan_uid FROM agreements a LEFT JOIN applications c ON c.uid::text = a.loan_uid;
           added            | loan_amount | payment_month | status |               loan_uid
----------------------------+-------------+---------------+--------+--------------------------------------
 2024-06-01 17:31:51.124457 |       55555 |            18 |      1 | 21f7ffb3-c5a3-4f36-a419-464f91b3645d
 2024-06-04 16:54:22.86312  |     1000000 |             6 |      1 | 808c6df4-5b9c-4d52-944b-918f1f9576d3
 2024-06-04 16:58:53.691384 |      100000 |            18 |      1 | 4ca44a89-1bb6-4af3-93c0-71a03fe2d407
 2024-06-04 17:10:52.018562 |      500000 |            12 |      1 | 67cb2d61-9db5-470e-b542-a70bc828a064
(4 rows)

 */
    public function userAgreement(){
        $query = $this->db->query("SELECT c.added,c.loan_amount,c.payment_month,a.status,a.loan_uid FROM agreements a LEFT JOIN applications c ON c.uid::text = a.loan_uid");
        $data =  $query->getResult('array');

        return $this->respond($data, 200);
    }
    private function userLoan($uid){
        $query = $this->db->query("SELECT a.uid AS application_uid,a.loan_amount,
                                   a.payment_month,a.status,a.added,
                                   a.updated 
                                   FROM applications a 
                                   LEFT JOIN customers c ON c.uid = a.customer_uid WHERE a.customer_uid='".$uid."' ORDER BY a.id DESC");
        return $query->getResult('array');
    }
    public function userProfile(){
        $in =  $this->request->getGet();
        $data = [];
        if ($in['uid'] !=''){
            $query = $this->db->query("SELECT * FROM customers WHERE uid = '".$in['uid']."' ");
            $row   = $query->getRowArray();
            $data = [
                'call_return' => '100',
                'customer' =>  $row
            ];
            return $this->respond($data, 200);
        }else{
            return $this->respond(['error'=>'empty uid','inn'=>$in,],  400);
        }

      //  return $this->respond([], 400);
    }

    public function userDashProfile(){
        $in =  $this->request->getGet();
        $data = [];
        if ($in['uid'] !=''){
            $query = $this->db->query("SELECT * FROM customers WHERE uid = '".$in['uid']."' ");
            $row   = $query->getRowArray();
            $data = [
                'call_return' => '100',
                'customer' =>  $row
            ];
            return $this->respond($data, 200);
        }else{
            return $this->respond(['error'=>'empty uid','inn'=>$in,],  400);
        }

        //  return $this->respond([], 400);
    }

    public function userDashEmployer(){
        $in =  $this->request->getGet();
        $data = [];
        if ($in['uid'] !=''){
            $query = $this->db->query("SELECT uid FROM customers WHERE uid = '".$in['uid']."' ");
            $row   = $query->getRowArray();
            $empl=
                [
                    "employer_uid" => "9cb678e0-0697-4cc9-9bf0-3f40a3c989fb",
                    "name" => "ChiefSoft Works LLC",
                    "official_email" => "workemail@work.com",
                    "industry" => "Education",
                    "job_sector" => "Non-Profit",
                    "job_title" => "Manager",
                    "start_date" => "10-10-2000",
                    "salary_date" => "15-08-2024",
                    "annual_salary" => "10000000",
                    "net_montlty" => "80000",
                    "employee_id" => "1234567890",
                    "highest_eductaion" => "Masters Degree"
                ];
            $data = [
                'call_return' => '100',
                'customer' =>  $row,
                'employer' => $empl
            ];
            return $this->respond($data, 200);
        }else{
            return $this->respond(['error'=>'empty uid','inn'=>$in,],  400);
        }

        //  return $this->respond([], 400);
    }

    public function userCustomer(){
        $in =  $this->request->getGet();
        $data = [];
        if ($in['uid'] !=''){
            $query = $this->db->query("SELECT * FROM customers WHERE uid = '".$in['uid']."' ");
            $row   = $query->getRowArray();
            $data = [
                'call_return' => '100',
                'customer' =>  $row
            ];
            return $this->respond($data, 200);
        }else{
            return $this->respond(['error'=>'empty uid','inn'=>$in,],  400);
        }

        //  return $this->respond([], 400);
    }

    public function userDashReferences(){
        $in =  $this->request->getGet();
        $data = [];
        if ($in['uid'] !=''){
            $query = $this->db->query("SELECT * FROM customers WHERE uid = '".$in['uid']."' ");
            $row   = $query->getRowArray();
            $data = [
                'call_return' => '100',
                'customer' =>  $row
            ];
            return $this->respond($data, 200);
        }else{
            return $this->respond(['error'=>'empty uid','inn'=>$in,],  400);
        }

        //  return $this->respond([], 400);
    }

    public function userPaymentStatus(){
        $in =  $this->request->getGet();
        $data = [];
        if ($in['uid'] !=''){
            $query = $this->db->query("SELECT uid,event , customer_code , plan_name , plan_code ,subscription_code  ,
                                              amount , authorization_code  , 
                                              gateway_response   , gateway_status  , reference  ,added FROM charges WHERE reference = '".$in['reference']."' ");
            $row   = $query->getRowArray();
            $data = [
                'call_return' => '100',
                'payment' =>  $row
            ];
            return $this->respond($data, 200);
        }else{
            return $this->respond(['error'=>'empty uid','inn'=>$in,],  400);
        }

        //  return $this->respond([], 400);
    }

}