<?php

namespace App\Controllers\Api\V1;

use Exception;
use App\Models\UsersModel;
use App\Controllers\BaseController;
use App\Models\RSAUsersModel;
use CodeIgniter\HTTP\ResponseInterface;

class AuthenticationController extends BaseController
{
    /**
     * Authenticate Existing User
     * @return Response
     */
    public function login()
    {
        $rules = [
            'email' => 'required|min_length[3]|max_length[50]|valid_email|emailExists[email]',
            'password' => 'required|min_length[3]|max_length[255]|validateUser[email, password]'
        ];

        $errors = [
            'email' => [
                'emailExists' => 'Please check the email. It does not exists in our system.',
            ],
            'password' => [
                'validateUser' => 'Invalid login credentials provided'
            ]
        ];

        $input = $this->getApiRequestInput($this->request);
        if (!$this->validateApiRequest($input, $rules, $errors)) {
            return $this
                ->getApiResponse(
                    [
                        'statusCode' => 3,
                        'message' => array_values($this->validator->getErrors()),
                    ],
                    ResponseInterface::HTTP_BAD_REQUEST
                );
        }
        return $this->getJWTForUser($input['email']);
    }


    private function getJWTForUser(string $emailAddress, int $responseCode = ResponseInterface::HTTP_OK)
    {
        try {
            $model = new UsersModel();
            $user = $model->findUserByEmailAddress($emailAddress);
            unset($user['PasswordHash']);
            unset($user['SecurityStamp']);
            return $this
                ->getApiResponse(
                    [
                        'statusCode' => 1,
                        'message' => 'User authenticated successfully',
                        'user' => $user,
                        'access_token' => getSignedJWTForUser($user['Email'], $user['Id'], $user['Role'],),
                    ]
                );
        } catch (Exception $exception) {
            return $this
                ->getApiResponse(
                    [
                        'error' => $exception->getMessage(),
                    ],
                    $responseCode
                );
        }
    }

    public function loggedInUserId()
    {
        $rsaUserModel = new RSAUsersModel();
        $user = $rsaUserModel->select('*')->where('Email', '03335102939@rsapakistan.com')->first();
        print_r($user); exit;
        // print_r($user); exit;
        // $query = $this->rsadb->table('AspNetUsers')
        //     ->select('*')
        //     ->where('Email', '03335102939@rsapakistan.com')
        //     ->get();
        // $rsaUser = $query->getRowArray();


        // $query = $this->insdb->table('AspNetUsers')
        //     ->select('*')
        //     ->where('Email', '03456211987@webdoc.com.pk')
        //     ->get();
        // $rsaUser = $query->getRowArray();

        // print_r($rsaUser);
        // exit;
        print_r(userId());
        print_r('/');
        print_r(roleName());
        print_r('/');
        print_r(userEmail());
        exit;
    }

    public function logout()
    {
        try {
            getSignedJWTForUserToLogout(userEmail());
        } catch (Exception $e) {
            return $this->getApiResponse(
                [
                    'statusCode' => 3,
                    'message' => $e->getMessage()
                ],
            );
        }
    }
}
