<?php
// Registers [pdf_download_form] shortcode.

defined('ABSPATH') || exit;

add_shortcode('pdf_download_form', 'spdfed_form_shortcode');
add_action('wp_enqueue_scripts', 'spdfed_enqueue_styles');

/**
 * Enqueue plugin styles
 */
function spdfed_enqueue_styles() {
    // Check if user has disabled the default styles
    if (get_option('spdfed_disable_styles')) {
        return;
    }

    wp_enqueue_style(
        'spdfed-styles',
        plugins_url('assets/css/style.css', dirname(__FILE__)),
        [],
        '1.0.0'
    );
}

/**
 * Render PDF download form
 *
 * @param array $atts Shortcode attributes
 * @return string
 */
function spdfed_form_shortcode($atts) {
    $atts = shortcode_atts([
        'id'    => 0,
        'label' => __('Download PDF', 'email-gated-downloads')
    ], $atts, 'pdf_download_form');

    $post_id = absint($atts['id']);
    $is_premium = function_exists('sped_fs') && sped_fs()->can_use_premium_code__premium_only();
    
    // Premium users with ID - use CPT system
    if ($is_premium && !empty($post_id)) {
        if (get_post_type($post_id) !== 'spdfed_secure_file') {
            return '<!-- Secure PDF Download: Invalid form ID. -->';
        }
        
        // Check if a file is actually associated with this post ID
        $file = get_post_meta($post_id, '_spdfed_storage_filename', true);
        if (empty($file)) {
            return '<!-- Secure PDF Download: No file associated with this ID. -->';
        }
        
        return spdfed_render_cpt_form($post_id, $atts['label']);
    }
    
    // Free users without ID - use settings-based single file
    if (!$is_premium && empty($post_id)) {
        $free_file = get_option('spdfed_free_storage_filename');
        if (empty($free_file)) {
            return '<!-- Secure PDF Download: No file configured. Please upload a file in the plugin settings. -->';
        }
        
        return spdfed_render_free_form($atts['label']);
    }
    
    // Invalid combinations
    if (!$is_premium && !empty($post_id)) {
        return '<!-- Secure PDF Download: Multiple downloads require premium version. -->';
    }
    
    // Premium users without ID - check for migrated/default post
    if ($is_premium && empty($post_id)) {
        $default_post_id = absint(get_option('spdfed_premium_default_post_id', 0));
        
        if (!empty($default_post_id)) {
            // Validate the default post still exists
            if (get_post_type($default_post_id) === 'spdfed_secure_file') {
                $file = get_post_meta($default_post_id, '_spdfed_storage_filename', true);
                if (!empty($file)) {
                    return spdfed_render_cpt_form($default_post_id, $atts['label']);
                } else {
                    // Post exists but no file - check if user is temporarily between file replacements
                    $file_removed_notice = get_option('spdfed_default_post_file_removed', 0);
                    if ($file_removed_notice == $default_post_id) {
                        // Show a helpful message instead of breaking completely
                        return '<!-- Secure PDF Download: Default file temporarily removed. Please upload a new file to restore functionality. -->';
                    }
                }
            }
            
            // Default post is invalid, clean it up
            delete_option('spdfed_premium_default_post_id');
        }
        
        return '<!-- Secure PDF Download: Premium users must specify an ID, e.g., [pdf_download_form id="123"]. -->';
    }
    
    return '<!-- Secure PDF Download: Invalid configuration. -->';
}

/**
 * Render form for CPT-based downloads (premium users).
 *
 * @param int    $post_id The CPT post ID.
 * @param string $label   Button label.
 * @return string
 */
