<?php

class agile_tix_Rest_Route
{

    static function refresh_ATS_data(WP_REST_Request $request)
    {
        nocache_headers();//ngix helper PLEASE stop chaching these
        try {
            //agile_tix::agile_tix_log_event("rest route data refresh run");
            //rest_ensure_response(agile_tix_data_fetcher::fetch_agile_data());
            agile_tix_data_fetcher::fetch_agile_data();
            //agile_tix::agile_tix_log_event("rest route post update run");
            agile_tix_post_creator::ats_universal_refresh_showsList(false);
            $response = new WP_REST_Response(['message' => 'Data refreshed successfully']);
            $response->set_headers([//none of these SHOULD be needed, but
                'Cache-Control' => 'no-store, no-cache, must-revalidate, max-age=0',
                'Pragma' => 'no-cache',
                'Expires' => 'Wed, 11 Jan 1984 05:00:00 GMT'
            ]);
            return $response;
        } catch (Exception $e) {
            agile_tix::agile_tix_log_event("Error in refresh_ATS_data: " . $e->getMessage());
            return new WP_Error(
                'ats_data_refresh_error',
                $e->getMessage(),
                ['status' => $e->getCode() ?: 500]
            );
        }
    }

    function prefix_register_routes()
    {
        register_rest_route('agile_tix/v1', '/refresh_data', array(
            'methods' => WP_REST_Server::READABLE,
            'callback' => 'agile_tix_Rest_Route::refresh_ATS_data',
            //'args' => array('sanitize_callback' => 'agile_tix_Rest_Route::agile_arg_sanitize_callback')
            'permission_callback' => 'agile_tix_Rest_Route::agile_rest_endpoint_parm_CB'
        ));
    }

    static function agile_rest_endpoint_parm_CB(WP_REST_Request $request)
    {
        try {
            $provided_signature = $request->get_header('ats-Signature');
            //agile_tix::agile_tix_log_event("agile_rest_endpoint_parm_CB provided- $provided_signature");
            // Retrieve the stored secret from WordPress options

            //agile_tix::agile_tix_log_event("agile_rest_endpoint_parm_CB expected- $expected_signature");
            if (!$provided_signature || !agile_tix_Rest_Route::agile_validate_signature($provided_signature)) {
                agile_tix::agile_tix_log_event("rest route permission denied - Invalid App-Secret");

                return new WP_Error('rest_forbidden', esc_html__('ERROR: Unauthorized request.', 'agile-ticketing'), array('status' => 403));
            }
            //agile_tix::agile_tix_log_event("rest route permission granted");
            return true; // Authentication passed
        } catch (Exception $ex) {
            agile_tix::agile_tix_log_event("rest route ERROR: " . $ex->getMessage());
            return new WP_Error('rest_forbidden', __('ERROR: Authentication failed.', 'agile-ticketing'), ['status' => 403]);
        }
    }



    /*
    function agile_prevalidate_ping_signature($response, $server) {
        // It should always be a GET
        if ($server->get_method() === 'GET') {
            // Extract the signature from the request header or query params
            $signature = isset($_SERVER['HTTP_ATS_SIGNATURE']) ? $_SERVER['HTTP_ATS_SIGNATURE'] : '';
            if (!$signature || $signature == ''){
                $valid_signature = agile_tix_Rest_Route::agile_validate_signature($signature);

                if (!$valid_signature) {
                    agile_tix::agile_tix_log_event("agile_prevalidate_ping_signature failed invalid Signature");
                    return new WP_Error('unauthorized', 'Invalid signature', array('status' => 403));
                } else {
                    agile_tix::agile_tix_log_event("agile_prevalidate_ping_signature worked");

                }
            }
        }
        return $response;
    }
    */

    static function agile_validate_signature($signature)
    {
        $stored_secret = get_option('agile_field_password');
        $expected_signature = hash_hmac('sha256', (get_site_url() . "/wp-json/agile_tix/v1/refresh_data"), $stored_secret);
        return hash_equals($signature, $expected_signature);
    }

    //may not work if a staging site is informally or incorrectly set up, works for dream host staging site creation
    static function agile_is_staging_site()
    {
        $eviroType = wp_get_environment_type() ?? '';
        return ($eviroType === 'staging');
    }


    /*
    function agile_whitelist_api_by_header($result) {
        agile_tix::agile_tix_log_event("agile_whitelist_api_by_header invoked");
        $provided_signature = isset($_SERVER['HTTP_ATS_SIGNATURE']) ? $_SERVER['HTTP_ATS_SIGNATURE'] : '';
        if (!empty($provided_signature)){
            $stored_secret = get_option('agile_field_password');
            $expected_signature = hash_hmac('sha256', (get_site_url() . "/wp-json/agile_tix/v1/refresh_data"), $stored_secret);


            if ($provided_signature === $expected_signature) {
                agile_tix::agile_tix_log_event("agile_whitelist_api_by_header validated sig");
                return true;
            }
        }
        // Otherwise, continue with the default authentication check
        agile_tix::agile_tix_log_event("agile_whitelist_api_by_header validation failed");
        return $result;
    }
    */
    //disallow our endpoint from robots.txt as a minor extra layer of concealment
    function agile_modify_robots($output)
    {
        $output .= "Disallow: /wp-json/agile_tix/\n";
        return $output;
    }

