<?php
/**
 * Zoho CRM Admin Interface
 *
 * @package HVACCommunityEvents
 */

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

/**
 * Zoho CRM Admin Class
 */
class HVAC_Zoho_Admin {
    
    /**
     * Initialize the admin interface
     */
    public function __construct() {
        add_action('admin_menu', array($this, 'add_admin_menu'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts'));
        add_action('wp_ajax_hvac_zoho_test_connection', array($this, 'test_connection'));
        add_action('wp_ajax_hvac_zoho_sync_data', array($this, 'sync_data'));
    }
    
    /**
     * Add admin menu
     */
    public function add_admin_menu() {
        add_submenu_page(
            'hvac-community-events',
            'Zoho CRM Sync',
            'Zoho CRM Sync',
            'manage_options',
            'hvac-zoho-sync',
            array($this, 'render_admin_page')
        );
    }
    
    /**
     * Enqueue admin scripts
     */
    public function enqueue_admin_scripts($hook) {
        if ($hook !== 'hvac-community-events_page_hvac-zoho-sync') {
            return;
        }
        
        wp_enqueue_script(
            'hvac-zoho-admin',
            HVAC_CE_PLUGIN_URL . 'assets/js/zoho-admin.js',
            array('jquery'),
            HVAC_CE_VERSION,
            true
        );
        
        wp_localize_script('hvac-zoho-admin', 'hvacZoho', array(
            'ajaxUrl' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('hvac_zoho_nonce')
        ));
        
        wp_enqueue_style(
            'hvac-zoho-admin',
            HVAC_CE_PLUGIN_URL . 'assets/css/zoho-admin.css',
            array(),
            HVAC_CE_VERSION
        );
    }
    
    /**
     * Render admin page
     */
    public function render_admin_page() {
        $config_file = HVAC_CE_PLUGIN_DIR . 'includes/zoho/zoho-config.php';
        $is_configured = file_exists($config_file);
        $site_url = get_site_url();
        $is_staging = strpos($site_url, 'upskillhvac.com') === false;
        ?>
        <div class="wrap">
            <h1>Zoho CRM Sync</h1>
            
            <?php if ($is_staging): ?>
                <div class="notice notice-info">
                    <h3>🔧 STAGING MODE ACTIVE</h3>
                    <p><strong>Current site:</strong> <?php echo esc_html($site_url); ?></p>
                    <p>Staging mode is active. Data sync will be simulated only. No actual data will be sent to Zoho CRM.</p>
                    <p>Production sync is only enabled on <strong>upskillhvac.com</strong></p>
                </div>
            <?php endif; ?>
            
            <?php if (!$is_configured): ?>
                <div class="notice notice-warning">
                    <p>Zoho CRM is not configured. Please complete the OAuth setup first.</p>
                    <p>Run: <code>./bin/zoho-setup-complete.sh</code></p>
                </div>
            <?php else: ?>
                <div class="hvac-zoho-status">
                    <h2>Connection Status</h2>
                    <button class="button button-primary" id="test-connection">Test Connection</button>
                    <div id="connection-status"></div>
                </div>
                
                <div class="hvac-zoho-sync">
                    <h2>Data Sync</h2>
                    
                    <div class="sync-section">
                        <h3>Events → Campaigns</h3>
                        <p>Sync events from The Events Calendar to Zoho CRM Campaigns</p>
                        <button class="button sync-button" data-type="events">Sync Events</button>
                        <div class="sync-status" id="events-status"></div>
                    </div>
                    
                    <div class="sync-section">
                        <h3>Users → Contacts</h3>
                        <p>Sync trainers and attendees to Zoho CRM Contacts</p>
                        <button class="button sync-button" data-type="users">Sync Users</button>
                        <div class="sync-status" id="users-status"></div>
                    </div>
                    
                    <div class="sync-section">
                        <h3>Purchases → Invoices</h3>
                        <p>Sync ticket purchases to Zoho CRM Invoices</p>
                        <button class="button sync-button" data-type="purchases">Sync Purchases</button>
                        <div class="sync-status" id="purchases-status"></div>
                    </div>
                </div>
                
                <div class="hvac-zoho-settings">
                    <h2>Sync Settings</h2>
                    <form id="zoho-settings-form">
                        <label>
                            <input type="checkbox" name="auto_sync" value="1" <?php checked(get_option('hvac_zoho_auto_sync'), '1'); ?>>
                            Enable automatic sync
                        </label>
                        <br><br>
                        <label>
                            Sync frequency:
                            <select name="sync_frequency">
                                <option value="hourly" <?php selected(get_option('hvac_zoho_sync_frequency'), 'hourly'); ?>>Hourly</option>
                                <option value="daily" <?php selected(get_option('hvac_zoho_sync_frequency'), 'daily'); ?>>Daily</option>
                                <option value="weekly" <?php selected(get_option('hvac_zoho_sync_frequency'), 'weekly'); ?>>Weekly</option>
                            </select>
                        </label>
                        <br><br>
                        <button type="submit" class="button button-primary">Save Settings</button>
                    </form>
                </div>
            <?php endif; ?>
        </div>
        <?php
    }
    
    /**
     * Test Zoho connection
     */
    public function test_connection() {
        check_ajax_referer('hvac_zoho_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_die('Unauthorized');
        }
        
        try {
            require_once HVAC_CE_PLUGIN_DIR . 'includes/zoho/class-zoho-crm-auth.php';
            $auth = new HVAC_Zoho_CRM_Auth();
            
            // Test API call
            $response = $auth->make_api_request('/settings/modules', 'GET');
            
            if ($response && !isset($response['error'])) {
                wp_send_json_success(array(
                    'message' => 'Connection successful!',
                    'modules' => count($response['modules']) . ' modules available'
                ));
            } else {
                wp_send_json_error(array(
                    'message' => 'Connection failed',
                    'error' => isset($response['error']) ? $response['error'] : 'Unknown error'
                ));
            }
        } catch (Exception $e) {
            wp_send_json_error(array(
                'message' => 'Connection failed',
                'error' => $e->getMessage()
            ));
        }
    }
    
    /**
     * Sync data to Zoho
     */
    public function sync_data() {
        check_ajax_referer('hvac_zoho_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_die('Unauthorized');
        }
        
        $type = sanitize_text_field($_POST['type']);
        
        try {
            require_once HVAC_CE_PLUGIN_DIR . 'includes/zoho/class-zoho-sync.php';
            $sync = new HVAC_Zoho_Sync();
            
            switch ($type) {
                case 'events':
                    $result = $sync->sync_events();
                    break;
                case 'users':
                    $result = $sync->sync_users();
                    break;
                case 'purchases':
                    $result = $sync->sync_purchases();
                    break;
                default:
                    throw new Exception('Invalid sync type');
            }
            
            wp_send_json_success($result);
        } catch (Exception $e) {
            wp_send_json_error(array(
                'message' => 'Sync failed',
                'error' => $e->getMessage()
            ));
        }
    }
}
?>