<?php
// phpcs:disable WordPress.Security.EscapeOutput.OutputNotEscaped,WordPress.Security.EscapeOutput.ExceptionNotEscaped,WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.PreparedSQLPlaceholders.LikeWildcardsInQuery,PluginCheck.Security.DirectDB.UnescapedDBParameter,WordPress.WP.AlternativeFunctions.file_system_operations_fopen,WordPress.WP.AlternativeFunctions.file_system_operations_fclose,WordPress.WP.AlternativeFunctions.file_system_operations_is_writable,WordPress.WP.AlternativeFunctions.file_system_operations_chmod,WordPress.WP.AlternativeFunctions.file_system_operations_rmdir,WordPress.DateTime.RestrictedFunctions.date_date,WordPress.WP.I18n.NonSingularStringLiteralDomain,WordPress.WP.I18n.MissingTranslatorsComment,WordPress.WP.I18n.MissingArgDomain,WordPressVIPMinimum.Performance.WPQueryParams.SuppressFilters_suppress_filters,WordPress.WP.EnqueuedResources.NonEnqueuedScript,WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet -- WordPress.org PCP audit pass: legacy controlled-beta surfaces require targeted follow-up hardening.
/**
 * Aysa Credits Component
 * 
 * A reusable component for displaying and managing Aysa credits across the plugin.
 * 
 * @since 1.0.0
 */

// If this file is called directly, abort.
if (!defined('WPINC')) {
    die;
}

class Aysa_Credits_Component {
    /**
     * The ID for the user
     * 
     * @var int
     */
    private $user_id;
    
    /**
     * API base URL
     * 
     * @var string
     */
    private $api_base_url;
    
    /**
     * Constructor
     * 
     * @param int $user_id Optional user ID (defaults to 0 for demo mode)
     */
    public function __construct($user_id = 0) {
        $this->user_id = $user_id;
        $this->api_base_url = AYSA_API_BASE_URL;
        
        // Register scripts and styles
        add_action('admin_enqueue_scripts', array($this, 'enqueue_scripts'));
        
        // Register AJAX handlers
        add_action('wp_ajax_aysa_get_credits', array($this, 'ajax_get_credits'));
        add_action('wp_ajax_aysa_buy_credits', array($this, 'ajax_buy_credits'));
    }

    /**
     * Get wallet manager singleton.
     *
     * @return Aysa_Wallet_Manager|null
     */
    private function wallet_manager() {
        if (!class_exists('Aysa_Wallet_Manager')) {
            $wallet_file = AYSA_PLUGIN_DIR . 'includes/class-aysa-wallet-manager.php';
            if (file_exists($wallet_file)) {
                require_once $wallet_file;
            }
        }
        if (!class_exists('Aysa_Wallet_Manager')) {
            return null;
        }
        return Aysa_Wallet_Manager::get_instance();
    }
    
    /**
     * Enqueue scripts and styles for the credits component
     */
    public function enqueue_scripts() {
        $js_path = AYSA_PLUGIN_DIR . 'assets/js/aysa-credits-component.js';
        $css_path = AYSA_PLUGIN_DIR . 'assets/css/aysa-credits-component.css';
        $js_ver = file_exists($js_path) ? (string) filemtime($js_path) : AYSA_VERSION;
        $css_ver = file_exists($css_path) ? (string) filemtime($css_path) : AYSA_VERSION;

        wp_enqueue_script(
            'aysa-credits-component', 
            AYSA_PLUGIN_URL . 'assets/js/aysa-credits-component.js',
            array('jquery'),
            $js_ver,
            true
        );
        
        wp_localize_script(
            'aysa-credits-component',
            'aysa_credits_params',
            array(
                'ajax_url' => admin_url('admin-ajax.php'),
                'nonce' => wp_create_nonce('aysa_credits_nonce'),
                'standard_nonce' => wp_create_nonce('aysa_nonce'),
                'api_base_url' => $this->api_base_url,
                'user_id' => $this->user_id,
                // Keep credits widget on the same project across all admin sections.
                'project_id' => intval($this->get_project_id())
            )
        );
        
        wp_enqueue_style(
            'aysa-credits-component',
            AYSA_PLUGIN_URL . 'assets/css/aysa-credits-component.css',
            array(),
            $css_ver
        );
    }
    
    /**
     * Get project ID from various sources
     */
    private function get_project_id() {
        if (isset($_POST['project_id'])) {
            $project_id = intval(wp_unslash($_POST['project_id']));
            if ($project_id > 0) {
                return $project_id;
            }
        }

        $wallet_manager = $this->wallet_manager();
        if ($wallet_manager) {
            $project_id = intval($wallet_manager->get_project_id());
            if ($project_id > 0) {
                return $project_id;
            }
        }

        $project_id = intval(get_option('aysa_project_id', 0));
        if ($project_id > 0) {
            return $project_id;
        }

        return 0;
    }
    