    static function agile_call_wordpress_webhook($isActive = false)
    {

        $domain = get_option('agile_field_domain');
        $apiBase = "";
        if (isset($domain)){
            if (str_contains($domain, "QA/") ){
                //agile_tix::agile_tix_log_event("agile_call_wordpress_webhook: QA domain detected");
                $apiBase = 'https://qa.agiletix.com/API/';
            } else {
                $apiBase = get_option('agile_field_apiURL');
            }
        }

        //$domain = 'https://dev.agiletix.net/';
        //$domain = 'https://qa.agiletix.com/';
        //$APIURL = $domain . "/API/Sales.svc/JSON/WordPressWebHook";
        
        //$apiBase = 'https://dev.agiletix.net/API/';
        $APIURL = $apiBase . "Sales.svc/JSON/WordPressWebHook";
        //$APIURL = 'https://dev.agiletix.net/api/Sales.svc/JSON/WordPressWebHook';
        if ($APIURL == false) {
            agile_tix::agile_tix_log_event("ERROR: agile_call_wordpress_webhook invalid API URL");
            return;
        }

        
        $orgID = get_option('agile_field_corpOrgID');
        $uri = (get_site_url() . "/wp-json/agile_tix/v1/refresh_data");
        $applicationPassword = get_option('agile_field_password');
        $appKey = "2b33e881-9a22-4963-8373-23acc6ca9d85";//get_option('agile_field_appKey');
        //$userKey = get_option('agile_field_userKey');

        if (empty($domain)) {
            agile_tix::agile_tix_log_event("ERROR: agile_call_wordpress_webhook invalid Domain");
            return ("Error: Invalid Domain");
        }
        if (empty($orgID)) {
            agile_tix::agile_tix_log_event("ERROR: agile_call_wordpress_webhook invalid OrgID");
            return ("Error: Invalid OrgID");
        }
        if (empty($uri)) {
            agile_tix::agile_tix_log_event("ERROR: agile_call_wordpress_webhook invalid URI");
            return ("Error: Invalid URI");
        }
        if (empty($applicationPassword)) {
            agile_tix::agile_tix_log_event("ERROR: agile_call_wordpress_webhook invalid Password");
            return ("Error: Invalid Password");
        }
        if (empty($appKey)) {
            agile_tix::agile_tix_log_event("ERROR: agile_call_wordpress_webhook invalid App Key");
            return ("Error: Invalid App Key");
        }
        //if (empty($userKey)) {
        //    return ("Error: Invalid User Key");
        //}

        //agile_tix::agile_tix_log_event('agile_call_wordpress_webhook $APIURL =' . $APIURL) ;
        //agile_tix::agile_tix_log_event('agile_call_wordpress_webhook $appKey =' . $appKey);
        //agile_tix::agile_tix_log_event('agile_call_wordpress_webhook $userKey =' . $userKey);
        //agile_tix::agile_tix_log_event('agile_call_wordpress_webhook $domain =' . $domain);
        //agile_tix::agile_tix_log_event('agile_call_wordpress_webhook $orgID =' . $orgID);
        //agile_tix::agile_tix_log_event('agile_call_wordpress_webhook $uri =' . $uri);
        //agile_tix::agile_tix_log_event('agile_call_wordpress_webhook $applicationPassword =' . $applicationPassword);
        //agile_tix::agile_tix_log_event('agile_call_wordpress_webhook $isActive =' . $isActive);
        // Parameters
        $data = [
            "appKey" => $appKey,
            "domain" => $domain,
            "orgID" => $orgID,
            "URI" => $uri,
            "applicationPassword" => $applicationPassword,
            "isActivation" => $isActive,
        ];

        try {
            $response = wp_safe_remote_post($APIURL, [
                'body' => json_encode($data),
                'headers' => [
                    'Content-Type' => 'application/json',
                ],
                'timeout' => 5, //wp timeout is in seconds
                'sslverify' => true,
            ]);

            //dev ONLY
            /*
            $response = wp_remote_post($apiURL, [
                'body' => json_encode($data),
                'headers' => [
                    'Content-Type' => 'application/json',
                ],
                'timeout' => 20, //wp timeout is in seconds
                'sslverify' => false,
            ]);
            */

            if (is_wp_error($response)) {
                agile_tix::agile_tix_log_event("Error: " . $response->get_error_message());
                return "Error: " . $response->get_error_message();
            }

            $body = wp_remote_retrieve_body($response);
            $http_code = wp_remote_retrieve_response_code($response);
            if ($http_code == 200) {
                //agile_tix::agile_tix_log_event("agile_call_wordpress_webhook http_code == 200");
                update_option('agile_field_webhook_is_active', $isActive);
            } else {
                agile_tix::agile_tix_log_event("ERROR: agile_call_wordpress_webhook http_code == $http_code");
            }

            //agile_tix::agile_tix_log_event("Response Code: $http_code");
            //agile_tix::agile_tix_log_event("Response: $body");
            return "Response Code: " . $http_code . "\nResponse: " . $body;
        } catch (Exception $e) {
            agile_tix::agile_tix_log_event("Activate WordPress Exception: " . $e);
        }
    }

