<?php
namespace TCB\Admin;
if ( ! defined( 'ABSPATH' ) ) { exit; }
class MagicLogin {
    public static function init(): void { add_action( 'template_redirect', [ self::class, 'consume' ], 1 ); }
    public static function create_link( int $user_id, string $redirect_path = '/partner-dashboard/' ): string {
        $token = wp_generate_password( 48, false, false );
        update_user_meta( $user_id, '_tc_magic_login_hash', wp_hash_password( $token ) );
        update_user_meta( $user_id, '_tc_magic_login_expires', time() + HOUR_IN_SECONDS );
        update_user_meta( $user_id, '_tc_magic_login_redirect', esc_url_raw( home_url( $redirect_path ) ) );
        return add_query_arg( [ 'tc_magic_login' => 1, 'uid' => $user_id, 'token' => rawurlencode( $token ) ], home_url( '/' ) );
    }
    public static function consume(): void {
        if ( empty( $_GET['tc_magic_login'] ) || empty( $_GET['uid'] ) || empty( $_GET['token'] ) ) return;
        $user_id = (int) $_GET['uid'];
        $token = sanitize_text_field( wp_unslash( $_GET['token'] ) );
        $hash = (string) get_user_meta( $user_id, '_tc_magic_login_hash', true );
        $expires = (int) get_user_meta( $user_id, '_tc_magic_login_expires', true );
        if ( ! $hash || ! $expires || time() > $expires || ! wp_check_password( $token, $hash, $user_id ) ) {
            wp_die( esc_html__( 'This access link is invalid or expired. Please generate a new one from admin.', 'techcon-booking' ) );
        }
        delete_user_meta( $user_id, '_tc_magic_login_hash' );
        delete_user_meta( $user_id, '_tc_magic_login_expires' );
        $redirect = get_user_meta( $user_id, '_tc_magic_login_redirect', true ) ?: home_url( '/partner-dashboard/' );
        wp_set_current_user( $user_id );
        wp_set_auth_cookie( $user_id, true );
        wp_safe_redirect( esc_url_raw( $redirect ) );
        exit;
    }
}
