<?php

namespace App\Http\Controllers;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Firebase\JWT\ExpiredException;
use Illuminate\Http\Request;

class XMPPController extends Controller
{
    public function registerToXMPP($phone, $password)
    {
        $token  = $this->generate_jwt();
        $url    = env('XMPP_URL', 'http://xmpp.icoredeals.com:8080') . "/register";
        $data   = [
            'username' => $phone,
            'password' => $password,
        ];
        $headers = [
            'Authorization: Bearer ' . $token,
            'Content-Type: application/json',
        ];
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        // receive server response ...
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $server_output = curl_exec($ch);
        //dd($server_output, $token);
        curl_close($ch);

        $response = json_decode($server_output, true);

        if ($response == null) {
            return json_encode([
                'status' => "error",
                'message' => 'Server Error',
            ]);
        }

        // dd($response);
        if ($response['status'] == "success") {
            return 1;
        } else {
            return $response;
        }
    }

    // function generate jwt token
    function generate_jwt()
    {
        //  $jwtSecret  = env('JWT_SECRET');
        $jwtKey     = env('JWT_SECRET');
        $jwtAlgo    = env('JWT_ALGO', 'HS256');

        // $key = new Key($jwtKey, $jwtAlgo);

        $payload = [
            'iss' => 'http://example.org',
            'aud' => 'http://example.com',
            'iat' => time() - 1000,
            'nbf' => time() - 1000,
            'exp' => time() + 2500,
            'data' => [
                'id' => 1,
                'name' => 'John Doe',
            ]
        ];
        return JWT::encode($payload, $jwtKey, $jwtAlgo);
    }
}
