<?php

namespace Kanzu\StoreVoiceAI\ResponseHandlers;

// Prevent direct file access.
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

class Webhook_Handler
{
    public function handle_agent_creation_completed(\WP_REST_Request $request)
    {
        $agent_id  = sanitize_text_field($request['agentId']);
        $api_key  = sanitize_text_field($request['apiKey']);
        update_option( '_storevoiceai_apikey', $api_key, false );
        update_option( '_storevoiceai_agentid', $agent_id, false );

        $response_data = [
            'status'  => 'success',
            'message' => 'Agent creation completed successfully.',
        ];
    
        // Return the response with a 200 OK status
        return new \WP_REST_Response($response_data, 200);
    }

    // Permission callback to check the secret key
    public function check_secret_key_permission()
    {
        $headers    = getallheaders();
        $secret_key = isset($headers['X-Vapi-Secret']) ? $headers['X-Vapi-Secret'] : '';

        // Define your secret key
        $valid_secret_key = get_option('_storevoiceai_serversecret');  

        if (hash_equals((string) $valid_secret_key, (string) $secret_key)) {
            return true;
        }

        return new \WP_Error('forbidden', 'Invalid secret key', ['status' => 403]);
    }


}