<?php

namespace App\Controllers\Api\V1;

use Exception;
use App\Controllers\BaseController;
use Willywes\AgoraSDK\RtcTokenBuilder;

class AgoraTokenController extends BaseController
{

    public function generateToken()
    {
        try {
            $rules = [
                'channel_name' => 'required',
            ];
            $errors = [
                'channel_name' => [
                    'required' => 'Channel name field is required.',
                ],
            ];
            $input = $this->getApiGetRequestInput($this->request);
            if (!$this->validateApiRequest($input, $rules, $errors)) {
                return $this
                    ->getApiResponse(
                        [
                            'statusCode' => 3,
                            'message' => array_values($this->validator->getErrors()),
                        ],
                    );
            }
            // $appId = 'c43d28b0f24d402fb9b6b3cf4dbde961';
            // $appCertificate = '834843b4408245fab6795c593f97fd22';
            $appId = 'f0924810ffd04733b7a726cb961157cd';
            $appCertificate = '2864a123be5245a1a12160a5bffc1ff2';
            $channelName = $input['channel_name'];
            $uid = 0;
            $role = RtcTokenBuilder::RoleAttendee; // or RtcTokenBuilder::RoleSubscriber

            $iat = time() - 30; // Current timestamp minus 30 seconds
            $exp = $iat + (60 * 60 * 2); // Expiry set to 2 hours
            $expirationTimeInSeconds = $exp;

            // Generate token
            $token = RtcTokenBuilder::buildTokenWithUid($appId, $appCertificate, $channelName, $uid, $role, $expirationTimeInSeconds);

            return $this
                ->getApiResponse(
                    [
                        'statusCode' => 1,
                        'message' => "Token generated successfully.",
                        'data' => ['token' => $token],
                    ]
                );
            return $this->response->setJSON(['token' => $token]);
        } catch (Exception $e) {
            return $this->getApiResponse(
                [
                    'statusCode' => 3,
                    'message' => $e->getMessage()
                ],
            );
        }

        
    }
}
