<?php

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

class Kavehboardwallet {

    private static $instance = null;
    private $table_name;
    private $transactions_table;

    public $options;

    public static function get_instance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    private function __construct() {
        global $wpdb;
        $this->table_name = $wpdb->prefix . 'kaveh_wallet';
        $this->transactions_table = $wpdb->prefix . 'kaveh_wallet_transactions';
        $this->options = get_option('kavehboard_options');

        if($this->options['kavehboard_wallet_enable'] !== '1'){
            return;
        }

        add_action('init', array($this, 'init'));
        add_action('wp_enqueue_scripts', array($this, 'enqueue_scripts'));
        add_action('wp_ajax_add_wallet_funds', array($this, 'ajax_add_wallet_funds'));
        add_action('wp_ajax_nopriv_add_wallet_funds', array($this, 'ajax_add_wallet_funds'));
        add_action('wp_ajax_process_wallet_payment', array($this, 'ajax_process_wallet_payment'));
        add_action('wp_ajax_nopriv_process_wallet_payment', array($this, 'ajax_process_wallet_payment'));
        
        // WooCommerce hooks - coupon-like wallet system
        add_action('woocommerce_review_order_before_payment', array($this, 'display_wallet_balance_on_checkout'));
        add_action('woocommerce_cart_calculate_fees', array($this, 'apply_wallet_discount'));
        add_action('woocommerce_checkout_update_order_meta', array($this, 'save_wallet_usage_meta'));
        add_action('woocommerce_payment_complete', array($this, 'deduct_wallet_funds_on_payment_complete'));
        add_action('woocommerce_order_status_completed', array($this, 'deduct_wallet_funds_on_order_complete'));
        add_action('wp_ajax_apply_wallet_discount', array($this, 'ajax_apply_wallet_discount'));
        add_action('wp_ajax_nopriv_apply_wallet_discount', array($this, 'ajax_apply_wallet_discount'));
        add_action('woocommerce_checkout_process', array($this, 'validate_wallet_payment'));
        
        // Admin hooks
        add_action('show_user_profile', array($this, 'add_wallet_fields_to_user_profile'));
        add_action('edit_user_profile', array($this, 'add_wallet_fields_to_user_profile'));
        add_action('personal_options_update', array($this, 'save_wallet_fields'));
        add_action('edit_user_profile_update', array($this, 'save_wallet_fields'));
        
        // Shortcodes are now handled by Kavehboardwalletshortcodes class
        
        // Remove payment gateway - now using coupon-like system
        // add_action('plugins_loaded', array($this, 'include_gateway'));
    }

    public function init() {
        $this->create_tables();
    }
    
    // Removed gateway methods - now using coupon-like system

    public function enqueue_scripts() {
        wp_enqueue_script('kaveh-wallet-js', get_template_directory_uri() . '/inc/plugins/kavehboard/assets/js/wallet.js', array('jquery'), '1.0.0', true);
        wp_enqueue_style('kaveh-wallet-css', get_template_directory_uri() . '/inc/plugins/kavehboard/assets/css/wallet.css', array(), '1.0.0');
        
        wp_localize_script('kaveh-wallet-js', 'kaveh_wallet_ajax', array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('kaveh_wallet_nonce'),
            'currency_symbol' => get_woocommerce_currency_symbol(),
            'checkout_url' => wc_get_checkout_url()
        ));
        
