<?php

if (!defined('WPINC')) {
    die;
}

/**
 * AJAX handler for credit analytics functionality
 */
class Aysa_Credit_Analytics_Ajax {
    
    /**
     * Constructor
     */
    public function __construct() {
        $this->init_hooks();
    }
    
    /**
     * Initialize WordPress hooks
     */
    private function init_hooks() {
        // AJAX handlers for logged-in users
        add_action('wp_ajax_aysa_get_credit_balance', array($this, 'ajax_get_credit_balance'));
        add_action('wp_ajax_aysa_get_credit_summary', array($this, 'ajax_get_credit_summary'));
        add_action('wp_ajax_aysa_get_credit_breakdown', array($this, 'ajax_get_credit_breakdown'));
        add_action('wp_ajax_aysa_get_credit_history', array($this, 'ajax_get_credit_history'));
        add_action('wp_ajax_aysa_get_expiring_credits', array($this, 'ajax_get_expiring_credits'));
    }

    /**
     * @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();
    }

    /**
     * Remote-first snapshot so UI reflects API wallet state.
     */
    private function get_local_snapshot($project_id, $wallet) {
        if (!$wallet || intval($project_id) <= 0) {
            return array();
        }
        return $wallet->get_wallet_snapshot(intval($project_id), array('allow_remote' => true));
    }
    
    /**
     * Get current credit balance
     */
    public function ajax_get_credit_balance() {
        try {
            // Verify nonce
            if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'aysa_credit_analytics_nonce')) {
                wp_send_json_error('Security check failed');
                return;
            }
            
            // Check user capabilities
            if (!current_user_can('manage_options')) {
                aysa_debug_log('AYSA Credit Analytics: User lacks manage_options capability');
                wp_send_json_error('Insufficient permissions');
                return;
            }
            
            // Get project ID
            $project_id = $this->get_project_id();
            if (empty($project_id)) {
                wp_send_json_error('Project ID not found');
                return;
            }

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

