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


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

class Divine_Security {

    private static function divine_get_filesystem() {
        require_once ABSPATH . 'wp-admin/includes/file.php';
        WP_Filesystem();

        global $wp_filesystem;

        return $wp_filesystem;
    }
    
    
    public static function init() {
        add_action('wp_ajax_divine_submit_signature', array(__CLASS__, 'divine_handle_signature_submission'));
        add_action('wp_ajax_nopriv_divine_submit_signature', array(__CLASS__, 'divine_handle_signature_submission'));
    }
    
    
    public static function divine_handle_signature_submission() {
        $nonce = isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : '';

        if (!$nonce || !wp_verify_nonce($nonce, 'divine_agreement_nonce')) {
            wp_send_json_error(array('message' => __('Security check failed.', 'divine-agreement-system')));
        }
        
        
        $token = isset($_POST['token']) ? sanitize_text_field(wp_unslash($_POST['token'])) : '';
        $agreement_id = Divine_Token::divine_validate_token($token);
        
        if (!$agreement_id) {
            wp_send_json_error(array('message' => __('Invalid or expired token.', 'divine-agreement-system')));
        }
        
        
        $status = get_post_meta($agreement_id, '_divine_status', true);
        if ($status === 'signed') {
            wp_send_json_error(array('message' => __('This agreement has already been signed.', 'divine-agreement-system')));
        }
        
       
        $required_fields = array('name', 'email', 'address', 'signature', 'acceptance');
        foreach ($required_fields as $field) {
            $field_value = '';

            if (isset($_POST[$field])) {
                $field_value = wp_unslash($_POST[$field]); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Sanitized after validation below.
            }

            if ('' === $field_value) {
                /* translators: %s: Required field name. */
                wp_send_json_error(array('message' => sprintf(__('Field "%1$s" is required.', 'divine-agreement-system'), $field)));
            }
        }
        
        
        $name = isset($_POST['name'])
            ? sanitize_text_field(wp_unslash($_POST['name']))
            : '';
        $email = isset($_POST['email'])
            ? sanitize_email(wp_unslash($_POST['email']))
            : '';
        $address = isset($_POST['address'])
            ? sanitize_text_field(wp_unslash($_POST['address']))
            : '';
        $signature_data = isset($_POST['signature'])
            ? sanitize_text_field(wp_unslash($_POST['signature']))
            : '';
        $acceptance = isset($_POST['acceptance'])
            ? sanitize_text_field(wp_unslash($_POST['acceptance']))
            : '';
        
        
        if (!is_email($email)) {
            wp_send_json_error(array('message' => __('Invalid email address.', 'divine-agreement-system')));
        }
        
        
        if ($acceptance !== 'yes') {
            wp_send_json_error(array('message' => __('You must accept the agreement terms.', 'divine-agreement-system')));
        }
        
        
        if (strpos($signature_data, 'data:image/png;base64,') !== 0) {
            wp_send_json_error(array('message' => __('Invalid signature format.', 'divine-agreement-system')));
        }
        
        
        $ip_address = self::divine_get_client_ip();
        
        
        $signature_path = self::divine_save_signature_image($agreement_id, $signature_data);
        
        if (!$signature_path) {
            wp_send_json_error(array('message' => __('Failed to save signature.', 'divine-agreement-system')));
        }
        
        
        $signed_date = current_time('mysql');
        update_post_meta($agreement_id, '_divine_status', 'signed');
        update_post_meta($agreement_id, '_divine_signed_name', $name);
        update_post_meta($agreement_id, '_divine_signed_email', $email);
        update_post_meta($agreement_id, '_divine_signed_address', $address);
        update_post_meta($agreement_id, '_divine_signed_date', $signed_date);
        update_post_meta($agreement_id, '_divine_signed_ip', $ip_address);
        update_post_meta($agreement_id, '_divine_signature_image', $signature_path);
        
        
        Divine_Token::divine_invalidate_token($token);
        
        
        $pdf_path = Divine_PDF_Generator::divine_generate_pdf($agreement_id);
        
        if ($pdf_path) {
            update_post_meta($agreement_id, '_divine_pdf_path', $pdf_path);
        }
        
        
        Divine_Email::divine_send_signed_notification($agreement_id);
        
        wp_send_json_success(array(
            'message' => __('Agreement signed successfully!', 'divine-agreement-system'),
            'pdf_generated' => (bool) $pdf_path
        ));
    }
    
    
    private static function divine_save_signature_image($agreement_id, $signature_data) {
        
        $signature_data = str_replace('data:image/png;base64,', '', $signature_data);
        $signature_data = str_replace(' ', '+', $signature_data);
        $decoded_data = base64_decode($signature_data, true);
        
        if (!$decoded_data) {
            return false;
        }
        
        
        $upload_dir = DIVINE_AGREEMENT_UPLOAD_DIR;
        if (!file_exists($upload_dir)) {
            wp_mkdir_p($upload_dir);
        }
        
        
        $filename = 'signature-' . $agreement_id . '-' . time() . '.png';
        $filepath = $upload_dir . $filename;
        
        
        $wp_filesystem = self::divine_get_filesystem();
        $saved = false;

        if ($wp_filesystem) {
            $saved = $wp_filesystem->put_contents($filepath, $decoded_data, FS_CHMOD_FILE);
        }
        
        return $saved ? $filepath : false;
    }
    
    
    public static function divine_get_client_ip() {
        $ip = '';
        
        if (isset($_SERVER['HTTP_CLIENT_IP']) && !empty($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = sanitize_text_field(wp_unslash($_SERVER['HTTP_CLIENT_IP']));
        } elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && !empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $forwarded_for = sanitize_text_field(wp_unslash($_SERVER['HTTP_X_FORWARDED_FOR']));
            $forwarded_ips = array_map('trim', explode(',', $forwarded_for));
            $ip = isset($forwarded_ips[0]) ? $forwarded_ips[0] : '';
        } elseif (isset($_SERVER['REMOTE_ADDR']) && !empty($_SERVER['REMOTE_ADDR'])) {
            $ip = sanitize_text_field(wp_unslash($_SERVER['REMOTE_ADDR']));
        }
        
        return sanitize_text_field($ip);
    }
    
    
    public static function divine_sanitize_filename($filename) {
        return sanitize_file_name($filename);
    }
}


Divine_Security::init();
