<?php

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

class Kavehboardwalletshortcodes
{

    private $wallet;

    public function __construct()
    {
        $this->wallet = Kavehboardwallet::get_instance();

        // Register shortcodes
        add_shortcode('kaveh_wallet_balance', array($this, 'wallet_balance_shortcode'));
        add_shortcode('kaveh_wallet_add_funds', array($this, 'add_funds_shortcode'));
        add_shortcode('kaveh_wallet_transactions', array($this, 'transactions_shortcode'));
        add_shortcode('kaveh_wallet_dashboard', array($this, 'wallet_dashboard_shortcode'));
        add_shortcode('kaveh_wallet_quick_stats', array($this, 'wallet_quick_stats_shortcode'));

        // AJAX handlers for shortcode functionality
        add_action('wp_ajax_get_wallet_balance', array($this, 'ajax_get_wallet_balance'));
        add_action('wp_ajax_nopriv_get_wallet_balance', array($this, 'ajax_get_wallet_balance'));
        add_action('wp_ajax_get_wallet_transactions', array($this, 'ajax_get_wallet_transactions'));
        add_action('wp_ajax_nopriv_get_wallet_transactions', array($this, 'ajax_get_wallet_transactions'));
    }

    /**
     * Wallet balance shortcode
     * Usage: [kaveh_wallet_balance style="card|simple|detailed"]
     */
    public function wallet_balance_shortcode($atts)
    {
        if (!is_user_logged_in()) {
            return $this->login_required_message();
        }

        // Check if wallet system is enabled
        $options = get_option('kavehboard_options', array());
        if (empty($options['kavehboard_wallet_enable'])) {
            return '<div class="wallet-disabled"><p>' . __('Wallet system is currently disabled.', 'kavehTheme') . '</p></div>';
        }

        $atts = shortcode_atts(array(
            'style' => 'simple',
            'show_currency' => 'yes',
            'class' => ''
        ), $atts);

        $user_id = get_current_user_id();
        $balance = $this->wallet->get_wallet_balance($user_id);

        ob_start();

        switch ($atts['style']) {
            case 'card':
                $this->render_balance_card($balance, $atts);
                break;
            case 'detailed':
                $this->render_balance_detailed($balance, $atts);
                break;
            default:
                $this->render_balance_simple($balance, $atts);
                break;
        }

        return ob_get_clean();
    }