function spdfed_render_cpt_form($post_id, $label) {
    $error_message   = '';
    $submitted_email = '';
    $submitted_name  = '';

    // Check for an error transient.
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    $error_key = isset($_GET['spdfed_error_key']) ? sanitize_key($_GET['spdfed_error_key']) : '';
    if ( ! empty($error_key) ) {
        $error_data = get_transient($error_key);
        if ($error_data && is_array($error_data)) {
            // Check if the error belongs to this specific form instance.
            if (isset($error_data['post_id']) && absint($error_data['post_id']) === $post_id) {
                $error_message   = isset($error_data['message']) ? sanitize_text_field($error_data['message']) : '';
                $submitted_email = isset($error_data['email']) ? sanitize_email($error_data['email']) : '';
                $submitted_name  = isset($error_data['name']) ? sanitize_text_field($error_data['name']) : '';
            }
            // Delete the transient once it's been used.
            delete_transient($error_key);
        }
    }

    // Fetch settings with override support
    $override_settings = get_post_meta($post_id, '_spdfed_override_settings', true) === '1';
    
    if ($override_settings) {
        // Use CPT-specific settings
        $gdpr_enabled = get_post_meta($post_id, '_spdfed_enable_gdpr', true);
        if ($gdpr_enabled === '') { $gdpr_enabled = '1'; } // Default to on
        
        $gdpr_message = get_post_meta($post_id, '_spdfed_gdpr_message', true);
        if (empty($gdpr_message)) {
            $gdpr_message = __('I consent to my email being stored for the purposes of this download.', 'email-gated-downloads');
        }
        
        $name_field_enabled = get_post_meta($post_id, '_spdfed_enable_name_field', true) === '1';
        $name_field_required = get_post_meta($post_id, '_spdfed_name_field_required', true) === '1';
    } else {
        // Use global settings (same as free settings)
        $gdpr_enabled = get_option('spdfed_free_enable_gdpr', 1);
        $gdpr_message = get_option('spdfed_free_gdpr_message', __('I consent to my email being stored for the purposes of this download.', 'email-gated-downloads'));
        $name_field_enabled = get_option('spdfed_free_enable_name_field', 0) == 1;
        $name_field_required = get_option('spdfed_free_name_field_required', 0) == 1;
    }


    ob_start();

    if ( ! empty( $error_message ) ) {
        echo '<div class="spdfed-error-message">' . esc_html( $error_message ) . '</div>';
    }
    ?>
    <div class="spdfed-form-wrapper">
        <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" class="spdfed-form">
            <?php if ($name_field_enabled): ?>
            <div class="spdfed-form-row">
                <input type="text"
                       name="spdfed_name"
                       <?php if ($name_field_required) echo 'required'; ?>
                       placeholder="<?php esc_attr_e('Enter your full name', 'email-gated-downloads'); ?>"
                       value="<?php echo esc_attr($submitted_name); ?>"
                       class="spdfed-input">
            </div>
            <?php endif; ?>
            <div class="spdfed-form-row">
                <input type="email" 
                       name="email" 
                       required 
                       placeholder="<?php esc_attr_e('Enter your email', 'email-gated-downloads'); ?>"
                       value="<?php echo esc_attr($submitted_email); ?>"
                       class="spdfed-input">
            </div>
            <?php if ($gdpr_enabled): ?>
                <div class="spdfed-form-row">
                    <label class="spdfed-checkbox-label">
                        <input type="checkbox" name="gdpr" value="1" required>
                        <?php echo esc_html($gdpr_message); ?>
                    </label>
                </div>
            <?php endif; ?>
            <input type="hidden" name="action" value="spdfed_download">
            <input type="hidden" name="post_id" value="<?php echo esc_attr($post_id); ?>">
            <input type="hidden" name="spdfed_redirect_url" value="<?php echo esc_url( spdfed_get_current_url() ); ?>">
            <?php wp_nonce_field('spdfed_download_nonce_' . $post_id, 'spdfed_nonce_field'); ?>
            <button type="submit" class="spdfed-button">
                <?php echo esc_html($label); ?>
            </button>
        </form>
    </div>
    <?php
    return ob_get_clean();
}

