<?php
/**
 * Google Sheets Admin Interface
 *
 * Provides admin interface for Google Sheets integration
 *
 * @package HVAC_Community_Events
 * @subpackage Google_Sheets_Integration
 */

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

require_once plugin_dir_path(__FILE__) . 'class-google-sheets-auth.php';
require_once plugin_dir_path(__FILE__) . 'class-google-sheets-manager.php';

class HVAC_Google_Sheets_Admin {
    
    private $auth;
    private $manager;
    
    public function __construct() {
        $this->auth = new HVAC_Google_Sheets_Auth();
        $this->manager = new HVAC_Google_Sheets_Manager();
        
        add_action('wp_ajax_hvac_create_master_report', array($this, 'ajax_create_master_report'));
        add_action('wp_ajax_hvac_create_event_spreadsheet', array($this, 'ajax_create_event_spreadsheet'));
        add_action('wp_ajax_hvac_test_google_sheets_connection', array($this, 'ajax_test_connection'));
        add_action('wp_ajax_hvac_verify_folder_structure', array($this, 'ajax_verify_folder_structure'));
    }
    
    /**
     * Render Google Sheets admin page
     */
    public function render_admin_page() {
        try {
            // Initialize with safe defaults
            $auth_status = array(
                'has_credentials' => false,
                'is_authenticated' => false,
                'client_id' => 'Not configured',
                'token_expires' => 'N/A'
            );
            
            // Try to get auth status
            if ($this->auth) {
                $auth_status = $this->auth->get_config_status();
            }
            
            // Initialize report variables
            $latest_report = null;
            $report_history = array();
            
            // Try to get reports if manager is available
            if ($this->manager) {
                $latest_report = $this->manager->get_latest_master_report();
                $report_history = $this->manager->get_master_report_history();
            }
        
        ?>
        <div class="hvac-google-sheets-admin">
            <div class="hvac-container">
                <div class="hvac-header">
                    <h1><i class="hvac-icon-sheets"></i>Google Sheets Integration</h1>
                    <div class="hvac-header-actions">
                        <a href="<?php echo home_url('/master-trainer/dashboard/'); ?>" class="hvac-btn hvac-btn-secondary">
                            <i class="hvac-icon-arrow-left"></i> Back to Master Dashboard
                        </a>
                    </div>
                </div>
                
                <!-- Success/Error Messages -->
                <?php if (isset($_GET['auth_success']) && $_GET['auth_success'] == '1'): ?>
                <div class="hvac-alert hvac-alert-success">
                    <i class="hvac-icon-check"></i>
                    <strong>Success!</strong> Google Sheets authorization completed successfully! You can now create reports.
                </div>
                <?php endif; ?>
                
                <?php if (isset($_GET['auth_error']) && $_GET['auth_error'] == '1'): ?>
                <div class="hvac-alert hvac-alert-error">
                    <i class="hvac-icon-warning"></i>
                    <strong>Error:</strong> <?php echo esc_html($_GET['message'] ?? 'Failed to complete Google Sheets authorization.'); ?>
                </div>
                <?php endif; ?>
                
                <!-- Connection Status -->
                <div class="hvac-card">
                    <div class="hvac-card-header">
                        <h2><i class="hvac-icon-connection"></i>Connection Status</h2>
                    </div>
                    <div class="hvac-card-body">
                        <div class="hvac-status-grid">
                            <div class="hvac-status-item">
                                <span class="hvac-status-label">Credentials:</span>
                                <span class="hvac-status-value <?php echo $auth_status['has_credentials'] ? 'success' : 'error'; ?>">
                                    <?php echo $auth_status['has_credentials'] ? '✓ Configured' : '✗ Missing'; ?>
                                </span>
                            </div>
                            <div class="hvac-status-item">
                                <span class="hvac-status-label">Authentication:</span>
                                <span class="hvac-status-value <?php echo $auth_status['is_authenticated'] ? 'success' : 'error'; ?>">
                                    <?php echo $auth_status['is_authenticated'] ? '✓ Connected' : '✗ Not Connected'; ?>
                                </span>
                            </div>
                            <div class="hvac-status-item">
                                <span class="hvac-status-label">Client ID:</span>
                                <span class="hvac-status-value"><?php echo esc_html($auth_status['client_id']); ?></span>
                            </div>
                            <div class="hvac-status-item">
                                <span class="hvac-status-label">Token Expires:</span>
                                <span class="hvac-status-value"><?php echo esc_html($auth_status['token_expires']); ?></span>
                            </div>
                        </div>
                        
                        <div class="hvac-actions">
                            <button id="test-connection" class="hvac-btn hvac-btn-primary">
                                <i class="hvac-icon-test"></i> Test Connection
                            </button>
                            <button id="verify-folders" class="hvac-btn hvac-btn-secondary"
                                    <?php echo !$auth_status['is_authenticated'] ? 'disabled' : ''; ?>>
                                <i class="hvac-icon-folder"></i> Verify Folders
                            </button>
                            <?php if (!$auth_status['is_authenticated']): ?>
                            <a href="<?php echo esc_url($this->auth->get_authorization_url()); ?>" 
                               class="hvac-btn hvac-btn-secondary" target="_blank">
                                <i class="hvac-icon-auth"></i> Authorize Access
                            </a>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                
                <!-- Master Report Section -->
                <div class="hvac-card">
                    <div class="hvac-card-header">
                        <h2><i class="hvac-icon-report"></i>Master Report</h2>
                    </div>
                    <div class="hvac-card-body">
                        <p>Generate a comprehensive report with system overview, trainer performance, all events, and revenue analytics.</p>
                        
                        <?php if ($latest_report): ?>
                        <div class="hvac-latest-report">
                            <h3>Latest Report</h3>
                            <div class="hvac-report-info">
                                <div class="hvac-report-meta">
                                    <span class="hvac-report-date">
                                        <i class="hvac-icon-calendar"></i>
                                        <?php echo date('M j, Y g:i A', strtotime($latest_report['created_at'])); ?>
                                    </span>
                                    <a href="<?php echo esc_url($latest_report['url']); ?>" 
                                       target="_blank" class="hvac-btn hvac-btn-primary hvac-btn-sm">
                                        <i class="hvac-icon-external"></i> Open Spreadsheet
                                    </a>
                                </div>
                            </div>
                        </div>
                        <?php endif; ?>
                        
                        <div class="hvac-actions">
                            <button id="create-master-report" class="hvac-btn hvac-btn-primary"
                                    <?php echo !$auth_status['is_authenticated'] ? 'disabled' : ''; ?>>
                                <i class="hvac-icon-create"></i> Generate New Master Report
                            </button>
                        </div>
                    </div>
                </div>
                
                <!-- Event Spreadsheets Section -->
                <div class="hvac-card">
                    <div class="hvac-card-header">
                        <h2><i class="hvac-icon-events"></i>Event Spreadsheets</h2>
                    </div>
                    <div class="hvac-card-body">
                        <p>Create detailed spreadsheets for individual events with attendees, financial data, and event details.</p>
                        
                        <div class="hvac-event-selection">
                            <label for="event-select">Select Event:</label>
                            <select id="event-select" class="hvac-select">
                                <option value="">Choose an event...</option>
                                <?php $this->render_event_options(); ?>
                            </select>
                            <button id="create-event-spreadsheet" class="hvac-btn hvac-btn-primary"
                                    <?php echo !$auth_status['is_authenticated'] ? 'disabled' : ''; ?>>
                                <i class="hvac-icon-create"></i> Create Event Spreadsheet
                            </button>
                        </div>
                        
                        <div id="existing-event-sheets">
                            <h3>Existing Event Spreadsheets</h3>
                            <div class="hvac-event-sheets-list">
                                <?php $this->render_existing_event_sheets(); ?>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Report History -->
                <?php if (!empty($report_history)): ?>
                <div class="hvac-card">
                    <div class="hvac-card-header">
                        <h2><i class="hvac-icon-history"></i>Report History</h2>
                    </div>
                    <div class="hvac-card-body">
                        <div class="hvac-history-list">
                            <?php foreach (array_reverse($report_history) as $report): ?>
                            <div class="hvac-history-item">
                                <div class="hvac-history-meta">
                                    <span class="hvac-history-date">
                                        <?php echo date('M j, Y g:i A', strtotime($report['created_at'])); ?>
                                    </span>
                                    <span class="hvac-history-user">
                                        by <?php echo get_userdata($report['created_by'])->display_name; ?>
                                    </span>
                                </div>
                                <a href="<?php echo esc_url($report['url']); ?>" target="_blank" 
                                   class="hvac-btn hvac-btn-secondary hvac-btn-sm">
                                    <i class="hvac-icon-external"></i> Open
                                </a>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
            </div>
        </div>
        
        <!-- Loading Overlay -->
        <div id="hvac-loading-overlay" class="hvac-loading-overlay" style="display: none;">
            <div class="hvac-loading-content">
                <div class="hvac-spinner"></div>
                <p>Processing request...</p>
            </div>
        </div>
        
        <script>
        // Define ajaxurl for frontend AJAX requests
        var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
        
        document.addEventListener('DOMContentLoaded', function() {
            // Test Connection
            document.getElementById('test-connection').addEventListener('click', function() {
                showLoading();
                
                fetch(ajaxurl, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                    body: 'action=hvac_test_google_sheets_connection&_wpnonce=<?php echo wp_create_nonce('hvac_google_sheets'); ?>'
                })
                .then(response => response.json())
                .then(data => {
                    hideLoading();
                    if (data.success) {
                        showNotification('Connection test successful!', 'success');
                    } else {
                        showNotification('Connection test failed: ' + data.data, 'error');
                    }
                })
                .catch(error => {
                    hideLoading();
                    showNotification('Connection test failed: ' + error.message, 'error');
                });
            });
            
            // Verify Folder Structure
            document.getElementById('verify-folders').addEventListener('click', function() {
                showLoading();
                
                fetch(ajaxurl, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                    body: 'action=hvac_verify_folder_structure&_wpnonce=<?php echo wp_create_nonce('hvac_google_sheets'); ?>'
                })
                .then(response => response.json())
                .then(data => {
                    hideLoading();
                    if (data.success) {
                        showNotification('Folder structure verification completed!', 'success');
                    } else {
                        showNotification('Folder verification failed: ' + data.data, 'error');
                    }
                })
                .catch(error => {
                    hideLoading();
                    showNotification('Folder verification failed: ' + error.message, 'error');
                });
            });
            
            // Create Master Report
            document.getElementById('create-master-report').addEventListener('click', function() {
                showLoading();
                
                fetch(ajaxurl, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                    body: 'action=hvac_create_master_report&_wpnonce=<?php echo wp_create_nonce('hvac_google_sheets'); ?>'
                })
                .then(response => response.json())
                .then(data => {
                    hideLoading();
                    if (data.success) {
                        showNotification('Master Report created successfully!', 'success');
                        setTimeout(() => window.location.reload(), 2000);
                    } else {
                        showNotification('Failed to create Master Report: ' + data.data, 'error');
                    }
                })
                .catch(error => {
                    hideLoading();
                    showNotification('Failed to create Master Report: ' + error.message, 'error');
                });
            });
            
            // Create Event Spreadsheet
            document.getElementById('create-event-spreadsheet').addEventListener('click', function() {
                const eventSelect = document.getElementById('event-select');
                const eventId = eventSelect.value;
                
                if (!eventId) {
                    showNotification('Please select an event first.', 'warning');
                    return;
                }
                
                showLoading();
                
                fetch(ajaxurl, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                    body: `action=hvac_create_event_spreadsheet&event_id=${eventId}&_wpnonce=<?php echo wp_create_nonce('hvac_google_sheets'); ?>`
                })
                .then(response => response.json())
                .then(data => {
                    hideLoading();
                    if (data.success) {
                        showNotification('Event spreadsheet created successfully!', 'success');
                        setTimeout(() => window.location.reload(), 2000);
                    } else {
                        showNotification('Failed to create event spreadsheet: ' + data.data, 'error');
                    }
                })
                .catch(error => {
                    hideLoading();
                    showNotification('Failed to create event spreadsheet: ' + error.message, 'error');
                });
            });
            
