<?php

namespace HelpGent\App\Repositories;

defined( 'ABSPATH' ) || exit;

use Exception;

class SiteVerificationRepository extends SettingsRepository {
    public function get_token(): string {
        $time  = time();
        $token = wp_generate_password( 32, false );
            
        $this->update_setting( 'site_verification_token', "{$time}:{$token}" );
        
        return $token;
    }
    
    /**
     * @throws Exception
     * @return bool
     */
    public function verify_token( string $token ): bool {
        $site_token_data = $this->get_by_key( 'site_verification_token' );

        if ( empty( $site_token_data ) ) {
            throw new Exception( 'Token not found.', 404 );
        }

        $site_token_data = explode( ':', $site_token_data );

        if ( count( $site_token_data ) !== 2 ) {
            throw new Exception( 'Token not found.', 404 );
        }

        $lock_time  = $site_token_data[0];
        $site_token = $site_token_data[1];

        $time_window = apply_filters( 'helpgent_site_token_window', 86400 ); // 24 hours

        if ( $lock_time < time() - $time_window ) {
            throw new Exception( 'The token is expired.', 403 );
        }

        if ( $site_token !== $token ) {
            throw new Exception( 'Token does not match.', 403 );
        }

        $this->update_setting( 'site_verification_token', null );
        
        return true;
    }
}