/**
 * Render form for free tier single download.
 *
 * @param string $label Button label.
 * @return string
 */
function spdfed_render_free_form($label) {
    $error_message   = '';
    $submitted_email = '';
    $submitted_name  = '';

    // Check for an error transient for free form
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    $error_key = isset($_GET['spdfed_error_key']) ? sanitize_key($_GET['spdfed_error_key']) : '';
    if ( ! empty($error_key) ) {
        $error_data = get_transient($error_key);
        if ($error_data && is_array($error_data)) {
            // Check if this is a free form error (no post_id or post_id = 0)
            if (!isset($error_data['post_id']) || absint($error_data['post_id']) === 0) {
                $error_message   = isset($error_data['message']) ? sanitize_text_field($error_data['message']) : '';
                $submitted_email = isset($error_data['email']) ? sanitize_email($error_data['email']) : '';
                $submitted_name  = isset($error_data['name']) ? sanitize_text_field($error_data['name']) : '';
            }
            // Delete the transient once it's been used.
            delete_transient($error_key);
        }
    }

    // Fetch settings from options
    $gdpr_enabled = get_option('spdfed_free_enable_gdpr', 1);
    $gdpr_message = get_option('spdfed_free_gdpr_message', __('I consent to my email being stored for the purposes of this download.', 'email-gated-downloads'));
    $name_field_enabled = get_option('spdfed_free_enable_name_field');
    $name_field_required = get_option('spdfed_free_name_field_required');

    ob_start();

    if ( ! empty( $error_message ) ) {
        echo '<div class="spdfed-error-message">' . esc_html( $error_message ) . '</div>';
    }
    ?>
    <div class="spdfed-form-wrapper">
        <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" class="spdfed-form">
            <?php if ($name_field_enabled): ?>
            <div class="spdfed-form-row">
                <input type="text"
                       name="spdfed_name"
                       <?php if ($name_field_required) echo 'required'; ?>
                       placeholder="<?php esc_attr_e('Enter your full name', 'email-gated-downloads'); ?>"
                       value="<?php echo esc_attr($submitted_name); ?>"
                       class="spdfed-input">
            </div>
            <?php endif; ?>
            <div class="spdfed-form-row">
                <input type="email" 
                       name="email" 
                       required 
                       placeholder="<?php esc_attr_e('Enter your email', 'email-gated-downloads'); ?>"
                       value="<?php echo esc_attr($submitted_email); ?>"
                       class="spdfed-input">
            </div>
            <?php if ($gdpr_enabled): ?>
                <div class="spdfed-form-row">
                    <label class="spdfed-checkbox-label">
                        <input type="checkbox" name="gdpr" value="1" required>
                        <?php echo esc_html($gdpr_message); ?>
                    </label>
                </div>
            <?php endif; ?>
            <input type="hidden" name="action" value="spdfed_download">
            <input type="hidden" name="post_id" value="0">
            <input type="hidden" name="spdfed_redirect_url" value="<?php echo esc_url( spdfed_get_current_url() ); ?>">
            <?php wp_nonce_field('spdfed_download_nonce_0', 'spdfed_nonce_field'); ?>
            <button type="submit" class="spdfed-button">
                <?php echo esc_html($label); ?>
            </button>
        </form>
    </div>
    <?php
    return ob_get_clean();
}

/**
 * Get the current page URL in a secure way.
 *
 * @return string The current page URL.
 */
function spdfed_get_current_url() {
    $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
    
    // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
    $host = isset($_SERVER['HTTP_HOST']) ? wp_unslash($_SERVER['HTTP_HOST']) : '';
    $host = sanitize_text_field($host);

    // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
    $uri = isset($_SERVER['REQUEST_URI']) ? wp_unslash($_SERVER['REQUEST_URI']) : '';
    $uri = sanitize_text_field($uri);

    return esc_url_raw($protocol . '://' . $host . $uri);
}
