<?php
/**
 * @package Divine_Agreement_System
 * @author Aditya Singh
 */


if (!defined('ABSPATH')) {
    exit;
}

class Divine_Token {
    
    
    public static function divine_generate_token($agreement_id) {
        $token = wp_generate_password(32, false, false);
        $token = sanitize_text_field($token);
        
        
        update_post_meta($agreement_id, '_divine_token', $token);
        update_post_meta($agreement_id, '_divine_token_created', current_time('mysql'));
        
        
        set_transient('divine_token_' . $token, $agreement_id, 30 * DAY_IN_SECONDS);
        
        return $token;
    }
    
    
    public static function divine_validate_token($token) {
        if (empty($token)) {
            return false;
        }
        
        $token = sanitize_text_field($token);
        
       
        $agreement_id = get_transient('divine_token_' . $token);
        
        if (!$agreement_id) {
            
            $args = array(
                'post_type' => 'divine_agreement',
                'posts_per_page' => 1,
                'post_status' => 'publish',
                // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key -- Fallback token lookup only runs when the transient cache misses.
                'meta_key' => '_divine_token',
                // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_value -- Fallback token lookup only runs when the transient cache misses.
                'meta_value' => $token,
                'meta_compare' => '=',
                'fields' => 'ids'
            );
            
            $agreements = get_posts($args);
            $agreement_id = !empty($agreements) ? $agreements[0] : false;
        }
        
        if (!$agreement_id) {
            return false;
        }
        
        
        $status = get_post_meta($agreement_id, '_divine_status', true);
        if ($status === 'signed') {
            return false; 
        }
        
        
        $agreement = get_post($agreement_id);
        if (!$agreement || $agreement->post_status !== 'publish') {
            return false;
        }
        
        return $agreement_id;
    }
    
    
    public static function divine_get_signing_url($token) {
        return add_query_arg('token', $token, home_url('/divine-sign/'));
    }
    
    
    public static function divine_invalidate_token($token) {
        delete_transient('divine_token_' . $token);
    }
    
    
    public static function divine_get_agreement_from_token($token) {
        return self::divine_validate_token($token);
    }
}