    /**
     * Get credits from the API
     * 
     * @return int Credits amount
     */
    private function get_user_credits() {
        $project_id = $this->get_project_id();
        if (!$project_id) {
            return 0;
        }
        $wallet_manager = $this->wallet_manager();
        if (!$wallet_manager) {
            return 0;
        }
        // UI read path must be local-first to avoid blocking admin pages.
        $snapshot = $wallet_manager->get_wallet_snapshot($project_id, array('allow_remote' => true));
        return intval($snapshot['balance_cents'] ?? 0);
    }
    
    /**
     * Render the credits component
     */
    public function render() {
        // Safety checks
        try {
            ob_start();
            ?>
            <div class="aysa-credits-component">
                <span class="aysa-credits-value">Credits: <span class="aysa-credits-amount"><span class="aysa-loading-spinner"></span></span></span>
                <div class="aysa-credits-meta"></div>
                <button type="button" class="aysa-buy-credits-btn">Buy more credits</button>
            </div>
            <?php
            return ob_get_clean();
        } catch (Exception $e) {
            // If any error occurs, return a simple fallback with loading
            return '<div class="aysa-credits-component">
                <span class="aysa-credits-value">Credits: <span class="aysa-credits-amount"><span class="aysa-loading-spinner"></span></span></span><button type="button" class="aysa-buy-credits-btn">Buy more credits</button>
                <div class="aysa-credits-meta"></div>
            </div>';
        }
    }
    
    /**
     * AJAX handler for getting credits
     */
    public function ajax_get_credits() {
        // Verify nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'aysa_credits_nonce')) {
            wp_send_json_error(array('message' => 'Security check failed'));
            return;
        }
        
        try {
            // In a real implementation, this would make an API request
            // For demo purposes, we'll simulate the API call
            $project_id = $this->get_project_id();
            $credits = $this->get_user_credits();
            $snapshot = array();
            $wallet_manager = $this->wallet_manager();
            if ($wallet_manager && $project_id > 0) {
                $snapshot = $wallet_manager->get_wallet_snapshot($project_id, array('allow_remote' => true));
            }
            
            wp_send_json_success(array(
                'credits' => $credits,
                'snapshot' => $snapshot,
                'message' => 'Credits retrieved successfully'
            ));
        } catch (Exception $e) {
            wp_send_json_error(array(
                'message' => $e->getMessage()
            ));
        }
    }
    
    /**
     * AJAX handler for buying credits
     */
    public function ajax_buy_credits() {
        // Verify nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'aysa_credits_nonce')) {
            wp_send_json_error(array('message' => 'Security check failed'));
            return;
        }
        
        try {
            $project_id = isset($_POST['project_id']) ? intval(wp_unslash($_POST['project_id'])) : $this->get_project_id();
            $credits_cents = isset($_POST['credits_cents']) ? intval(wp_unslash($_POST['credits_cents'])) : 0;

            if ($project_id <= 0) {
                wp_send_json_error(array('message' => 'Project ID missing. Complete setup first.'));
                return;
            }

            if ($credits_cents <= 0) {
                wp_send_json_error(array('message' => 'Invalid credits amount.'));
                return;
            }

            $wallet_manager = $this->wallet_manager();
            if (!$wallet_manager) {
                wp_send_json_error(array('message' => 'Wallet manager unavailable.'));
                return;
            }

            $order = $wallet_manager->create_topup_order($project_id, $credits_cents, get_current_user_id());
            if (is_wp_error($order)) {
                wp_send_json_error(array('message' => $order->get_error_message()));
                return;
            }

            wp_send_json_success(array(
                'message' => 'Credit order created. Complete payment to top up wallet.',
                'order' => $order,
                'payment_link' => (string) ($order['payment_link'] ?? ''),
            ));
        } catch (Exception $e) {
            wp_send_json_error(array(
                'message' => $e->getMessage()
            ));
        }
    }
    
    /**
     * Static function to display the credits component
     * Easy to use in any template with: <?php Aysa_Credits_Component::display(); ?>
     */
    public static function display() {
        global $aysa_admin;
        
        if (isset($aysa_admin) && property_exists($aysa_admin, 'credits_component')) {
            echo $aysa_admin->credits_component->render();
        } else {
            // If global instance not available, create a new instance
            $credits_component = new self();
            echo $credits_component->render();
        }
    }
} 