    static function agile_register_rest_options()
    {
        $textFieldArgs = array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default' => NULL,
        );

        $option_group = 'agile_options_credentials_settings';
        register_setting($option_group, 'agile_field_apiURL', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default' => '',
        ));

        register_setting($option_group, 'agile_field_webURL', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default' => '',
        ));
        register_setting($option_group, 'agile_field_corpOrgID', $textFieldArgs);
        register_setting($option_group, 'agile_field_epgID', $textFieldArgs);
        register_setting($option_group, 'agile_field_guid', $textFieldArgs);
        register_setting($option_group, 'agile_field_widget_target', $textFieldArgs);
        register_setting($option_group, 'agile_field_widget_mode', $textFieldArgs);
        register_setting($option_group, 'agile_field_epgTag', $textFieldArgs);
        //register_setting($option_group, 'agile_field_appKey', $textFieldArgs);
        //register_setting($option_group, 'agile_field_userKey', $textFieldArgs);
        register_setting($option_group, 'agile_field_password', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default' => NULL,
        ));
        register_setting($option_group, 'agile_field_use_coming_soon_feed', array(
            'type' => 'boolean',
            'sanitize_callback' => 'sanitize_text_field',
            'default' => false,
        ));
        register_setting($option_group, 'agile_field_coming_soon_guid', $textFieldArgs);
        register_setting($option_group, 'agile_field_coming_soon_epgID', $textFieldArgs);


        $option_group = 'agile_options_config_settings';
        register_setting($option_group, 'agile_field_comment_status', array('show_in_rest' => true, 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field', 'default' => 'closed'));
        register_setting($option_group, 'agile_field_post_status', array('autoload' => 'true', 'show_in_rest' => true, 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field', 'default' => 'publish'));
        register_setting($option_group, 'agile_field_auto_cull', array('show_in_rest' => true, 'type' => 'boolean', 'sanitize_callback' => 'sanitize_text_field', 'default' => '1'));

        register_setting($option_group, 'agile_field_widget_active', array('show_in_rest' => true, 'type' => 'boolean', 'sanitize_callback' => 'sanitize_text_field', 'default' => '0'));
        register_setting($option_group, 'agile_field_widget_target', array('show_in_rest' => true, 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field', 'default' => 'agile_frame'));
        register_setting($option_group, 'agile_field_widget_mode', array('show_in_rest' => true, 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field', 'default' => 'popup'));

        $option_group = 'agile_options_content_settings';
        register_setting($option_group, 'agile_options_content_settings');
        register_setting($option_group, 'agile_field_content_infoLink');

        $contentDefaults = array(
            ['agile_field_content_distributor', '{distributor}', 'Proudly presented by {distributor}'],
            ['agile_field_content_duration', '{duration}', '{duration} minutes'],
            ['agile_field_content_full_description', '{full description}', '{full description}'],
            ['agile_field_content_release_year', '{release year}', 'Released {release year}'],
            ['agile_field_content_rating', '{rating}', 'Rated {rating}'],
            ['agile_field_content_director', '{director}', 'Directed by {director}'],
            ['agile_field_content_cast', '{cast list}', 'Cast: {cast list}'],
            ['agile_field_content_genre', '{genre list}', 'Genre: {genre list}'],
            ['agile_field_content_renderLocation', '{location}', '{location}'],
        );

        foreach ($contentDefaults as $defaultField) {
            register_setting($option_group, $defaultField[0], array(
                'type' => 'string',
                'sanitize_callback' => function ($input) use ($defaultField) {
                    return agile_tix_Options::agile_validate_custom_fields($input, $defaultField[1], $defaultField[0]);
                },
                'default' => $defaultField[2],
            ));
        }
        

        $option_group = 'agile_options_theme_settings';
        register_setting($option_group, 'agile_field_config_integration_type');
        register_setting($option_group, 'agile_field_theme_custom_map_post_type');
        register_setting($option_group, 'agile_field_theme_custom_map_template');
        register_setting($option_group, 'agile_custom_fields');
        register_setting($option_group, 'agile_term_fields');
        register_setting($option_group, 'agile_field_theme_custom_code');

    }




    //TODO: hook into agile_field_password onchange to update this users password
    /*
    static function create_agile_API_agent_user(){

        $username = 'Agile_api_agent';

        if (!username_exists($username)) {
            $stored_secret = get_option('agile_field_password');
            $password = hash_hmac('sha256', (get_site_url() . "/wp-json/agile_tix/v1/refresh_data"), $stored_secret);
            $user_id = wp_create_user($username, $password);
            if (!is_wp_error($user_id)) {

            }
        }
    }
    */
}


