<?php
// Prevent direct access
if (!defined('ABSPATH')) exit;

class SITSEL_Stripe_Shortcodes {

    public function __construct() {
        add_shortcode('sitsel_success', [$this, 'success_page']);
        add_shortcode('sitsel_failed', [$this, 'failed_page']);
        add_action('wp_enqueue_scripts', [$this, 'load_styles_conditionally']);
    }

  
    public function load_styles_conditionally() {
        global $post;
        
   
        $cache_key = 'sitsel_has_shortcodes_' . ($post ? $post->ID : 0);
        $has_shortcodes = wp_cache_get($cache_key);
        
        if (false === $has_shortcodes) {
         
            $has_shortcodes = ($post && (
                has_shortcode($post->post_content, 'sitsel_success') || 
                has_shortcode($post->post_content, 'sitsel_failed')
            )) ? 1 : 0;
            
          
            wp_cache_set($cache_key, $has_shortcodes, '', 3600);
        }
        
    
        if ($has_shortcodes) {
            wp_enqueue_style(
                'sitsel-shortcodes-css',
                SITS_ELEMENTOR_ADDONS_PLUGIN_URL . 'assets/css/shortcodes.css',
                [],
                SITS_ELEMENTOR_ADDONS_VERSION
            );
        }
    }

    public function success_page() {
        // No nonce verification needed - this is a public shortcode on success/cancel pages
        global $wpdb;
        $table = $wpdb->prefix . "sitsel_payments";
        
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        if (!isset($_GET['session_id'])) {
            return ""; // Return empty if no session_id
        }
        
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $session_id = sanitize_text_field(wp_unslash($_GET['session_id']));

        // ✅ Cache payment data for 1 hour
        $cache_key = 'sitsel_payment_' . $session_id;
        $data = wp_cache_get($cache_key);

        if (false === $data) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
            $data = $wpdb->get_row($wpdb->prepare(
                "SELECT * FROM " . $wpdb->prefix . "sitsel_payments WHERE payment_id = %s LIMIT 1",
                $session_id
            ));
            wp_cache_set($cache_key, $data, '', 3600); // Cache for 1 hour
        }

        if (!$data) {
            return ""; // Return empty if no data found
        }

        // CRITICAL FIX: Only show success content if status is actually 'success'
        if ($data->status !== 'success') {
            return ""; // Hide this shortcode if payment is not successful
        }

        ob_start();
        ?>
        <div class="sitsel-success-container">
            <h2 class="sitsel-success-heading">🎉 Payment Successful</h2>
            <table class="sitsel-table">
                <tr><th>Name</th><td><?php echo esc_html($data->name); ?></td></tr>
                <tr><th>Email</th><td><?php echo esc_html($data->email); ?></td></tr>
                <tr><th>Price</th><td>
                    <?php
                    $currency_symbols = [
                        'USD' => '$',
                        'EUR' => '€',
                        'GBP' => '£',
                        'INR' => '₹',
                        'AUD' => 'A$',
                        'CAD' => 'C$',
                        'JPY' => '¥',
                        'CNY' => '¥',
                        'CHF' => 'CHF',
                        'AED' => 'د.إ',
                    ];
                    $sym = $currency_symbols[$data->currency] ?? $data->currency;
                    $zero_decimal = in_array($data->currency, ['JPY', 'KRW', 'VND']);
                    $decimals = $zero_decimal ? 0 : 2;
                    echo esc_html($sym . number_format($data->price, $decimals));
                    ?>
                </td></tr>
                <tr><th>Currency</th><td><?php echo esc_html($data->currency); ?></td></tr>
                <tr><th>Status</th><td class="sitsel-status-success">Success</td></tr>
                <tr><th>Payment ID</th><td><?php echo esc_html($data->payment_id); ?></td></tr>
            </table>

            <a href="<?php echo esc_url(home_url()); ?>" class="sitsel-btn sitsel-btn-primary">⬅ Back to Home</a>
        </div>

        <?php
        return ob_get_clean();
    }

    public function failed_page() {
        // No nonce verification needed - this is a public shortcode on success/cancel pages
        global $wpdb;
        $table = $wpdb->prefix . "sitsel_payments";

        // If no session ID found
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        if (!isset($_GET['session_id']) || empty($_GET['session_id'])) {
            return ""; // Return empty instead of showing error
        }
        
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $session_id = sanitize_text_field(wp_unslash($_GET['session_id']));

        // ✅ Cache payment data for 1 hour
        $cache_key = 'sitsel_payment_' . $session_id;
        $data = wp_cache_get($cache_key);

        if (false === $data) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
            $data = $wpdb->get_row($wpdb->prepare(
                "SELECT * FROM " . $wpdb->prefix . "sitsel_payments WHERE payment_id = %s LIMIT 1",
                $session_id
            ));
            wp_cache_set($cache_key, $data, '', 3600); // Cache for 1 hour
        }

        // If no record found
        if (!$data) {
            return ""; // Return empty if no data found
        }

        // CRITICAL FIX: Don't show failed content if payment is successful
        if ($data->status === 'success') {
            return ""; // Hide this shortcode if payment was successful
        }

        // Update status ONLY if it's pending (not already failed)
        if ($data->status === 'pending') {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
            $wpdb->update(
                $table,
                ['status' => 'failed'],
                ['payment_id' => $session_id],
                ['%s'],
                ['%s']
            );
            
            // Clear cache after update
            wp_cache_delete($cache_key);
        }

        ob_start();
        ?>
        <div class="sitsel-failed-container">
            <h2 class="sitsel-failed-heading">❌ Payment Failed</h2>
            <table class="sitsel-table">
                <tr><th>Name</th><td><?php echo esc_html($data->name); ?></td></tr>
                <tr><th>Email</th><td><?php echo esc_html($data->email); ?></td></tr>
                <tr><th>Price</th><td>
                    <?php
                    $currency_symbols = [
                        'USD' => '$',
                        'EUR' => '€',
                        'GBP' => '£',
                        'INR' => '₹',
                        'AUD' => 'A$',
                        'CAD' => 'C$',
                        'JPY' => '¥',
                        'CNY' => '¥',
                        'CHF' => 'CHF',
                        'AED' => 'د.إ',
                    ];
                    $sym = $currency_symbols[$data->currency] ?? $data->currency;
                    $zero_decimal = in_array($data->currency, ['JPY', 'KRW', 'VND']);
                    $decimals = $zero_decimal ? 0 : 2;
                    echo esc_html($sym . number_format($data->price, $decimals));
                    ?>
                </td></tr>
                <tr><th>Currency</th><td><?php echo esc_html($data->currency); ?></td></tr>
                <tr><th>Status</th><td class="sitsel-status-failed">Failed</td></tr>
                <tr><th>Payment ID</th><td><?php echo esc_html($data->payment_id); ?></td></tr>
            </table>

            <a href="<?php echo esc_url(home_url()); ?>" class="sitsel-btn sitsel-btn-primary">⬅ Back to Home</a>
        </div>
        <?php

        return ob_get_clean();
    }

}

new SITSEL_Stripe_Shortcodes();