<?php

namespace App\Controllers;

use CodeIgniter\HTTP\ResponseInterface;


class Employers  extends BaseController
{
    public function approvedEmployersList()  :ResponseInterface {
        $query = $this->db->query("SELECT uid,name FROM employer_sector");
        $employer_sector   = $query->getResult('array');

        $query = $this->db->query("SELECT uid,name FROM salary_sources");
        $salary_sources   = $query->getResult('array');

        $query = $this->db->query("SELECT * FROM employers WHERE signatory_count > 0 ORDER BY name ASC");
        $row   = $query->getResult('array');
        $data = [
            'call_return' => '100',
            'salary_sources' => $salary_sources,
            'employer_sector' => $employer_sector,
            'records' =>  $row
        ];
        return $this->respond($data, 200);
    }

    private function pickSignatory($employer_uid):array{
        $signatoryQRy = "SELECT s.* FROM employers_signatory s LEFT JOIN employers e ON e.id =s.employer_id WHERE e.uid ='$employer_uid' ORDER BY s.id ASC LIMIT 1";
        log_message('error', "pickSignatory---=>" . $signatoryQRy);
        $query = $this->db->query($signatoryQRy);
        $row   = $query->getResult('array');
        return $row[0];
    }

    /*
     * We dont want two employer checks to be at status 1
     */
    private function moveChecksToZero($application_uid): int {
        $sqlZeroSql = "UPDATE employer_checks SET status = 0 WHERE status = 1 AND  application_uid='$application_uid'";
        $query = $this->db->query($sqlZeroSql);
        return 0;
    }
    public function verifyEmployer()
    {
        $data = $this->request->getPost();

        if ($data['application_uid'] != '') {

            $findEmp ="SELECT  c.firstname,c.lastname,a.uid AS application_uid, a.* 
                       FROM applications a 
                       LEFT JOIN customers c ON c.uid =a.customer_uid  
                       WHERE a.status =2 AND a.uid = '".trim($data['application_uid'])."'";
         //   log_message('error', "findEmp---=>" . $findEmp);

            $query = $this->db->query($findEmp);
            $row   = $query->getResult('array');
            $employer_uid =  $row[0]['employer_uid'];
            $application_uid = $row[0]['application_uid'];

            $sigNatory = $this->pickSignatory($employer_uid);

            $to_number = $sigNatory["phone"]; // "2347032847884"; // "16784574345"; //

            if ($row[0]['uid']!='' && $application_uid !='' ){
                $this->moveChecksToZero($application_uid); // all previous login is to employer verification is invalid invalid

                log_message('error', "Call API---=>");
                $api_data = $row[0];
                $api_data["signatory_password"] = $this->randomPassword(); // "1000011";
                $api_data["signatory_email"]    =  $sigNatory['email']; //"ameye+signatory@chiefsoft.com";
                $api_data["signatory_name"]     =  $sigNatory['name']; //"Signatory Name";
                $api_data["signatory_uid"]      =  $sigNatory['uid']; //"Signatory Name";
                $api_data["processing_bank_name"]     =  "Processing Bank";
                $api_data["processing_bank_email"]     =  "processingbank@email.com";

                $udata = [
                    'employer_uid' => $employer_uid,
                    'password' => md5($api_data["signatory_password"]),
                    'username' => $api_data["signatory_email"],
                    'signatory_uid'=> $api_data["signatory_uid"],
                    'application_uid'=>$data['application_uid']
                ];
                $addedData =  $this->insert_db('employer_checks',$udata);

                $sms_message = "Your OTP = 1234";
                $this->sendSMS($to_number, $sms_message);

                $checkData = $this->APIcall("POST", "http://10.10.10.48:6332/api/verify/employer", json_encode($api_data));
            }else{
                log_message('error', "Not found  API---=>");
            }



            //$addedData =[];

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

            $response = [
                'message' => 'Verification text sent to employer',
                'call_return' => '100',
                'verification_id' => $addedData["uid"],
                'verify_data' => $checkData["res"]["data"]
            ];
//    'status' => $checkData["res"]["status"],
            return $this->respond($response, 200);
        } else {
            $response = [
                'message' => 'Failure',
                'call_return' => '100',
                'token' => ''
            ];
            return $this->fail($response, 409);
        }


        //return json_encode( $response );

    }
}