<?php

/**
 * Command to create an authentication session with a one-time access code.
 */
class SC_Command_Users_CreateSession extends SC_Command_Base
{
    /**
     * Execute the command to create an authentication session.
     *
     * @return array An associative array with the result of the command execution.
     */
    public function execute()
    {
        // Get the username from the arguments
        $username = $this->args['username'];

        // Validate username
        if (empty($username)) {
            return [
              'success' => false,
              'message' => 'Username is required.',
            ];
        }

        // Check if the user exists
        if (!username_exists($username)) {
            return [
              'success' => false,
              'message' => 'User does not exist.',
            ];
        }

        // Generate a 25-character one-time access code
        $access_code = $this->generate_access_code(25);
        $sessionCode = $this->generate_pending_session_code();

        // Store the access code in the options table
        update_option('sc_login_' . $sessionCode . '_token', $access_code);
        update_option('sc_login_' . $sessionCode . '_username', $username);

        return [
          'success' => true,
          'message' => 'Access code generated successfully.',
          'data'    => [
            'username'     => $username,
            'access_code'  => $access_code,
            'session_code' => $sessionCode
          ],
        ];
    }

    /**
     * Generate a one-time use access code.
     *
     * @param int $length The length of the access code.
     * @return string The generated access code.
     */
    private function generate_access_code($length): string
    {
        $characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $characters_length = strlen($characters);
        $access_code = '';

        for ($i = 0; $i < $length; $i++) {
            $index = random_int(0, $characters_length - 1);
            $access_code .= $characters[$index];
        }

        return $access_code;
    }

    private function generate_pending_session_code($length = 4): string
    {
        $characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $characters_length = strlen($characters);
        $access_code = '';

        for ($i = 0; $i < $length; $i++) {
            $index = random_int(0, $characters_length - 1);
            $access_code .= $characters[$index];
        }

        return $access_code;
    }
}