            function showLoading() {
                document.getElementById('hvac-loading-overlay').style.display = 'flex';
            }
            
            function hideLoading() {
                document.getElementById('hvac-loading-overlay').style.display = 'none';
            }
            
            function showNotification(message, type) {
                // Create notification element
                const notification = document.createElement('div');
                notification.className = `hvac-notification hvac-notification-${type}`;
                notification.innerHTML = `
                    <span>${message}</span>
                    <button onclick="this.parentElement.remove()">×</button>
                `;
                
                document.body.appendChild(notification);
                
                // Auto-remove after 5 seconds
                setTimeout(() => {
                    if (notification.parentElement) {
                        notification.remove();
                    }
                }, 5000);
            }
        });
        </script>
        <?php
        } catch (Exception $e) {
            // Display error message if something goes wrong
            ?>
            <div class="hvac-google-sheets-admin">
                <div class="hvac-container">
                    <div class="hvac-alert hvac-alert-error">
                        <i class="hvac-icon-warning"></i>
                        <strong>Error:</strong> Unable to load Google Sheets integration. <?php echo esc_html($e->getMessage()); ?>
                    </div>
                    <div class="hvac-actions">
                        <a href="<?php echo home_url('/master-trainer/dashboard/'); ?>" class="hvac-btn hvac-btn-secondary">
                            <i class="hvac-icon-arrow-left"></i> Back to Master Dashboard
                        </a>
                    </div>
                </div>
            </div>
            <?php
            error_log('HVAC Google Sheets Admin Error: ' . $e->getMessage());
        }
    }
    
    /**
     * Render event options for select dropdown
     */
    private function render_event_options() {
        $events = get_posts(array(
            'post_type' => 'tribe_events',
            'post_status' => 'publish',
            'numberposts' => -1,
            'orderby' => 'meta_value',
            'meta_key' => '_EventStartDate',
            'order' => 'DESC'
        ));
        
        foreach ($events as $event) {
            $event_date = get_post_meta($event->ID, '_EventStartDate', true);
            $formatted_date = $event_date ? date('M j, Y', strtotime($event_date)) : 'No date';
            $trainer_name = get_the_author_meta('display_name', $event->post_author);
            
            echo '<option value="' . esc_attr($event->ID) . '">';
            echo esc_html($event->post_title) . ' - ' . esc_html($formatted_date) . ' (' . esc_html($trainer_name) . ')';
            echo '</option>';
        }
    }
    
    /**
     * Render existing event spreadsheets
     */
    private function render_existing_event_sheets() {
        global $wpdb;
        
        $results = $wpdb->get_results(
            "SELECT p.ID, p.post_title, pm.meta_value, u.display_name
             FROM {$wpdb->posts} p
             JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id
             JOIN {$wpdb->users} u ON p.post_author = u.ID
             WHERE p.post_type = 'tribe_events'
             AND pm.meta_key = '_hvac_google_sheet'
             ORDER BY p.post_date DESC"
        );
        
        if (empty($results)) {
            echo '<p class="hvac-no-sheets">No event spreadsheets created yet.</p>';
            return;
        }
        
        foreach ($results as $result) {
            $sheet_data = maybe_unserialize($result->meta_value);
            if (is_array($sheet_data) && isset($sheet_data['url'])) {
                echo '<div class="hvac-event-sheet-item">';
                echo '<div class="hvac-sheet-info">';
                echo '<h4>' . esc_html($result->post_title) . '</h4>';
                echo '<span class="hvac-sheet-trainer">by ' . esc_html($result->display_name) . '</span>';
                echo '<span class="hvac-sheet-date">Created: ' . date('M j, Y', strtotime($sheet_data['created_at'])) . '</span>';
                echo '</div>';
                echo '<a href="' . esc_url($sheet_data['url']) . '" target="_blank" class="hvac-btn hvac-btn-secondary hvac-btn-sm">';
                echo '<i class="hvac-icon-external"></i> Open Spreadsheet';
                echo '</a>';
                echo '</div>';
            }
        }
    }
    
    /**
     * AJAX: Create Master Report
     */
    public function ajax_create_master_report() {
        check_ajax_referer('hvac_google_sheets', '_wpnonce');
        
        if (!current_user_can('view_master_dashboard')) {
            wp_die('Insufficient permissions');
        }
        
        $result = $this->manager->create_master_report();
        
        if ($result['success']) {
            wp_send_json_success($result);
        } else {
            wp_send_json_error($result['error']);
        }
    }
    
    /**
     * AJAX: Create Event Spreadsheet
     */
    public function ajax_create_event_spreadsheet() {
        check_ajax_referer('hvac_google_sheets', '_wpnonce');
        
        if (!current_user_can('view_master_dashboard')) {
            wp_die('Insufficient permissions');
        }
        
        $event_id = intval($_POST['event_id']);
        if (!$event_id) {
            wp_send_json_error('Invalid event ID');
        }
        
        $result = $this->manager->create_event_spreadsheet($event_id);
        
        if ($result['success']) {
            wp_send_json_success($result);
        } else {
            wp_send_json_error($result['error']);
        }
    }
    
    /**
     * AJAX: Test Connection
     */
    public function ajax_test_connection() {
        check_ajax_referer('hvac_google_sheets', '_wpnonce');
        
        if (!current_user_can('view_master_dashboard')) {
            wp_die('Insufficient permissions');
        }
        
        $result = $this->manager->test_connection();
        
        if ($result['success']) {
            wp_send_json_success($result['message']);
        } else {
            wp_send_json_error($result['message']);
        }
    }
    
    /**
     * AJAX: Verify Folder Structure
     */
    public function ajax_verify_folder_structure() {
        check_ajax_referer('hvac_google_sheets', '_wpnonce');
        
        if (!current_user_can('view_master_dashboard')) {
            wp_die('Insufficient permissions');
        }
        
        require_once plugin_dir_path(dirname(__FILE__)) . '../google-sheets-folder-manager.php';
        $folder_manager = new HVAC_Google_Sheets_Folder_Manager();
        
        $result = $folder_manager->verify_folder_structure();
        
        wp_send_json_success($result);
    }
}