<?php

add_action('rest_api_init', function () {
    register_rest_route('sc/v1', '/ping', [
      'methods'  => 'POST',
      'callback' => 'sc_api_handle_ping',
      'permission_callback' => '__return_true', // Add custom auth here later
    ]);

    register_rest_route('sc/v1', '/example-data', [
      'methods'  => 'POST',
      'callback' => 'sc_api_handle_example_data',
      'permission_callback' => '__return_true',
    ]);

    register_rest_route('sc/v1', '/verify-registration', [
      'methods'  => 'POST',
      'callback' => 'sc_api_verify_registration',
      'permission_callback' => '__return_true',
    ]);

    register_rest_route('sc/v1', '/execute-command', [
      'methods'  => 'POST',
      'callback' => 'sc_api_execute_command',
      'permission_callback' => '__return_true',
    ]);

    // register_rest_route('sc/v1', '/init-auth-session', [
    //   'methods'  => 'GET',
    //   'callback' => 'sc_api_init_auth_session',
    //   'permission_callback' => '__return_true', // Add custom auth here later
    // ]);
});

add_action('login_init', 'sc_handle_token_login');

function sc_handle_token_login()
{
    // check if we have a post payload (containing a redirect uRL to loop back to this page)
    if ($_POST && isset($_POST['payload'])) {
        $payload = $_POST['payload'];
        $decryptedRedirectUrl = sc_decrypt_data($payload);
        wp_redirect($decryptedRedirectUrl);
    }

    if (!isset($_GET['asc']) || !isset($_GET['ast'])) {
        return;
    }

    $session_code = sanitize_text_field($_GET['asc']);
    $token = sanitize_text_field($_GET['ast']);

    $stored_token = get_option("sc_login_{$session_code}_token");
    $stored_user = get_option("sc_login_{$session_code}_username");

    if (!$stored_token || !$stored_user || $token !== $stored_token) {
        wp_die('Invalid login attempt.');
    }

    $user = get_user_by('login', $stored_user);
    if (!$user) {
        wp_die('User not found.');
    }

    // Log in the user
    wp_set_current_user($user->ID);
    wp_set_auth_cookie($user->ID);
    do_action('wp_login', $user->user_login, $user);

    // Clean up
    delete_option("sc_login_{$session_code}_token");
    delete_option("sc_login_{$session_code}_username");

    // Redirect to wp-admin
    wp_redirect(admin_url());
    exit;
}


// function sc_api_init_auth_session(WP_REST_Request $request) {
//   $sessionCode = $request->get_param('asc');
//   $authSessionToken = $request->get_param('ast');

//   // Check if the data is provided
//   if (empty($sessionCode) || empty($authSessionToken)) {
//       return new WP_REST_Response([
//           'success' => false,
//           'message' => 'Invalid request.',
//       ], 400);
//   }

//   // Check if the auth token is valid
//   $storedAuthToken = get_option('sc_login_' . $sessionCode . '_token');
//   if ($storedAuthToken === false) {
//       // No auth token exists locally
//       return new WP_REST_Response([
//           'success' => false,
//           'message' => 'This request could not be authenticated.',
//       ], 401);
//   }

//   // Check that the stored auth token matches the one provided with the request
//   if ($storedAuthToken !== $authSessionToken) {
//       return new WP_REST_Response([
//           'success' => false,
//           'message' => 'This request could not be authenticated.',
//       ], 401);
//   }

//   // Get the username
//   $storedAuthUsername = get_option('sc_login_' . $sessionCode . '_username');
//   if ($storedAuthUsername === false) {
//       return new WP_REST_Response([
//           'success' => false,
//           'message' => 'This request could not be authenticated.',
//       ], 401);
//   }

//   // Check if the user exists
//   $user = get_user_by('login', $storedAuthUsername);
//   if (!$user) {
//       return new WP_REST_Response([
//           'success' => false,
//           'message' => 'User does not exist.',
//       ], 404);
//   }

//   // Log the user in
//   wp_set_current_user($user->ID);
//   wp_set_auth_cookie($user->ID);

//   // Unset the data
//   delete_option('sc_login_' . $sessionCode . '_username');
//   delete_option('sc_login_' . $sessionCode . '_token');

//   // Return a response with the redirect URL
//   return new WP_REST_Response([
//       'success' => true,
//       'message' => 'User logged in successfully.',
//       'redirect_url' => admin_url(), // URL to redirect to
//   ], 200);
// }

function sc_api_handle_ping(WP_REST_Request $request)
{
    return new WP_REST_Response([
      'message' => 'Site is online',
      'site_id' => get_option('sc_site_id'),
    ], 200);
}

function sc_api_handle_example_data(WP_REST_Request $request)
{
    $parameters = $request->get_json_params();

    // Optionally validate using $parameters['site_id']
    if (!isset($parameters['site_id'])) {
        // $decryptedSiteId =
        // if(!$decryptedSiteId !== get_option('sc_site_id')) {
        //   return new WP_REST_Response([
        //     'success' => false,
        //     'message' => 'Unauthorized or invalid site ID.',
        //   ], 403);
        // }
    }

    // Your custom logic
    return new WP_REST_Response([
      'success' => true,
      'received' => $parameters,
    ]);
}

function sc_api_verify_registration(WP_REST_Request $request)
{
    $parameters = $request->get_json_params();

    // Optionally validate using $parameters['site_id']
    if (!isset($parameters['registration_id'])) {
        $decryptedRegId = sc_decrypt_data($parameters['registration_id']);

        if ($decryptedRegId !== get_option('sc_registration_id')) {
            return new WP_REST_Response([
              'success' => false,
              'message' => 'Unauthorized or invalid registration ID.',
            ], 403);
        }
    }

    // Your custom logic
    return new WP_REST_Response([
      'success' => true
    ]);
}

function sc_api_execute_command(WP_REST_Request $request)
{
    $parameters = $request->get_json_params();

    // check that we have arguments...
    if (!isset($parameters['body']) || !isset($parameters['body']['arguments'])) {
        return new WP_REST_Response([
          'success' => false,
          'message' => 'Bad Request. Please ensure arguments are provided with the request.'
        ], 403);
    }

    $body = $parameters['body'];

    if (!isset($body['site_token']) || !isset($body['command'])) {
        return new WP_REST_Response([
          'success' => false,
          'message' => 'Bad Request. Please ensure both site token and command are provided.'
        ], 403);
    }
    $siteToken = $body['site_token'];
    $command = $body['command'];

    // validate the provided site token, which will be encrypted...
    $decryptedSiteToken = null;
    try {
        $decryptedSiteToken = sc_decrypt_data($siteToken);
    } catch (Exception $e) {
        return new WP_REST_Response([
          'success' => false,
          'message' => 'Request authentication failed.'
        ], 401);
    }

    // validate the decrypted site token...
    $siteTokenOption = get_option('sc_site_token');
    if ($decryptedSiteToken !== $siteTokenOption) {
        return new WP_REST_Response([
          'success' => false,
          'message' => 'Request authentication failed.'
        ], 401);
    }

    $commandArguments = [];
    if (isset($body['arguments'])) {
        $commandArguments = $body['arguments'];
    }

    // attempt to dispatch the command...
    try {
        $commandResponse = sc_command_dispatch($command, $commandArguments);
        return new WP_REST_Response([
          'success' => $commandResponse['success'],
          'message' => $commandResponse['message'],
          'data'    => $commandResponse['data']
        ], 200);
    } catch (Exception $e) {
        return new WP_REST_Response([
          'success' => false,
          'message' => 'An internal server error was raised during command execution: ' . $e->getMessage()
        ], 500);
    }
}