        // Enqueue checkout script if on checkout page
        if (is_checkout()) {
            wp_enqueue_script('kaveh-wallet-checkout', get_template_directory_uri() . '/inc/plugins/kavehboard/assets/js/wallet-checkout.js', array('jquery'), '1.0.0', true);
            
            wp_localize_script('kaveh-wallet-checkout', 'kaveh_wallet_checkout', array(
                'ajax_url' => admin_url('admin-ajax.php'),
                'nonce' => wp_create_nonce('kaveh_wallet_nonce'),
                'currency_symbol' => get_woocommerce_currency_symbol(),
                'messages' => array(
                    'error_applying_discount' => __('Error applying wallet discount', 'kavehTheme'),
                    'available_balance' => __('Available Balance:', 'kavehTheme')
                )
            ));
        }
    }

    private function create_tables() {
        global $wpdb;
        
        $charset_collate = $wpdb->get_charset_collate();
        
        // Wallet balance table
        $sql1 = "CREATE TABLE IF NOT EXISTS {$this->table_name} (
            id int(11) NOT NULL AUTO_INCREMENT,
            user_id bigint(20) NOT NULL,
            balance decimal(10,2) NOT NULL DEFAULT 0.00,
            created_at datetime DEFAULT CURRENT_TIMESTAMP,
            updated_at datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            UNIQUE KEY user_id (user_id)
        ) $charset_collate;";
        
        // Wallet transactions table
        $sql2 = "CREATE TABLE IF NOT EXISTS {$this->transactions_table} (
            id int(11) NOT NULL AUTO_INCREMENT,
            user_id bigint(20) NOT NULL,
            transaction_type enum('credit','debit') NOT NULL,
            amount decimal(10,2) NOT NULL,
            balance_before decimal(10,2) NOT NULL DEFAULT 0.00,
            balance_after decimal(10,2) NOT NULL DEFAULT 0.00,
            description text,
            order_id bigint(20) DEFAULT NULL,
            payment_method varchar(50) DEFAULT NULL,
            transaction_id varchar(100) DEFAULT NULL,
            status enum('pending','completed','failed','cancelled') DEFAULT 'pending',
            created_at datetime DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            KEY user_id (user_id),
            KEY order_id (order_id)
        ) $charset_collate;";
        
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql1);
        dbDelta($sql2);
    }

    public function get_wallet_balance($user_id) {
        global $wpdb;
        
        $balance = $wpdb->get_var($wpdb->prepare(
            "SELECT balance FROM {$this->table_name} WHERE user_id = %d",
            $user_id
        ));
        
        return $balance ? floatval($balance) : 0.00;
    }

    public function update_wallet_balance($user_id, $amount, $type = 'credit', $description = '', $order_id = null, $payment_method = '', $transaction_id = '') {
        global $wpdb;
        
        $current_balance = $this->get_wallet_balance($user_id);
        
        if ($type === 'debit' && $current_balance < $amount) {
            return false; // Insufficient funds
        }
        
        $new_balance = ($type === 'credit') ? $current_balance + $amount : $current_balance - $amount;
        
        // Update or insert wallet balance
        $wpdb->replace(
            $this->table_name,
            array(
                'user_id' => $user_id,
                'balance' => $new_balance
            ),
            array('%d', '%f')
        );
        
        // Insert transaction record
        $wpdb->insert(
            $this->transactions_table,
            array(
                'user_id' => $user_id,
                'transaction_type' => $type,
                'amount' => $amount,
                'balance_before' => $current_balance,
                'balance_after' => $new_balance,
                'description' => $description,
                'order_id' => $order_id,
                'payment_method' => $payment_method,
                'transaction_id' => $transaction_id,
                'status' => 'completed'
            ),
            array('%d', '%s', '%f', '%f', '%f', '%s', '%d', '%s', '%s', '%s')
        );
        
        return $new_balance;
    }

    public function get_wallet_transactions($user_id, $limit = 20, $offset = 0) {
        global $wpdb;
        
        return $wpdb->get_results($wpdb->prepare(
            "SELECT * FROM {$this->transactions_table} 
             WHERE user_id = %d 
             ORDER BY created_at DESC 
             LIMIT %d OFFSET %d",
            $user_id, $limit, $offset
        ));
    }

    public function ajax_add_wallet_funds() {
        check_ajax_referer('kaveh_wallet_nonce', 'nonce');
        
        if (!is_user_logged_in()) {
            wp_die(json_encode(array('success' => false, 'message' => 'User not logged in')));
        }
        
        $amount = floatval($_POST['amount']);
        $payment_method = sanitize_text_field($_POST['payment_method']);
        
        if ($amount <= 0) {
            wp_die(json_encode(array('success' => false, 'message' => 'Invalid amount')));
        }
        
        $user_id = get_current_user_id();
        
        // Create a temporary order for payment processing
        $order = wc_create_order();
        $order->set_customer_id($user_id);
        $order->add_product(wc_get_product($this->get_or_create_wallet_product()), 1, array('total' => $amount));
        $order->set_total($amount);
        $order->update_meta_data('_is_wallet_topup', true);
        $order->update_meta_data('_wallet_topup_amount', $amount);
        $order->save();
        
        // Redirect to checkout with the order
        $checkout_url = $order->get_checkout_payment_url();
        
        wp_die(json_encode(array(
            'success' => true, 
            'redirect_url' => $checkout_url,
            'order_id' => $order->get_id()
        )));
    }

    private function get_or_create_wallet_product() {
        $product_id = get_option('kaveh_wallet_product_id');
        
        if (!$product_id || !get_post($product_id)) {
            // Create wallet top-up product
            $product = new WC_Product_Simple();
            $product->set_name('Wallet Top-up');
            $product->set_status('private');
            $product->set_catalog_visibility('hidden');
            $product->set_price(0);
            $product->set_virtual(true);
            $product->set_sold_individually(true);
            $product_id = $product->save();
            
            update_option('kaveh_wallet_product_id', $product_id);
        }
        
        return $product_id;
    }

    // Removed gateway methods - now using coupon-like system

    /**
     * Apply wallet discount during cart calculation
     */
    public function apply_wallet_discount() {
        if (is_admin() && !defined('DOING_AJAX')) return;
        if (!WC()->session) return;
        
        $use_wallet = WC()->session->get('use_wallet_payment');
        if (!$use_wallet) return;
        
        $user_id = get_current_user_id();
        if (!$user_id) return;
        
        $wallet_balance = $this->get_wallet_balance($user_id);
        if ($wallet_balance <= 0) return;
        
        $cart_total = WC()->cart->get_subtotal() + WC()->cart->get_shipping_total() + WC()->cart->get_taxes_total();
        $wallet_discount = min($wallet_balance, $cart_total);
        
        if ($wallet_discount > 0) {
            WC()->cart->add_fee(__('Wallet Credit', 'kavehTheme'), -$wallet_discount);
            WC()->session->set('wallet_discount_amount', $wallet_discount);
        }
    }
    
    /**
     * AJAX handler to apply/remove wallet discount
     */
    public function ajax_apply_wallet_discount() {
        check_ajax_referer('kaveh_wallet_nonce', 'nonce');
        
        $use_wallet = isset($_POST['use_wallet']) && $_POST['use_wallet'] === '1';
        
        if ($use_wallet) {
            WC()->session->set('use_wallet_payment', true);
        } else {
            WC()->session->set('use_wallet_payment', false);
            WC()->session->set('wallet_discount_amount', 0);
        }
        
        wp_send_json_success(array('use_wallet' => $use_wallet));
    }
    
    /**
     * Save wallet usage meta when order is placed
     */
    public function save_wallet_usage_meta($order_id) {
        $wallet_discount = WC()->session->get('wallet_discount_amount');
        if ($wallet_discount > 0) {
            update_post_meta($order_id, '_wallet_discount_amount', $wallet_discount);
            update_post_meta($order_id, '_wallet_payment_pending', 'yes');
        }
    }
    
    /**
     * Deduct wallet funds only after payment is complete
     */
    public function deduct_wallet_funds_on_payment_complete($order_id) {
        $this->process_wallet_deduction($order_id);
    }
    
    /**
     * Deduct wallet funds when order is completed (fallback)
     */
    public function deduct_wallet_funds_on_order_complete($order_id) {
        $this->process_wallet_deduction($order_id);
    }
    
    /**
     * Process the actual wallet deduction
     */
    private function process_wallet_deduction($order_id) {
        $wallet_discount = get_post_meta($order_id, '_wallet_discount_amount', true);
        $already_processed = get_post_meta($order_id, '_wallet_payment_processed', true);
        
        if (!$wallet_discount || $already_processed === 'yes') {
            return;
        }
        
        $order = wc_get_order($order_id);
        $user_id = $order->get_user_id();
        
        if (!$user_id) return;
        
        $current_balance = $this->get_wallet_balance($user_id);
        if ($wallet_discount > $current_balance) {
            $order->add_order_note(__('Warning: Insufficient wallet balance at payment time.', 'kavehTheme'));
            return;
        }
        
        // Deduct from wallet
        $this->deduct_wallet_balance($user_id, $wallet_discount);
        
        // Mark as processed
        update_post_meta($order_id, '_wallet_payment_processed', 'yes');
        update_post_meta($order_id, '_wallet_payment_used', 'yes');
        delete_post_meta($order_id, '_wallet_payment_pending');
        
        // Add order note
        $order->add_order_note(sprintf(__('Wallet payment: %s deducted from user wallet.', 'kavehTheme'), wc_price($wallet_discount)));
    }
    
    public function process_wallet_payment_on_checkout($order_id, $posted_data, $order) {
        if ($order->get_meta('_is_wallet_topup')) {
            // This is a wallet top-up order
            $amount = $order->get_meta('_wallet_topup_amount');
            $user_id = $order->get_customer_id();
            
            if ($order->is_paid()) {
                $this->update_wallet_balance(
                    $user_id, 
                    $amount, 
                    'credit', 
                    'Wallet top-up via ' . $order->get_payment_method_title(),
                    $order_id,
                    $order->get_payment_method(),
                    $order->get_transaction_id()
                );
            }
        }
    }

    public function display_wallet_balance_on_checkout() {
        if (!is_user_logged_in()) return;
        
        $user_id = get_current_user_id();
        $balance = $this->get_wallet_balance($user_id);
        
        if ($balance <= 0) return;
        
        $cart_total = WC()->cart->get_subtotal() + WC()->cart->get_shipping_total() + WC()->cart->get_taxes_total();
        $wallet_discount = min($balance, $cart_total);
        $use_wallet = WC()->session->get('use_wallet_payment');
        
        echo '<div class="wallet-checkout-info">';
        echo '<h4>' . __('Wallet Balance', 'kavehTheme') . '</h4>';
        echo '<p class="wallet-balance">' . __('Available Balance: ', 'kavehTheme') . wc_price($balance) . '</p>';
        
        echo '<div class="wallet-discount-option">';
        echo '<label><input type="checkbox" id="use_wallet_payment" name="use_wallet_payment" value="1"' . checked($use_wallet, true, false) . '> ' . __('Apply wallet credit to this order', 'kavehTheme') . '</label>';
        /* translators: %s: wallet amount that will be applied */
        echo '<p class="description">' . sprintf(__('Will apply: %s as discount', 'kavehTheme'), wc_price($wallet_discount)) . '</p>';
        echo '</div>';
        echo '</div>';
    }

    public function validate_wallet_payment() {
        if (isset($_POST['use_wallet_payment']) && $_POST['use_wallet_payment'] == '1') {
            $wallet_amount = floatval($_POST['wallet_payment_amount']);
            $user_id = get_current_user_id();
            $balance = $this->get_wallet_balance($user_id);
            
            if ($wallet_amount > $balance) {
                wc_add_notice(__('Insufficient wallet balance.', 'kavehTheme'), 'error');
            }
        }
    }

    // Admin functions
    public function add_wallet_fields_to_user_profile($user) {
        if (!current_user_can('manage_options')) return;
        
        $balance = $this->get_wallet_balance($user->ID);
        ?>
        <h3><?php _e('Wallet Management', 'kavehTheme'); ?></h3>
        <table class="form-table">
            <tr>
                <th><label for="wallet_balance"><?php _e('Current Wallet Balance', 'kavehTheme'); ?></label></th>
                <td>
                    <strong><?php echo wc_price($balance); ?></strong>
                </td>
            </tr>
            <tr>
                <th><label for="wallet_add_amount"><?php _e('Add/Deduct Amount', 'kavehTheme'); ?></label></th>
                <td>
                    <input type="number" name="wallet_add_amount" id="wallet_add_amount" step="0.01" class="regular-text" />
                    <p class="description"><?php _e('Enter positive amount to add, negative to deduct', 'kavehTheme'); ?></p>
                </td>
            </tr>
            <tr>
                <th><label for="wallet_description"><?php _e('Description', 'kavehTheme'); ?></label></th>
                <td>
                    <input type="text" name="wallet_description" id="wallet_description" class="regular-text" />
                    <p class="description"><?php _e('Reason for balance change', 'kavehTheme'); ?></p>
                </td>
            </tr>
        </table>
        <?php
    }

    public function save_wallet_fields($user_id) {
        if (!current_user_can('manage_options')) return;
        
        if (isset($_POST['wallet_add_amount']) && !empty($_POST['wallet_add_amount'])) {
            $amount = floatval($_POST['wallet_add_amount']);
            $description = sanitize_text_field($_POST['wallet_description']) ?: __('Admin adjustment', 'kavehTheme');
            
            if ($amount != 0) {
                $type = $amount > 0 ? 'credit' : 'debit';
                $amount = abs($amount);
                
                $this->update_wallet_balance($user_id, $amount, $type, $description, null, 'admin', 'admin_' . time());
            }
        }
    }

    // Shortcode functions are now handled by Kavehboardwalletshortcodes class
}