<?php

namespace Phox\core\admin;

use Phox\core\License_Activation;
use WP_Session_Tokens;
use WP_User;

class Temporary_Login
{
    CONST TEMP_META_KEY = '_wdes_temporary_login_key';
    CONST TEMP_META_LOGIN = 'first_name';
    CONST TEMP_META_SECRET = '_wdes_temporary_login_secret';
    CONST TEMP_META_EXPIRE_DATE = '_wdes_temporary_login_expire_date';

    private $user;

    private string $key = '';

    private string $secret = '';

    private array $meta;
    private License_Activation $activation;

    public function get_meta(): array
    {
        return $this->meta;
    }

    public function set_user(): void
    {
        $this->user = $this->get_users();
    }

    public function __construct()
    {
        $this->meta = [
            'key' => '',
            'secret' => '',
        ];

        $this->set_user();

    }

    public function create_temporary_login_session():void
    {

        if( ! empty ( $this->user ) ){

            $user_id = $this->user[0]->ID;

        }else{

            $user_id = $this->generate_user();

        }

        $this->meta = $this->get_login_temp_cookies($user_id);

        if( empty($this->meta['key']) && empty($this->meta['secret']) || $this->is_user_expired($user_id) ) {

            $expiration = $this->get_expiration();

            $token = $this->create_token(
                user_id: $user_id,
                expiration: $expiration
            );

            $cookie = wp_generate_auth_cookie( $user_id, $expiration, 'logged_in', $token );
            $this->create_user_meta(
                key: LOGGED_IN_COOKIE,
                secret: $cookie,
                exp_date: $expiration,
                user_id: $user_id
            );

            $this->meta = [
                'key' => LOGGED_IN_COOKIE,
                'secret' => $cookie,
            ];

            $this->key = LOGGED_IN_COOKIE;
            $this->secret = $cookie;

        }

        $this->key = $this->meta['key'];
        $this->secret = $this->meta['secret'];


    }

    private function get_login_temp_cookies (int $user_id) {

        return [
            'key' => get_user_meta(
                user_id: $user_id,
                key: self::TEMP_META_KEY,
                single: true,
            ),
            'secret' => get_user_meta(
                user_id: $user_id,
                key: self::TEMP_META_SECRET,
                single: true,
            )
        ];
    }

    private function get_meta_expiration (int $user_id) {

        return get_user_meta(
            user_id: $user_id,
            key: self::TEMP_META_EXPIRE_DATE,
            single: true
        );

    }

    private function is_user_expired (int $user_id): bool
    {
        $expiration = $this->get_meta_expiration($user_id);

        if( empty($expiration) ) {
            return true;
        }

        return current_time('timestamp') > $expiration;
    }

    private function create_user_meta(string $key, string $secret, int $exp_date, int $user_id):void
    {
        $user_metas = [
            self::TEMP_META_KEY => $key,
            self::TEMP_META_SECRET => $secret,
            self::TEMP_META_EXPIRE_DATE => $exp_date,
        ];

        foreach ($user_metas as $key => $value) {
            update_user_meta($user_id, $key, $value);
        }

    }

    public function remove_user_meta()
    {
        $user_metas = [
            self::TEMP_META_KEY,
            self::TEMP_META_SECRET ,
            self::TEMP_META_EXPIRE_DATE
        ];

        foreach ($user_metas as  $meta_key) {
            delete_user_meta($this->user->ID, $meta_key);
        }
    }

    private function create_token(int $user_id, int $expiration): string
    {
        $session_tokens = \WP_Session_Tokens::get_instance($user_id);

        return $session_tokens->create($expiration);

    }

    private function get_expiration()
    {
        return time() + (MINUTE_IN_SECONDS * 60);
    }

    private function generate_user()
    {
        $username = 'temp-login-' . wp_generate_password( 15, false );
        $password = wp_generate_password( 64, true, true );

        $user_id = wp_insert_user( [
            'user_login' => $username,
            'user_pass' => $password,
            'role' => 'administrator',
            'first_name' => 'wdes-temp-login',
        ] );

        return $user_id;
    }

    private function get_users() : array {
        return get_users( [
            'meta_key' =>  self::TEMP_META_LOGIN,
            'meta_value' => 'wdes-temp-login',
        ] );
    }

    public function create_wp_rest_nonce():string
    {
        global $current_user;

        if(empty($this->key) && empty($this->secret)) return '';

        $user_id = $current_user->ID;

        if( ! $this->get_user_id()) {
            $this->set_user();
        }

        $current_user = get_user_by( 'id', $this->get_user_id() );

        $global_cookies = $_COOKIE;

        $_COOKIE = [];
        $_COOKIE[$this->key] = $this->secret;

        $nonce = wp_create_nonce( 'wp_rest' );

        $_COOKIE = $global_cookies;

        $current_user = get_user_by( 'id', $user_id );

        return $nonce;
    }

    public function remove_all_temporary_users()
    {
        $temporary_users = $this->get_users();

        if ( empty( $temporary_users ) ) {
            return;
        }

        if ( ! function_exists( 'wp_delete_user' ) ) {
            require_once ABSPATH . 'wp-admin/includes/user.php';
        }

        foreach ( $temporary_users as $user ) {
            wp_delete_user( $user->ID );
        }
    }

    public function get_user_id()
    {
        return isset($this->user[0]) ? $this->user[0]->ID : 0;

    }

}