<?php


namespace App\Controllers;
use CodeIgniter\API\ResponseTrait;
use Firebase\JWT\JWT;

class DigiFiAuth extends BaseController
{
    use ResponseTrait;

    var $request;
    function __construct() {
        $this->request = \Config\Services::request();
    }
    public function index(): string
    {
        return '';
    }

    public function startBkoToken()
    {
        $data = $this->request->getPost();

        if ( $data['username'] == 'demo@demo.com' && $data['pass']=== 'demo1' ){

            $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" => "Backoffice VerifiedT",
                "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' => 'Login was successful',
                    'call_return' => '100',
                    'username' => $data['username'],
                    'token' => $token,
                    "id" =>  1,
                    "first_name" =>  "Biboqwe",
                    "last_name" =>  "Fotoohi",
                    "email" =>  "demo@demo.com",
                    "email_verified_at" =>  "2023-07-12T13:39:04.000000Z",
                    "created_at" =>  "2023-07-12T13:39:04.000000Z",
                    "updated_at" =>  "2024-04-01T21:01:31.000000Z",
                    "api_token" =>  $token
            ];

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