<?php
require '../../../config/db.php';

header("Access-Control-Allow-Origin: * ");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

include_once '../../../vendor/firebase/php-jwt/src/BeforeValidException.php';
include_once '../../../vendor/firebase/php-jwt/src/ExpiredException.php';
include_once '../../../vendor/firebase/php-jwt/src/SignatureInvalidException.php';
include_once '../../../vendor/firebase/php-jwt/src/JWT.php';
use \Firebase\JWT\JWT;


//Get posted data
$postData = file_get_contents("php://input");

if(isset($postData) && !empty($postData)){
    //Extract the data
    $request = json_decode($postData);
   
    //Validate data
    if(trim($request->phone)==='' || trim($request->otp)===''){
        return http_response_code(400);
    }
										
    //Sanitize
    $phone = mysqli_real_escape_string($con, trim($request->phone));
    $otp = mysqli_real_escape_string($con, trim($request->otp));

    $query = "SELECT * FROM Employees WHERE phone='{$phone}' LIMIT 1";
    if($result = mysqli_query($con,$query)){
        if(mysqli_num_rows($result)==1){
            while($row = mysqli_fetch_assoc($result)){
                $userId = $row['user_id'];
                $email = $row['email'];
                $fname = $row['fname'];
                $lname = $row['lname'];
                $phone = $row['phone'];
                $type = $row['type'];
                $status = $row['status'];
                $savedOtp = $row['otp'];
            }
            if($status == 0){
                // If active user
                if($savedOtp == $otp){
                    $query = "UPDATE Employees SET `otp` = null,`status` = '1' WHERE `user_id` = '{$userId}' LIMIT 1";
                    if($results = mysqli_query($con,$query)){
                        $n = mysqli_affected_rows($con);
                        if($n==1){
                            $secretKey = "sA6HTfF3DVheBwpaXAgC2gDqDteYusWRn73t9AdbggtE9RAXzWhAnr8TPaSQp3CC";
                            $issuer_claim = "ayush"; // this can be the servername
                            $audience_claim = "THE_AUDIENCE";
                            $issuedat_claim = time(); // issued at
                            $notbefore_claim = $issuedat_claim + 10; //not before in seconds
                            $expire_claim = $issuedat_claim + (3600); // expire time in seconds
                            $accessToken = array(
                                "iss" => $issuer_claim,
                                "aud" => $audience_claim,
                                "iat" => $issuedat_claim,
                                "nbf" => $notbefore_claim,
                                "exp" => $expire_claim,
                                "data" => array(
                                    "userId" => $userId,
                                    "fname" => $fname,
                                    "lname" => $lname,
                                    "email" => $email,
                                    "phone" => $phone,
                                    "type" => $type,
                                    "status" => $status,
                            ));
                            $refreshToken = array(
                                "iss" => $issuer_claim,
                                "aud" => $audience_claim,
                                "iat" => $issuedat_claim,
                                "nbf" => $notbefore_claim,
                                "exp" => $expire_claim+(3600),
                                "data" => array(
                                    "userId" => $userId,
                                    "fname" => $fname,
                                    "lname" => $lname,
                                    "email" => $email,
                                    "phone" => $phone,
                            ));
                            $accessJwt = JWT::encode($accessToken, $secretKey);
                            $refreshJwt = JWT::encode($refreshToken, $secretKey);
                            echo json_encode(
                                array(
                                    "status" => 1,
                                    "message" => "Account activated.",
                                    "accessToken" => $accessJwt,
                                    "refreshToken" => $refreshJwt,
                                    "expireAt" => $expire_claim
                                ));                            
                        }else{
                            $responseArray = [
                                'status'=> 0,
                                'message'=> 'OTP Validated but account activation failed.'
                            ];
                            echo json_encode($responseArray);
                        }
                    }else{
                        $responseArray = [
                            'status'=> -100,
                            'message'=> 'Query execution problem.'
                        ];
                        echo json_encode($responseArray);
                    }
                }else{
                    $responseArray = [
                        'status'=> -1,
                        'message'=> 'OTP is incorrect'
                    ];
                    echo json_encode($responseArray);
                }
            }else{
                // If banned user
                $response = [
                    'status' => -1,
                    'message' => 'User is banned!'  
                ];
            }
        }else{
            echo json_encode(
                array(
                    "status" => 0,
                    "message" => "Username or password incorrect.", 
                )); 
        }
    }
}


?>