<?php

defined( 'ABSPATH' ) || exit;

use HelpGent\App\DTO\UserDTO;
use HelpGent\App\Models\HelpGentUser;

function helpgent_get_valid_user() {
    global $helpgent_valid_user;

    if ( $helpgent_valid_user ) {
        return $helpgent_valid_user;
    }

    $user = wp_get_current_user();

    if ( 0 !== $user->ID ) {
        $helpgent_valid_user = HelpGentUser::query()->where( 'registered_id', $user->ID )->first();

        if ( $helpgent_valid_user ) {
            $helpgent_valid_user->is_administrator = apply_filters( 'helpgent_is_user_administrator', in_array( 'administrator', $user->roles ) || user_can( $user, 'manage_options' ), $user );
            $helpgent_valid_user->is_agent         = apply_filters( 'helpgent_is_user_agent', in_array( 'helpgent_agent', $user->roles ) );
        }
    } elseif ( ! empty( $_COOKIE['helpgent_user_token'] ) ) {
        $token               = sanitize_text_field( wp_unslash( $_COOKIE['helpgent_user_token'] ) );
        $helpgent_valid_user = HelpGentUser::query()->where( 'token', $token )->where( 'token_expires_at', '>', gmdate( helpgent_date_time_format(), time() ) )->first();
       
        if ( $helpgent_valid_user ) {
            $helpgent_valid_user->is_administrator = false;
            $helpgent_valid_user->is_agent         = false;
        }
    }

    return $helpgent_valid_user;
}

/**
 * Get current user data.
 *
 * @return UserDTO|null
 */
function helpgent_get_current_user() {
    global $helpgent_user;

    if ( ! is_null( $helpgent_user ) ) {
        return apply_filters( 'helpgent_user', $helpgent_user );
    }
    
    $user = helpgent_get_valid_user();

    if ( ! $user ) {
        return null;
    }

    $dto = ( new UserDTO() )->set_id( $user->id )
        ->set_user_type( $user->user_type )
        ->set_registered_id( $user->registered_id )
        ->set_name( $user->name )
        ->set_email( $user->email )
        ->set_number( $user->number )
        ->set_company( $user->company )
        ->set_acceptance( $user->acceptance )
        ->set_token( $user->token )
        ->set_token_expires_at( $user->token_expires_at ? helpgent_now()->create_from_format( helpgent_date_time_format(), $user->token_expires_at ) : null )
        ->set_about( $user->about )
        ->set_timezone( $user->timezone )
        ->set_created_at( $user->created_at )
        ->set_administrator( $user->is_administrator )
        ->set_agent( $user->is_agent )
        ->set_avatar_id( $user->avatar_id );

    $helpgent_user = $dto;

    return $helpgent_user;
}

function helpgent_get_user_avatar_url( $user, string $fallback_url = '' ): string {
    $avatar_id = 0;
    $email     = '';

    if ( $user instanceof UserDTO ) {
        $avatar_id = $user->is_initialized( 'avatar_id' )
            ? absint( $user->get_avatar_id() )
            : 0;
        $email     = $user->is_initialized( 'email' )
            ? (string) $user->get_email()
            : '';
    } elseif ( is_object( $user ) ) {
        $avatar_id = absint( $user->avatar_id ?? 0 );
        $email     = (string) ( $user->email ?? '' );
    } elseif ( is_string( $user ) ) {
        $email = $user;
    }

    if ( ! empty( $avatar_id ) ) {
        $avatar_url = wp_get_attachment_url( $avatar_id );

        if ( $avatar_url ) {
            return esc_url_raw( $avatar_url );
        }
    }

    if ( ! empty( $email ) ) {
        return esc_url_raw( get_avatar_url( $email ) );
    }

    return esc_url_raw( $fallback_url );
}

function helpgent_user_login( string $token ): bool {
    wp_logout();

    $user = HelpGentUser::query()->where( 'token', $token )->where( 'token_expires_at', '>', gmdate( helpgent_date_time_format(), time() ) )->first();

    if ( ! $user ) {
        return false;
    }

    /**
     * Remove login attempt data
     * 
     * Conditionally starting and closing session to avoid conflict with third-party plugins.
     */
    $session_id       = session_id();
    $helpgent_session = false;

    if ( ! $session_id ) {
        @session_start();
        $helpgent_session = true;
    }

    unset( $_SESSION['helpgent_user_login_attempt'] );

    if ( $helpgent_session ) {
        session_write_close();
    }

    setcookie( "helpgent_user_login_attempt", "", time() - 100, '/' );
    $current_user_ip = helpgent_get_user_ip_address();
    helpgent_option()->update( "login_{$current_user_ip}", "" );

    /**
     * Login guest using cookie
     */
    return setcookie( "helpgent_user_token", $user->token, time() + MONTH_IN_SECONDS, '/' );
}

function helpgent_logout() {
    return setcookie( "helpgent_user_token", "", time() - 100, '/' );
}

function helpgent_get_user_from_cookie() {
    if ( empty( $_COOKIE['helpgent_user_token'] ) ) {
        return null;
    }

    $token = sanitize_text_field( wp_unslash( $_COOKIE['helpgent_user_token'] ) );

    return HelpGentUser::query()->where( 'token', $token )->first();
}

/**
 * @return bool|WP_Error
 */
function helpgent_user_middleware_handler() {
    $user = helpgent_get_current_user();

    if ( is_null( $user ) ) {
        return false;
    }

    if ( $user->get_token_expires_at() < gmdate( helpgent_date_time_format(), time() ) ) {
        return new WP_Error( 410, esc_html__( 'The user token has expired', 'helpgent' ) );
    }

    return true;
}
