<?php
/**
 * M2C Admin Settings
 * Additional admin functionality and settings pages
 */

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

class M2C_Admin_Settings {
    
    private $api;
    
    public function __construct() {
        $this->api = new M2C_API_Client();
        
        // Add admin menu
        add_action('admin_menu', array($this, 'add_admin_menu'));
        
        // Register AJAX handlers
        add_action('wp_ajax_m2c_test_connection', array($this, 'ajax_test_connection'));
        add_action('wp_ajax_m2c_check_status', array($this, 'ajax_check_status'));
    }
    
    /**
     * Add admin menu items
     */
    public function add_admin_menu() {
        add_submenu_page(
            'woocommerce',
            __('AB2BC Transactions', 'ab2bc-red-envelope'),
            __('AB2BC Transactions', 'ab2bc-red-envelope'),
            'manage_woocommerce',
            'm2c-transactions',
            array($this, 'transactions_page')
        );
    }
    
    /**
     * Transactions admin page
     */
    public function transactions_page() {
        global $wpdb;
        $table_name = $wpdb->prefix . 'm2c_transactions';
        
        // Get transactions
        $transactions = $wpdb->get_results(
            "SELECT * FROM $table_name ORDER BY created_at DESC LIMIT 100",
            ARRAY_A
        );
        
        include MRE_PLUGIN_DIR . 'templates/admin-transactions.php';
    }
    
    /**
     * AJAX: Test API connection
     */
    public function ajax_test_connection() {
        check_ajax_referer('m2c_red_envelope_nonce', 'nonce');
        
        if (!current_user_can('manage_woocommerce')) {
            wp_send_json_error(array('message' => 'Unauthorized'));
            return;
        }
        
        $results = $this->api->test_connection();
        
        if ($results['m2c_backend'] && $results['genesis_api']) {
            wp_send_json_success($results);
        } else {
            wp_send_json_error(array(
                'message' => 'Connection failed',
                'results' => $results
            ));
        }
    }
    
    /**
     * AJAX: Check connection status
     */
    public function ajax_check_status() {
        check_ajax_referer('m2c_red_envelope_nonce', 'nonce');
        
        if (!current_user_can('manage_woocommerce')) {
            wp_send_json_error(array('message' => 'Unauthorized'));
            return;
        }
        
        $results = $this->api->test_connection();
        wp_send_json_success($results);
    }
}

// Initialize only if not already done
if (!isset($GLOBALS['m2c_admin_settings'])) {
    $GLOBALS['m2c_admin_settings'] = new M2C_Admin_Settings();
}