    /**
     * Add funds shortcode
     * Usage: [kaveh_wallet_add_funds title="Add Funds" button_text="Add Money"]
     */
    public function add_funds_shortcode($atts)
    {
        if (!is_user_logged_in()) {
            return $this->login_required_message();
        }

        // Check if wallet system is enabled
        $options = get_option('kavehboard_options', array());
        if (empty($options['kavehboard_wallet_enable'])) {
            return '<div class="wallet-disabled"><p>' . __('Wallet system is currently disabled.', 'kavehTheme') . '</p></div>';
        }

        $atts = shortcode_atts(array(
            'title' => __('Add Funds to Wallet', 'kavehTheme'),
            'button_text' => __('Add Funds', 'kavehTheme'),
            'show_quick_amounts' => 'yes',
            'quick_amounts' => !empty($options['kavehboard_wallet_quick_amounts']) ? $options['kavehboard_wallet_quick_amounts'] : '10,25,50,100,250,500',
            'class' => ''
        ), $atts);

        $min_amount = !empty($options['kavehboard_wallet_min_amount']) ? $options['kavehboard_wallet_min_amount'] : 1;
        $max_amount = !empty($options['kavehboard_wallet_max_amount']) ? $options['kavehboard_wallet_max_amount'] : 10000;

        ob_start();
?>
        <div class="wallet-add-funds <?php echo esc_attr($atts['class']); ?>">
            <h4><?php echo esc_html($atts['title']); ?></h4>

            <?php if ($atts['show_quick_amounts'] === 'yes'): ?>
                <div class="wallet-quick-amounts-section">
                    <label><?php _e('Quick Amounts:', 'kavehTheme'); ?></label>
                    <div class="wallet-quick-amounts">
                        <?php
                        $amounts = explode(',', $atts['quick_amounts']);
                        foreach ($amounts as $amount) {
                            $amount = trim($amount);
                            if (is_numeric($amount)) {
                                echo '<button type="button" class="wallet-quick-amount btn btn-outline-secondary btn-sm" data-amount="' . esc_attr($amount) . '">' . wc_price($amount) . '</button>';
                            }
                        }
                        ?>
                    </div>
                </div>
            <?php endif; ?>

            <form id="wallet-add-funds-form" class="wallet-form">
                <div class="form-group">
                    <label for="wallet-amount"><?php _e('Amount', 'kavehTheme'); ?> <span class="required">*</span></label>
                    <input type="number" id="wallet-amount" name="amount" min="<?php echo esc_attr($min_amount); ?>" max="<?php echo esc_attr($max_amount); ?>" step="0.01" required class="form-control">
                    <!-- translators: 1: minimum amount, 2: maximum amount -->
                    <small class="form-text text-muted"><?php printf(__('Minimum: %1$s, Maximum: %2$s', 'kavehTheme'), wc_price($min_amount), wc_price($max_amount)); ?></small>
                </div>

                <div class="form-group">
                    <label for="wallet-payment-method"><?php _e('Payment Method', 'kavehTheme'); ?> <span class="required">*</span></label>
                    <select id="wallet-payment-method" name="payment_method" required class="form-control">
                        <option value=""><?php _e('Select Payment Method', 'kavehTheme'); ?></option>
                        <?php
                        $gateways = WC()->payment_gateways->get_available_payment_gateways();
                        foreach ($gateways as $gateway) {
                            if ($gateway->enabled === 'yes' && $gateway->id !== 'kaveh_wallet') {
                                echo '<option value="' . esc_attr($gateway->id) . '">' . esc_html($gateway->title) . '</option>';
                            }
                        }
                        ?>
                    </select>
                </div>

                <div class="form-group">
                    <button type="submit" class="btn btn-primary wallet-submit-btn">
                        <i class="fas fa-plus-circle"></i> <?php echo esc_html($atts['button_text']); ?>
                    </button>
                </div>
            </form>
        </div>
    <?php
        return ob_get_clean();
    }

