<?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 simple test handler
        add_action('wp_ajax_hvac_zoho_simple_test', array($this, 'simple_test'));
        // Add OAuth callback handler
        add_action('init', array($this, 'handle_oauth_callback'));
        add_action('init', array($this, 'add_oauth_rewrite_rule'));
        add_action('template_redirect', array($this, 'handle_oauth_template_redirect'));
        add_filter('query_vars', array($this, 'add_oauth_query_vars'));
    }
    
    /**
     * 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) {
        error_log('Admin script enqueue called for hook: ' . $hook);
        
        // Temporarily load on all admin pages to debug
        if (!is_admin()) {
            return;
        }
        
        error_log('Enqueuing Zoho admin scripts');
        
        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')
        ));
        
        // Add inline test script for debugging
        wp_add_inline_script('hvac-zoho-admin', '
            console.log("Zoho admin script loaded");
            jQuery(document).ready(function($) {
                console.log("DOM ready, setting up click handler");
                $(document).on("click", "#test-zoho-connection", function() {
                    console.log("Test button clicked - inline script");
                });
            });
        ');
        
        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;
        
        // Additional checks for staging domains
        $known_staging_domains = array(
            'upskill-staging.measurequick.com',
            'wordpress-974670-5399585.cloudwaysapps.com',
            'localhost',
            'staging',
            'test',
            'dev'
        );
        
        foreach ($known_staging_domains as $domain) {
            if (strpos($site_url, $domain) !== false) {
                $is_staging = true;
                break;
            }
        }
        ?>
        <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>
                    <p><strong>OAuth Redirect URI:</strong> <?php echo defined('ZOHO_REDIRECT_URI') ? esc_html(ZOHO_REDIRECT_URI) : 'Not defined'; ?></p>
                    <p><em>If you're having connection issues, please ensure your Zoho OAuth settings match this redirect URI.</em></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>
                    
                    <?php
                    // Check for OAuth authorization requirement
                    if (file_exists($config_file)) {
                        require_once $config_file;
                    }
                    $stored_refresh_token = get_option('hvac_zoho_refresh_token');
                    $has_credentials = defined('ZOHO_CLIENT_ID') && !empty(ZOHO_CLIENT_ID) && defined('ZOHO_CLIENT_SECRET') && !empty(ZOHO_CLIENT_SECRET);
                    
                    if ($has_credentials && empty($stored_refresh_token)):
                        // Show OAuth authorization directly
                        require_once HVAC_CE_PLUGIN_DIR . 'includes/zoho/class-zoho-crm-auth.php';
                        $auth = new HVAC_Zoho_CRM_Auth();
                        $auth_url = $auth->get_authorization_url();
                    ?>
                        <div class="notice notice-warning">
                            <h3>🔐 OAuth Authorization Required</h3>
                            <p><strong>You have valid credentials but need to complete OAuth authorization to get a fresh token</strong></p>
                            <ol>
                                <li>Click the authorization URL below</li>
                                <li>Sign in to your Zoho account</li>
                                <li>Grant permissions to the application</li>
                                <li>You will be redirected back and the refresh token will be saved automatically</li>
                            </ol>
                            <p>
                                <a href="<?php echo esc_url($auth_url); ?>" target="_blank" class="button button-primary" style="margin: 10px 0;">
                                    🚀 Authorize with Zoho CRM
                                </a>
                            </p>
                            <p><strong>Current Status:</strong></p>
                            <ul>
                                <li>Client ID: <?php echo esc_html(substr(ZOHO_CLIENT_ID, 0, 10) . '...'); ?></li>
                                <li>Client Secret: ✓ Loaded</li>
                                <li>Refresh Token: ❌ Missing</li>
                            </ul>
                            <p><em>After authorization, refresh this page and test the connection.</em></p>
                        </div>
                    <?php else: ?>
                        <button class="button button-primary" id="test-connection">Test Connection</button>
                        <div id="connection-status"></div>
                    <?php endif; ?>
                </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
    }
    
    /**
     * Simple test handler to isolate issues
     */
    public function simple_test() {
        error_log('Simple test AJAX handler called');
        wp_send_json_success(array('message' => 'Simple test works!'));
    }
    
    /**
     * Add OAuth query vars
     */
    public function add_oauth_query_vars($vars) {
        $vars[] = 'hvac_oauth_callback';
        return $vars;
    }
    
    /**
     * Add OAuth callback rewrite rule
     */
    public function add_oauth_rewrite_rule() {
        add_rewrite_rule('^oauth/callback/?$', 'index.php?hvac_oauth_callback=1', 'top');
    }
    
    /**
     * Handle OAuth template redirect
     */
    public function handle_oauth_template_redirect() {
        if (get_query_var('hvac_oauth_callback')) {
            $this->process_oauth_callback();
        }
    }
    
    /**
     * Process OAuth callback from Zoho
     */
    public function process_oauth_callback() {
        if (!isset($_GET['code'])) {
            wp_die('OAuth callback missing authorization code');
        }
        
        error_log('OAuth callback received with code: ' . substr($_GET['code'], 0, 20) . '...');
        
        // Load Zoho configuration
        $config_file = HVAC_CE_PLUGIN_DIR . 'includes/zoho/zoho-config.php';
        if (file_exists($config_file)) {
            require_once $config_file;
        }
        
        require_once HVAC_CE_PLUGIN_DIR . 'includes/zoho/class-zoho-crm-auth.php';
        $auth = new HVAC_Zoho_CRM_Auth();
        
        // Exchange code for refresh token
        $result = $auth->exchange_code_for_tokens($_GET['code']);
        
        if ($result) {
            // Success - redirect to admin page with success message
            wp_redirect(admin_url('admin.php?page=hvac-zoho-sync&oauth=success'));
            exit;
        } else {
            // Error - redirect with error message
            wp_redirect(admin_url('admin.php?page=hvac-zoho-sync&oauth=error'));
            exit;
        }
    }
    
    /**
     * Handle OAuth callback from Zoho (legacy method)
     */
    public function handle_oauth_callback() {
        // This method is kept for backwards compatibility
        // The main handling is now done in template_redirect
        return;
    }
    
    /**
     * Test Zoho connection
     */
    public function test_connection() {
        error_log('test_connection method called');
        
        try {
            // Skip nonce check for now to debug
            // check_ajax_referer('hvac_zoho_nonce', 'nonce');
            
            if (!current_user_can('manage_options')) {
                wp_send_json_error(array('message' => 'Unauthorized access'));
                return;
            }
            
            error_log('Authorization check passed');
            
            // Load Zoho configuration
            $config_file = HVAC_CE_PLUGIN_DIR . 'includes/zoho/zoho-config.php';
            if (file_exists($config_file)) {
                require_once $config_file;
                error_log('Zoho config loaded');
            } else {
                error_log('Zoho config file not found: ' . $config_file);
            }
            
            // Simple .env loading first
            $env_file = ABSPATH . '.env';
            $debug_info = array(
                'env_file_exists' => file_exists($env_file),
                'env_file_path' => $env_file,
                'abspath' => ABSPATH
            );
            
            if (file_exists($env_file)) {
                $content = file_get_contents($env_file);
                if (preg_match('/ZOHO_CLIENT_ID=([^\r\n]+)/', $content, $matches)) {
                    if (!defined('ZOHO_CLIENT_ID')) {
                        define('ZOHO_CLIENT_ID', trim($matches[1]));
                    }
                    $debug_info['client_id_found'] = 'Yes';
                }
                if (preg_match('/ZOHO_CLIENT_SECRET=([^\r\n]+)/', $content, $matches)) {
                    if (!defined('ZOHO_CLIENT_SECRET')) {
                        define('ZOHO_CLIENT_SECRET', trim($matches[1]));
                    }
                    $debug_info['client_secret_found'] = 'Yes';
                }
                if (preg_match('/ZOHO_REFRESH_TOKEN=([^\r\n]+)/', $content, $matches)) {
                    if (!defined('ZOHO_REFRESH_TOKEN')) {
                        define('ZOHO_REFRESH_TOKEN', trim($matches[1]));
                    }
                    $debug_info['refresh_token_found'] = 'Yes';
                }
            }

            // Check configuration before attempting connection
            if (!defined('ZOHO_CLIENT_ID') || empty(ZOHO_CLIENT_ID)) {
                wp_send_json_error(array(
                    'message' => 'Configuration Error',
                    'error' => 'ZOHO_CLIENT_ID is not configured',
                    'details' => 'Please check your .env file and ensure ZOHO_CLIENT_ID is set',
                    'help' => 'Add ZOHO_CLIENT_ID=your_client_id to your .env file',
                    'debug' => $debug_info
                ));
                return;
            }
            
            if (!defined('ZOHO_CLIENT_SECRET') || empty(ZOHO_CLIENT_SECRET)) {
                wp_send_json_error(array(
                    'message' => 'Configuration Error',
                    'error' => 'ZOHO_CLIENT_SECRET is not configured',
                    'details' => 'Please check your .env file and ensure ZOHO_CLIENT_SECRET is set',
                    'help' => 'Add ZOHO_CLIENT_SECRET=your_client_secret to your .env file'
                ));
                return;
            }
            
            // Check if we have stored refresh token from previous OAuth
            $stored_refresh_token = get_option('hvac_zoho_refresh_token');
            $env_refresh_token = defined('ZOHO_REFRESH_TOKEN') ? ZOHO_REFRESH_TOKEN : '';
            
            // If no stored refresh token, trigger OAuth even if env token exists
            // (env tokens are often old/expired)
            if (empty($stored_refresh_token)) {
                error_log('No stored refresh token found, triggering OAuth authorization');
                
                require_once HVAC_CE_PLUGIN_DIR . 'includes/zoho/class-zoho-crm-auth.php';
                $auth = new HVAC_Zoho_CRM_Auth();
                $auth_url = $auth->get_authorization_url();
                
                wp_send_json_error(array(
                    'message' => 'OAuth Authorization Required',
                    'error' => 'No stored refresh token found',
                    'details' => 'You have valid credentials but need to complete OAuth authorization to get a fresh token',
                    'help' => 'Click the authorization link below to complete setup',
                    'next_steps' => array(
                        '1. Click the authorization URL below',
                        '2. Sign in to your Zoho account', 
                        '3. Grant permissions to the application',
                        '4. You will be redirected back and the refresh token will be saved automatically'
                    ),
                    'auth_url' => $auth_url,
                    'credentials_status' => array(
                        'client_id' => substr(ZOHO_CLIENT_ID, 0, 10) . '...',
                        'client_secret_exists' => true,
                        'refresh_token_exists' => false,
                        'env_token_found' => !empty($env_refresh_token)
                    )
                ));
                return;
            }
            
            // We have a refresh token - test the actual API connection
            require_once HVAC_CE_PLUGIN_DIR . 'includes/zoho/class-zoho-crm-auth.php';
            $auth = new HVAC_Zoho_CRM_Auth();
            
            error_log('Testing API with refresh token: ' . substr($env_refresh_token ?: $stored_refresh_token, 0, 10) . '...');
            
            // Test API call
            $response = $auth->make_api_request('/settings/modules', 'GET');
            
            if (is_wp_error($response)) {
                error_log('WordPress HTTP error: ' . $response->get_error_message());
                wp_send_json_error(array(
                    'message' => 'API Connection Failed',
                    'error' => $response->get_error_message(),
                    'details' => 'WordPress HTTP error occurred'
                ));
                return;
            }
            
            error_log('API response: ' . json_encode($response));
            
            if (isset($response['error'])) {
                error_log('Zoho API error: ' . $response['error']);
                
                // Check if it's an invalid token error
                if (strpos($response['error'], 'invalid') !== false || strpos($response['error'], 'expired') !== false) {
                    error_log('Token appears invalid/expired, triggering OAuth flow');
                    // Clear the invalid token and trigger OAuth
                    delete_option('hvac_zoho_refresh_token');
                    
                    $auth_url = $auth->get_authorization_url();
                    wp_send_json_error(array(
                        'message' => 'OAuth Authorization Required',
                        'error' => 'Refresh token expired or invalid',
                        'details' => 'The stored refresh token is no longer valid. Please re-authorize.',
                        'help' => 'Click the authorization link below to complete setup',
                        'next_steps' => array(
                            '1. Click the authorization URL below',
                            '2. Sign in to your Zoho account', 
                            '3. Grant permissions to the application',
                            '4. You will be redirected back and the refresh token will be saved automatically'
                        ),
                        'auth_url' => $auth_url,
                        'credentials_status' => array(
                            'client_id' => substr(ZOHO_CLIENT_ID, 0, 10) . '...',
                            'client_secret_exists' => true,
                            'refresh_token_exists' => false
                        )
                    ));
                    return;
                }
                
                wp_send_json_error(array(
                    'message' => 'Zoho API Error', 
                    'error' => $response['error'],
                    'details' => isset($response['details']) ? $response['details'] : 'No additional details'
                ));
                return;
            }
            
            // Success!
            wp_send_json_success(array(
                'message' => 'Connection successful!',
                'modules' => isset($response['modules']) ? count($response['modules']) . ' modules available' : 'API connected',
                'credentials_status' => array(
                    'client_id' => substr(ZOHO_CLIENT_ID, 0, 10) . '...',
                    'client_secret_exists' => true,
                    'refresh_token_exists' => true,
                    'api_working' => true
                )
            ));
        } catch (Exception $e) {
            error_log('Exception in test_connection: ' . $e->getMessage() . ' in ' . $e->getFile() . ':' . $e->getLine());
            wp_send_json_error(array(
                'message' => 'Connection test failed due to exception',
                'error' => $e->getMessage(),
                'file' => $e->getFile() . ':' . $e->getLine()
            ));
        } catch (Error $e) {
            error_log('PHP Error in test_connection: ' . $e->getMessage() . ' in ' . $e->getFile() . ':' . $e->getLine());
            wp_send_json_error(array(
                'message' => 'Connection test failed due to PHP error',
                'error' => $e->getMessage(),
                'file' => $e->getFile() . ':' . $e->getLine()
            ));
        } catch (Throwable $e) {
            error_log('Fatal error in test_connection: ' . $e->getMessage() . ' in ' . $e->getFile() . ':' . $e->getLine());
            wp_send_json_error(array(
                'message' => 'Connection test failed due to fatal error',
                'error' => $e->getMessage(),
                'file' => $e->getFile() . ':' . $e->getLine()
            ));
        }
    }
    
    /**
     * 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()
            ));
        }
    }
}
?>