            $snapshot = $this->get_local_snapshot($project_id, $wallet);
            wp_send_json_success(array(
                'project_id' => intval($project_id),
                'totalCredits' => intval($snapshot['balance_cents'] ?? 0),
                'currentBalance' => intval($snapshot['balance_cents'] ?? 0),
                'spendableCredits' => intval($snapshot['spendable_cents'] ?? 0),
                'reservedForLinks' => intval($snapshot['reserved_links_cents'] ?? 0),
                'plan' => array(
                    'code' => (string) ($snapshot['plan_code'] ?? ''),
                    'label' => (string) ($snapshot['plan_label'] ?? ''),
                    'recommended_keywords' => intval($snapshot['recommended_keywords'] ?? 0),
                    'included_links' => intval($snapshot['included_links'] ?? 0),
                ),
            ));
            
        } catch (Exception $e) {
            wp_send_json_error('Server error: ' . $e->getMessage());
        }
    }
    
    /**
     * Get credit summary
     */
    public function ajax_get_credit_summary() {
        try {
            // Verify nonce
            if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'aysa_credit_analytics_nonce')) {
                wp_send_json_error('Security check failed');
                return;
            }
            
            // Check user capabilities
            if (!current_user_can('manage_options')) {
                wp_send_json_error('Insufficient permissions');
                return;
            }
            
            // Get project ID instead of user ID
            $project_id = $this->get_project_id();
            if (empty($project_id)) {
                wp_send_json_error('Project ID is required');
                return;
            }

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

            $snapshot = $this->get_local_snapshot($project_id, $wallet);
            $orders = $wallet->get_orders($project_id, 100);
            $pending_orders = 0;
            $pending_amount_cents = 0;
            $paid_amount_cents = 0;
            foreach ($orders as $order) {
                $amount = intval($order['amount_cents'] ?? 0);
                if (($order['status'] ?? '') === 'pending') {
                    $pending_orders++;
                    $pending_amount_cents += $amount;
                } elseif (($order['status'] ?? '') === 'paid') {
                    $paid_amount_cents += $amount;
                }
            }

            wp_send_json_success(array(
                'currentBalance' => intval($snapshot['balance_cents'] ?? 0),
                'totalEarned' => intval($snapshot['monthly_credits_cents'] ?? 0),
                'totalCreditsUsed' => max(0, intval($snapshot['monthly_credits_cents'] ?? 0) - intval($snapshot['spendable_cents'] ?? 0)),
                'totalSpent' => max(0, intval($snapshot['monthly_credits_cents'] ?? 0) - intval($snapshot['spendable_cents'] ?? 0)),
                'creditsThisMonth' => max(0, intval($snapshot['monthly_credits_cents'] ?? 0) - intval($snapshot['spendable_cents'] ?? 0)),
                'averageDailyUsage' => max(0, (int) round((max(0, intval($snapshot['monthly_credits_cents'] ?? 0) - intval($snapshot['spendable_cents'] ?? 0))) / 30)),
                'availableSpendable' => intval($snapshot['spendable_cents'] ?? 0),
                'reservedForLinks' => intval($snapshot['reserved_links_cents'] ?? 0),
                'pendingOrders' => $pending_orders,
                'pendingAmountCents' => $pending_amount_cents,
                'paidTopupsCents' => $paid_amount_cents,
            ));
            
        } catch (Exception $e) {
            wp_send_json_error('Server error: ' . $e->getMessage());
        }
    }
    
    /**
     * Get credit breakdown by type
     */
    public function ajax_get_credit_breakdown() {
        try {
            // Verify nonce
            if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'aysa_credit_analytics_nonce')) {
                wp_send_json_error('Security check failed');
                return;
            }
            
            // Check user capabilities
            if (!current_user_can('manage_options')) {
                wp_send_json_error('Insufficient permissions');
                return;
            }
            
            // Get project ID
            $project_id = $this->get_project_id();
            if (empty($project_id)) {
                wp_send_json_error('Project ID not found');
                return;
            }

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

            $snapshot = $this->get_local_snapshot($project_id, $wallet);
            $breakdown = array(
                array('name' => 'Spendable', 'credits' => intval($snapshot['spendable_cents'] ?? 0)),
                array('name' => 'Reserved links budget', 'credits' => intval($snapshot['reserved_links_cents'] ?? 0)),
            );

            wp_send_json_success(array(
                'creditBreakdown' => $breakdown,
                'categoryBreakdown' => $breakdown,
            ));
            
        } catch (Exception $e) {
            wp_send_json_error('Server error: ' . $e->getMessage());
        }
    }
    
    /**
     * Get credit transaction history
     */
    public function ajax_get_credit_history() {
        try {
            // Verify nonce
            if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'aysa_credit_analytics_nonce')) {
                wp_send_json_error('Security check failed');
                return;
            }
            
            // Check user capabilities
            if (!current_user_can('manage_options')) {
                wp_send_json_error('Insufficient permissions');
                return;
            }
            
            // Get project ID instead of user ID
            $project_id = $this->get_project_id();
            if (empty($project_id)) {
                wp_send_json_error('Project ID is required');
                return;
            }
            
            $wallet = $this->wallet_manager();
            if (!$wallet) {
                wp_send_json_error('Wallet manager unavailable');
                return;
            }

            $orders = $wallet->get_orders($project_id, 100);
            $items = array();
            foreach ($orders as $order) {
                $amount = intval($order['amount_cents'] ?? 0);
                $items[] = array(
                    'id' => intval($order['id'] ?? 0),
                    'category' => (($order['status'] ?? '') === 'paid') ? 'credit_purchase' : 'credit_pending_order',
                    'creditsUsed' => (($order['status'] ?? '') === 'paid') ? $amount : 0,
                    'amount_cents' => $amount,
                    'transactionType' => (string) ($order['status'] ?? 'pending'),
                    'description' => sprintf('Top-up order #%d', intval($order['id'] ?? 0)),
                    'createdAt' => (string) ($order['created_at'] ?? ''),
                );
            }

            wp_send_json_success(array(
                'records' => $items,
                'transactions' => $items,
                'total' => count($items),
                'page' => 1,
                'pageSize' => count($items),
                'currentBalance' => intval($wallet->get_wallet_snapshot(intval($project_id), array('allow_remote' => true))['balance_cents'] ?? 0),
            ));
            
        } catch (Exception $e) {
            wp_send_json_error('Server error: ' . $e->getMessage());
        }
    }
    
    /**
     * Get expiring credits
     */
    public function ajax_get_expiring_credits() {
        try {
            // Verify nonce
            if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'aysa_credit_analytics_nonce')) {
                wp_send_json_error('Security check failed');
                return;
            }
            
            // Check user capabilities
            if (!current_user_can('manage_options')) {
                wp_send_json_error('Insufficient permissions');
                return;
            }
            
            // Get project ID
            $project_id = $this->get_project_id();
            if (empty($project_id)) {
                wp_send_json_error('Project ID not found');
                return;
            }

            // No expiration model yet in local wallet; expose current reserved budget instead.
            $wallet = $this->wallet_manager();
            if (!$wallet) {
                wp_send_json_error('Wallet manager unavailable');
                return;
            }
            $snapshot = $this->get_local_snapshot($project_id, $wallet);
            wp_send_json_success(array(
                'expiringCredits' => 0,
                'reservedForLinks' => intval($snapshot['reserved_links_cents'] ?? 0),
            ));
            
        } catch (Exception $e) {
            wp_send_json_error('Server error: ' . $e->getMessage());
        }
    }
    
    /**
     * Get project ID from various sources
     */
    private function get_project_id() {
        $wallet = $this->wallet_manager();
        if ($wallet) {
            $project_id = intval($wallet->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;
    }
}