    /**
     * Wallet transactions shortcode
     * Usage: [kaveh_wallet_transactions limit="20" show_pagination="yes"]
     */
    public function transactions_shortcode($atts)
    {
        if (!is_user_logged_in()) {
            return $this->login_required_message();
        }

        // Check if wallet system is enabled
        $options = get_option('kavehboard_options', array());
        if (empty($options['kavehboard_wallet_enable'])) {
            return '<div class="wallet-disabled"><p>' . __('Wallet system is currently disabled.', 'kavehTheme') . '</p></div>';
        }

        $default_limit = !empty($options['kavehboard_wallet_transaction_limit']) ? $options['kavehboard_wallet_transaction_limit'] : 20;

        $atts = shortcode_atts(array(
            'limit' => $default_limit,
            'show_pagination' => 'yes',
            'show_filters' => 'yes',
            'class' => ''
        ), $atts);

        $user_id = get_current_user_id();
        $page = isset($_GET['wallet_page']) ? max(1, intval($_GET['wallet_page'])) : 1;
        $offset = ($page - 1) * $atts['limit'];

        $transactions = $this->wallet->get_wallet_transactions($user_id, $atts['limit'], $offset);
        $total_transactions = $this->get_total_transactions_count($user_id);

        ob_start();
    ?>
        <div class="wallet-transactions <?php echo esc_attr($atts['class']); ?>">
            <div class="wallet-transactions-header">
                <h4><?php _e('Wallet Transactions', 'kavehTheme'); ?></h4>

                <?php if ($atts['show_filters'] === 'yes'): ?>
                    <div class="wallet-transaction-filters">
                        <select id="transaction-type-filter" class="form-control">
                            <option value=""><?php _e('All Types', 'kavehTheme'); ?></option>
                            <option value="credit"><?php _e('Credit', 'kavehTheme'); ?></option>
                            <option value="debit"><?php _e('Debit', 'kavehTheme'); ?></option>
                        </select>

                        <select id="transaction-period-filter" class="form-control">
                            <option value=""><?php _e('All Time', 'kavehTheme'); ?></option>
                            <option value="today"><?php _e('Today', 'kavehTheme'); ?></option>
                            <option value="week"><?php _e('This Week', 'kavehTheme'); ?></option>
                            <option value="month"><?php _e('This Month', 'kavehTheme'); ?></option>
                        </select>
                    </div>
                <?php endif; ?>
            </div>

            <?php if (empty($transactions)): ?>
                <div class="wallet-no-transactions">
                    <p><?php _e('No transactions found.', 'kavehTheme'); ?></p>
                </div>
            <?php else: ?>
                <div class="wallet-transactions-table-container">
                    <table class="wallet-transactions-table">
                        <thead>
                            <tr>
                                <th><?php _e('Date', 'kavehTheme'); ?></th>
                                <th><?php _e('Type', 'kavehTheme'); ?></th>
                                <th><?php _e('Amount', 'kavehTheme'); ?></th>
                                <th><?php _e('Description', 'kavehTheme'); ?></th>
                                <th><?php _e('Balance', 'kavehTheme'); ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($transactions as $transaction): ?>
                                <tr class="transaction-row transaction-<?php echo esc_attr($transaction->transaction_type); ?>">
                                    <td class="transaction-date">
                                        <?php echo date_i18n(get_option('date_format'), strtotime($transaction->created_at)); ?>
                                        <small class="transaction-time"><?php echo date_i18n(get_option('time_format'), strtotime($transaction->created_at)); ?></small>
                                    </td>
                                    <td class="transaction-type transaction-type-<?php echo esc_attr($transaction->transaction_type); ?>">
                                        <span class="transaction-badge">
                                            <?php if ($transaction->transaction_type === 'credit'): ?>
                                                <i class="fas fa-arrow-up"></i> <?php _e('Credit', 'kavehTheme'); ?>
                                            <?php else: ?>
                                                <i class="fas fa-arrow-down"></i> <?php _e('Debit', 'kavehTheme'); ?>
                                            <?php endif; ?>
                                        </span>
                                    </td>
                                    <td class="transaction-amount transaction-amount-<?php echo esc_attr($transaction->transaction_type); ?>">
                                        <?php echo ($transaction->transaction_type === 'credit' ? '+' : '-') . wc_price($transaction->amount); ?>
                                    </td>
                                    <td class="transaction-description">
                                        <?php echo esc_html($transaction->description); ?>
                                        <?php if ($transaction->order_id): ?>
                                            <small><a href="<?php echo esc_url(wc_get_account_endpoint_url('orders')); ?>">#<?php echo $transaction->order_id; ?></a></small>
                                        <?php endif; ?>
                                    </td>
                                    <td class="transaction-balance">
                                        <?php echo wc_price($transaction->balance_after); ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>

                <?php if ($atts['show_pagination'] === 'yes' && $total_transactions > $atts['limit']): ?>
                    <?php $this->render_pagination($page, $atts['limit'], $total_transactions); ?>
                <?php endif; ?>
            <?php endif; ?>
        </div>
    <?php
        return ob_get_clean();
    }

    /**
     * Wallet dashboard shortcode
     * Usage: [kaveh_wallet_dashboard show_balance="yes" show_add_funds="yes" show_transactions="yes"]
     */
    public function wallet_dashboard_shortcode($atts)
    {
        if (!is_user_logged_in()) {
            return $this->login_required_message();
        }

        // Check if wallet system is enabled
        $options = get_option('kavehboard_options', array());
        if (empty($options['kavehboard_wallet_enable'])) {
            return '<div class="wallet-disabled"><p>' . __('Wallet system is currently disabled.', 'kavehTheme') . '</p></div>';
        }

        $atts = shortcode_atts(array(
            'show_balance' => 'yes',
            'show_add_funds' => 'yes',
            'show_transactions' => 'yes',
            'show_quick_stats' => 'yes',
            'transactions_limit' => 10,
            'class' => ''
        ), $atts);

        ob_start();
    ?>
        <div class="wallet-dashboard <?php echo esc_attr($atts['class']); ?>">
            <?php if ($atts['show_balance'] === 'yes'): ?>
                <div class="wallet-balance-section">
                    <?php echo $this->wallet_balance_shortcode(array('style' => 'card')); ?>
                </div>
            <?php endif; ?>
            <?php if ($atts['show_quick_stats'] === 'yes'): ?>
                <?php echo $this->wallet_quick_stats_shortcode(array()); ?>
            <?php endif; ?>

            <div class="wallet-dashboard-content">
                <div class="">


                    <?php if ($atts['show_add_funds'] === 'yes'): ?>
                        <div class="wallet-add-funds-section">
                            <?php echo $this->add_funds_shortcode(array()); ?>
                        </div>

                    <?php endif; ?>
                </div>

                        <?php if ($atts['show_transactions'] === 'yes'): ?>
                            <div class="wallet-transactions-section">
                                <?php echo $this->transactions_shortcode(array('limit' => $atts['transactions_limit'], 'show_pagination' => 'no')); ?>
                                <div class="wallet-view-all-transactions">
                                    <a href="<?php echo esc_url(add_query_arg('wallet_view', 'transactions')); ?>" class="btn btn-outline-primary">
                                        <?php _e('View All Transactions', 'kavehTheme'); ?>
                                    </a>
                                </div>
                            </div>
                        <?php endif; ?>
            </div>
        </div>
    <?php
        return ob_get_clean();
    }

