<?php
/**
 * Zoho CRM Admin Interface
 * 
 * Provides WordPress admin interface for Zoho credential management
 */

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

class HVAC_Zoho_Admin {
    
    public function __construct() {
        add_action('admin_menu', array($this, 'add_admin_menu'));
        add_action('admin_init', array($this, 'handle_auth_callback'));
    }
    
    /**
     * Add menu item to WordPress admin
     */
    public function add_admin_menu() {
        add_submenu_page(
            'edit.php?post_type=tribe_events',
            'Zoho CRM Integration',
            'Zoho CRM',
            'manage_options',
            'hvac-zoho-crm',
            array($this, 'admin_page')
        );
    }
    
    /**
     * Handle OAuth callback
     */
    public function handle_auth_callback() {
        if (isset($_GET['page']) && $_GET['page'] === 'hvac-zoho-crm' && isset($_GET['code'])) {
            $auth = new HVAC_Zoho_CRM_Auth();
            
            if ($auth->exchange_code_for_tokens($_GET['code'])) {
                add_settings_error(
                    'hvac_zoho_messages',
                    'hvac_zoho_auth_success',
                    'Successfully connected to Zoho CRM!',
                    'success'
                );
            } else {
                add_settings_error(
                    'hvac_zoho_messages',
                    'hvac_zoho_auth_error',
                    'Failed to connect to Zoho CRM. Please check your credentials.',
                    'error'
                );
            }
            
            // Redirect to remove code from URL
            wp_redirect(admin_url('edit.php?post_type=tribe_events&page=hvac-zoho-crm'));
            exit;
        }
    }
    
    /**
     * Display admin page
     */
    public function admin_page() {
        ?>
        <div class="wrap">
            <h1>Zoho CRM Integration</h1>
            
            <?php settings_errors('hvac_zoho_messages'); ?>
            
            <?php
            // Check if config file exists
            $config_file = plugin_dir_path(dirname(__FILE__)) . 'zoho/zoho-config.php';
            $config_exists = file_exists($config_file);
            
            if (!$config_exists):
            ?>
                <div class="notice notice-warning">
                    <p>Zoho CRM configuration file not found. Please follow the setup instructions below.</p>
                </div>
                
                <h2>Setup Instructions</h2>
                <ol>
                    <li>
                        <strong>Register your application in Zoho:</strong>
                        <a href="https://api-console.zoho.com/" target="_blank">Go to Zoho API Console</a>
                    </li>
                    <li>Create a new Server-based Application</li>
                    <li>Set redirect URI to: <code><?php echo admin_url('edit.php?post_type=tribe_events&page=hvac-zoho-crm'); ?></code></li>
                    <li>Copy your Client ID and Client Secret</li>
                    <li>Run the setup helper script from command line:
                        <pre>cd <?php echo plugin_dir_path(dirname(__FILE__)); ?>zoho
php setup-helper.php</pre>
                    </li>
                </ol>
                
            <?php else: ?>
                
                <?php
                // Load configuration
                require_once $config_file;
                $auth = new HVAC_Zoho_CRM_Auth();
                
                // Test connection
                $org_info = $auth->make_api_request('/crm/v2/org');
                $connected = !is_wp_error($org_info) && isset($org_info['org']);
                ?>
                
                <?php if ($connected): ?>
                    <div class="notice notice-success">
                        <p>✓ Connected to Zoho CRM</p>
                    </div>
                    
                    <h2>Organization Information</h2>
                    <table class="form-table">
                        <tr>
                            <th>Organization Name</th>
                            <td><?php echo esc_html($org_info['org'][0]['company_name']); ?></td>
                        </tr>
                        <tr>
                            <th>Organization ID</th>
                            <td><?php echo esc_html($org_info['org'][0]['id']); ?></td>
                        </tr>
                        <tr>
                            <th>Time Zone</th>
                            <td><?php echo esc_html($org_info['org'][0]['time_zone']); ?></td>
                        </tr>
                    </table>
                    
                    <h2>Integration Status</h2>
                    <?php $this->display_integration_status(); ?>
                    
                    <h2>Actions</h2>
                    <p>
                        <a href="<?php echo wp_nonce_url(admin_url('edit.php?post_type=tribe_events&page=hvac-zoho-crm&action=test_sync'), 'test_sync'); ?>" 
                           class="button button-primary">Test Sync</a>
                        <a href="<?php echo wp_nonce_url(admin_url('edit.php?post_type=tribe_events&page=hvac-zoho-crm&action=create_fields'), 'create_fields'); ?>" 
                           class="button">Create Custom Fields</a>
                    </p>
                    
                <?php else: ?>
                    <div class="notice notice-error">
                        <p>✗ Not connected to Zoho CRM</p>
                    </div>
                    
                    <h2>Reconnect to Zoho</h2>
                    <p>Click the button below to authorize this application with Zoho CRM:</p>
                    <p>
                        <a href="<?php echo esc_url($auth->get_authorization_url()); ?>" 
                           class="button button-primary">Connect to Zoho CRM</a>
                    </p>
                <?php endif; ?>
                
            <?php endif; ?>
        </div>
        <?php
    }
    
    /**
     * Display integration status
     */
    private function display_integration_status() {
        ?>
        <table class="widefat striped">
            <thead>
                <tr>
                    <th>Module</th>
                    <th>Fields Configured</th>
                    <th>Last Sync</th>
                    <th>Status</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>Campaigns (Events)</td>
                    <td><?php echo $this->check_custom_fields('Campaigns'); ?></td>
                    <td><?php echo get_option('hvac_zoho_last_campaign_sync', 'Never'); ?></td>
                    <td><span class="dashicons dashicons-yes-alt" style="color: green;"></span></td>
                </tr>
                <tr>
                    <td>Contacts (Users)</td>
                    <td><?php echo $this->check_custom_fields('Contacts'); ?></td>
                    <td><?php echo get_option('hvac_zoho_last_contact_sync', 'Never'); ?></td>
                    <td><span class="dashicons dashicons-yes-alt" style="color: green;"></span></td>
                </tr>
                <tr>
                    <td>Invoices (Orders)</td>
                    <td><?php echo $this->check_custom_fields('Invoices'); ?></td>
                    <td><?php echo get_option('hvac_zoho_last_invoice_sync', 'Never'); ?></td>
                    <td><span class="dashicons dashicons-yes-alt" style="color: green;"></span></td>
                </tr>
            </tbody>
        </table>
        <?php
    }
    
    /**
     * Check if custom fields exist
     */
    private function check_custom_fields($module) {
        // This would actually check via API if the custom fields exist
        // For now, return a placeholder
        return '<span style="color: orange;">Pending</span>';
    }
}

// Initialize admin interface
if (is_admin()) {
    new HVAC_Zoho_Admin();
}