    /**
     * Wallet quick stats shortcode
     * Usage: [kaveh_wallet_quick_stats]
     */
    public function wallet_quick_stats_shortcode($atts)
    {
        if (!is_user_logged_in()) {
            return $this->login_required_message();
        }

        // Check if wallet system is enabled
        $options = get_option('kavehboard_options', array());
        if (empty($options['kavehboard_wallet_enable'])) {
            return '<div class="wallet-disabled"><p>' . __('Wallet system is currently disabled.', 'kavehTheme') . '</p></div>';
        }

        $user_id = get_current_user_id();
        $balance = $this->wallet->get_wallet_balance($user_id);
        $stats = $this->get_wallet_stats($user_id);

        ob_start();
    ?>
        <div class="wallet-quick-stats">
            <div class="wallet-stat-card balance">
                <div class="stat-value"><?php echo wc_price($balance); ?></div>
                <div class="stat-label"><?php _e('Current Balance', 'kavehTheme'); ?></div>
            </div>

            <div class="wallet-stat-card spent">
                <div class="stat-value"><?php echo wc_price($stats['total_spent']); ?></div>
                <div class="stat-label"><?php _e('Total Spent', 'kavehTheme'); ?></div>
            </div>

            <div class="wallet-stat-card added">
                <div class="stat-value"><?php echo wc_price($stats['total_added']); ?></div>
                <div class="stat-label"><?php _e('Total Added', 'kavehTheme'); ?></div>
            </div>

            <div class="wallet-stat-card transactions">
                <div class="stat-value"><?php echo number_format($stats['transaction_count']); ?></div>
                <div class="stat-label"><?php _e('Transactions', 'kavehTheme'); ?></div>
            </div>
        </div>
    <?php
        return ob_get_clean();
    }

    // Helper methods
    private function render_balance_simple($balance, $atts)
    {
    ?>
        <div class="wallet-balance-display simple <?php echo esc_attr($atts['class']); ?>">
            <strong><?php _e('Wallet Balance: ', 'kavehTheme'); ?><?php echo wc_price($balance); ?></strong>
        </div>
    <?php
    }

    private function render_balance_card($balance, $atts)
    {
    ?>
        <div class="wallet-balance-display card <?php echo esc_attr($atts['class']); ?>">
            <div class="balance-icon">
                <i class="isax isax-empty-wallet-tick4"></i>
            </div>
            <div class="balance-content">
                <div class="balance-label"><?php _e('Wallet Balance', 'kavehTheme'); ?></div>
                <div class="balance-amount"><?php echo wc_price($balance); ?></div>
            </div>
        </div>
    <?php
    }

    private function render_balance_detailed($balance, $atts)
    {
        $user_id = get_current_user_id();
        $stats = $this->get_wallet_stats($user_id);

    ?>
        <div class="wallet-balance-display detailed <?php echo esc_attr($atts['class']); ?>">
            <div class="balance-main">
                <div class="balance-amount"><?php echo wc_price($balance); ?></div>
                <div class="balance-label"><?php _e('Available Balance', 'kavehTheme'); ?></div>
            </div>
            <div class="balance-stats">
                <div class="stat-item">
                    <span class="stat-value"><?php echo wc_price($stats['total_added']); ?></span>
                    <span class="stat-label"><?php _e('Total Added', 'kavehTheme'); ?></span>
                </div>
                <div class="stat-item">
                    <span class="stat-value"><?php echo wc_price($stats['total_spent']); ?></span>
                    <span class="stat-label"><?php _e('Total Spent', 'kavehTheme'); ?></span>
                </div>
            </div>
        </div>
    <?php
    }

    private function render_pagination($current_page, $per_page, $total_items)
    {
        $total_pages = ceil($total_items / $per_page);

        if ($total_pages <= 1) {
            return;
        }

    ?>
        <div class="wallet-pagination">
            <?php if ($current_page > 1): ?>
                <a href="<?php echo esc_url(add_query_arg('wallet_page', $current_page - 1)); ?>" class="wallet-page-link prev">
                    <i class="fas fa-chevron-left"></i> <?php _e('Previous', 'kavehTheme'); ?>
                </a>
            <?php endif; ?>

            <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                <?php if ($i == $current_page): ?>
                    <span class="wallet-page-link current"><?php echo $i; ?></span>
                <?php else: ?>
                    <a href="<?php echo esc_url(add_query_arg('wallet_page', $i)); ?>" class="wallet-page-link"><?php echo $i; ?></a>
                <?php endif; ?>
            <?php endfor; ?>

            <?php if ($current_page < $total_pages): ?>
                <a href="<?php echo esc_url(add_query_arg('wallet_page', $current_page + 1)); ?>" class="wallet-page-link next">
                    <?php _e('Next', 'kavehTheme'); ?> <i class="fas fa-chevron-right"></i>
                </a>
            <?php endif; ?>
        </div>
<?php
    }

    private function get_wallet_stats($user_id)
    {
        global $wpdb;

        $transactions_table = $wpdb->prefix . 'kaveh_wallet_transactions';

        $stats = $wpdb->get_row($wpdb->prepare(
            "SELECT 
                SUM(CASE WHEN transaction_type = 'credit' THEN amount ELSE 0 END) as total_added,
                SUM(CASE WHEN transaction_type = 'debit' THEN amount ELSE 0 END) as total_spent,
                COUNT(*) as transaction_count
             FROM {$transactions_table} 
             WHERE user_id = %d AND status = 'completed'",
            $user_id
        ));

        return array(
            'total_added' => $stats->total_added ?: 0,
            'total_spent' => $stats->total_spent ?: 0,
            'transaction_count' => $stats->transaction_count ?: 0
        );
    }

    private function get_total_transactions_count($user_id)
    {
        global $wpdb;

        $transactions_table = $wpdb->prefix . 'kaveh_wallet_transactions';

        return $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM {$transactions_table} WHERE user_id = %d",
            $user_id
        ));
    }

    private function login_required_message()
    {
        return '<div class="wallet-login-required"><p>' . __('Please log in to access your wallet.', 'kavehTheme') . '</p></div>';
    }

    // AJAX handlers
    public function ajax_get_wallet_balance()
    {
        check_ajax_referer('kaveh_wallet_nonce', 'nonce');

        if (!is_user_logged_in()) {
            wp_die(json_encode(array('success' => false, 'message' => 'User not logged in')));
        }

        $user_id = get_current_user_id();
        $balance = $this->wallet->get_wallet_balance($user_id);

        wp_die(json_encode(array(
            'success' => true,
            'balance' => $balance,
            'formatted_balance' => wc_price($balance)
        )));
    }

    public function ajax_get_wallet_transactions()
    {
        check_ajax_referer('kaveh_wallet_nonce', 'nonce');

        if (!is_user_logged_in()) {
            wp_die(json_encode(array('success' => false, 'message' => 'User not logged in')));
        }

        $page = isset($_POST['page']) ? max(1, intval($_POST['page'])) : 1;
        $limit = isset($_POST['limit']) ? max(1, intval($_POST['limit'])) : 20;
        $offset = ($page - 1) * $limit;

        $user_id = get_current_user_id();
        $transactions = $this->wallet->get_wallet_transactions($user_id, $limit, $offset);

        ob_start();
        echo $this->transactions_shortcode(array('limit' => $limit, 'show_pagination' => 'yes'));
        $html = ob_get_clean();

        wp_die(json_encode(array(
            'success' => true,
            'html' => $html
        )));
    }
}

new Kavehboardwalletshortcodes();
