<?php
/**
 * CLAWS Admin Class
 * Handles WordPress admin interface for CLAWS
 */

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

class CLAWS_Admin {
    
    private static $instance = null;
    private $database;
    
    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    private function __construct() {
        $this->database = CLAWS_Database::getInstance();
        
        add_action('admin_menu', array($this, 'add_admin_menu'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts'));
        
        // Add user capabilities
        add_action('admin_init', array($this, 'add_user_capabilities'));
        
        // Add meta boxes for custom post types
        add_action('add_meta_boxes', array($this, 'add_custom_meta_boxes'));
        
        // Save meta box data
        add_action('save_post', array($this, 'save_meta_box_data'));
        
        // Flush rewrite rules when needed
        add_action('wp_loaded', array($this, 'maybe_flush_rewrite_rules'));
    }
    
    
    /**
     * Add user capabilities
     */
    public function add_user_capabilities() {
        $roles = array('subscriber', 'contributor', 'author', 'editor', 'administrator');
        foreach ($roles as $role_name) {
            $role = get_role($role_name);
            if ($role) {
                $role->add_cap('read_claws_data');
                $role->add_cap('edit_claws_data');
            }
        }
        
        // Add admin-specific capabilities
        $admin_role = get_role('administrator');
        if ($admin_role) {
            $admin_role->add_cap('manage_claws');
        }
    }
    
    /**
     * Add admin menu
     */
    public function add_admin_menu() {
        add_menu_page(
            __('Purralytics Management', 'claws'),
            __('Purralytics', 'claws'),
            'read_claws_data',
            'claws-admin',
            array($this, 'admin_dashboard'),
            'dashicons-heart',
            30
        );
        
        add_submenu_page(
            'claws-admin',
            __('CATS - Colony Analysis & Tracking System', 'claws'),
            __('CATS Dashboard', 'claws'),
            'read_claws_data',
            'claws-admin',
            array($this, 'admin_dashboard')
        );
        
        // User-specific data management pages
        add_submenu_page(
            'claws-admin',
            __('My Intakes', 'claws'),
            __('My Intakes', 'claws'),
            'read_claws_data',
            'claws-intakes',
            array($this, 'admin_intakes')
        );
        
        add_submenu_page(
            'claws-admin',
            __('My Discharges', 'claws'),
            __('My Discharges', 'claws'),
            'read_claws_data',
            'claws-discharges',
            array($this, 'admin_discharges')
        );
        
        add_submenu_page(
            'claws-admin',
            __('My Feeding Records', 'claws'),
            __('My Feeding Records', 'claws'),
            'read_claws_data',
            'claws-feeding',
            array($this, 'admin_feeding')
        );
        
        // Colony management pages
        add_submenu_page(
            'claws-admin',
            __('My Colonies', 'claws'),
            __('My Colonies', 'claws'),
            'read_claws_data',
            'claws-my-colonies',
            array($this, 'admin_my_colonies')
        );
        
        // Show "All Colonies" for authors and admins
        if (current_user_can('edit_others_posts')) {
            add_submenu_page(
                'claws-admin',
                __('All Colonies', 'claws'),
                __('All Colonies', 'claws'),
                'edit_others_posts',
                'claws-all-colonies',
                array($this, 'admin_all_colonies')
            );
            
            add_submenu_page(
                'claws-admin',
                __('Historical Colony Data', 'claws'),
                __('Historical Colony Data', 'claws'),
                'edit_others_posts',
                'claws-colony-history',
                array($this, 'admin_colony_history')
            );
        }
        
        if (current_user_can('manage_options')) {
            add_submenu_page(
                'claws-admin',
                __('Reports', 'claws'),
                __('Reports', 'claws'),
                'manage_options',
                'claws-reports',
                array($this, 'admin_reports')
            );
            
            add_submenu_page(
                'claws-admin',
                __('Settings', 'claws'),
                __('Settings', 'claws'),
                'manage_options',
                'claws-settings',
                array($this, 'admin_settings')
            );
            
        }
        
        // Volunteer system menu items
        add_submenu_page(
            'claws-admin',
            __('Volunteer Tasks', 'claws'),
            __('Tasks', 'claws'),
            'read_claws_data',
            'edit.php?post_type=claws_volunteer_time',
            null
        );
        
        add_submenu_page(
            'claws-admin',
            __('Events & Projects', 'claws'),
            __('Events/Projects', 'claws'),
            'read_claws_data',
            'edit.php?post_type=claws_event',
            null
        );
        
        add_submenu_page(
            'claws-admin',
            __('Help', 'claws'),
            __('Help', 'claws'),
            'read_claws_data',
            'claws-help',
            array($this, 'admin_help')
        );
    }
    
    /**
     * Enqueue admin scripts
     */
    public function enqueue_admin_scripts($hook) {
        // Only load on CLAWS admin pages
        if (strpos($hook, 'claws') === false) {
            return;
        }
        
        wp_enqueue_script('claws-admin', CLAWS_PLUGIN_URL . 'assets/js/admin.js', 
            array('jquery', 'wp-api'), CLAWS_VERSION, true);
        
        wp_enqueue_style('claws-admin', CLAWS_PLUGIN_URL . 'assets/css/admin.css', 
            array(), CLAWS_VERSION);
        
        // Enqueue Chart.js for admin reports page
        if (strpos($hook, 'claws-reports') !== false) {
            wp_enqueue_script('chartjs', 'https://cdn.jsdelivr.net/npm/chart.js', array(), '4.4.0', true);
        }
        
        // Enqueue Leaflet.js and media library for settings page
        if (strpos($hook, 'claws-settings') !== false) {
            wp_enqueue_script('leaflet', 'https://unpkg.com/leaflet@1.9.4/dist/leaflet.js', array(), '1.9.4', true);
            wp_enqueue_style('leaflet', 'https://unpkg.com/leaflet@1.9.4/dist/leaflet.css', array(), '1.9.4');
            
            // Enqueue WordPress media library for logo upload
            wp_enqueue_media();
        }
        
        // Localize admin script
        wp_localize_script('claws-admin', 'clawsAdmin', array(
            'apiUrl' => rest_url('claws/v1/'),
            'nonce' => wp_create_nonce('wp_rest'),
            'currentUserId' => get_current_user_id(),
            'isAdmin' => current_user_can('manage_options')
        ));
    }
    
    /**
     * Admin dashboard page
     */
    public function admin_dashboard() {
        $colonies = $this->database->get_colonies();
        $user_id = get_current_user_id();
        
        // Get user's personal stats
        $user_intakes = $this->database->get_user_intakes($user_id);
        $user_discharges = $this->database->get_user_discharges($user_id);
        $user_feedings = $this->database->get_user_feeding_records($user_id, 10);
        
        // Get overall stats (for admins)
        $total_colonies = count($colonies);
        $total_cats = array_sum(array_column($colonies, 'cats'));
        
        ?>
        <div class="wrap">
            <h1><?php _e('CATS - Colony Analysis & Tracking System', 'claws'); ?></h1>
            
            <?php if (function_exists('pur_fs')): ?>
                <!-- Plan Badge -->
                <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 1rem; border-radius: 0.5rem; margin: 1rem 0 2rem 0; box-shadow: 0 4px 6px rgba(0,0,0,0.1);">
                    <div style="display: flex; justify-content: space-between; align-items: center;">
                        <div>
                            <div style="font-size: 0.875rem; opacity: 0.9; margin-bottom: 0.25rem;">
                                <?php 
                                if (pur_fs()->is_trial()) {
                                    $trial = pur_fs()->get_trial_plan();
                                    if ($trial) {
                                        $days_left = ceil(($trial->trial_ends - time()) / DAY_IN_SECONDS);
                                        echo sprintf(__('Trial Period - %d days remaining', 'claws'), $days_left);
                                    }
                                } else {
                                    echo __('Current Plan', 'claws');
                                }
                                ?>
                            </div>
                            <div style="font-size: 1.5rem; font-weight: 700;">
                                <?php 
                                if (pur_fs()->is_trial()) {
                                    echo __('Trial - Full Access', 'claws');
                                } elseif (pur_fs()->is_plan('deluxe', true)) {
                                    echo __('Deluxe', 'claws') . ' ✨';
                                } elseif (pur_fs()->is_plan('basic', true)) {
                                    echo __('Basic', 'claws');
                                } else {
                                    echo __('Free', 'claws');
                                }
                                ?>
                            </div>
                            <?php if (pur_fs()->is_plan('basic', true)): ?>
                                <div style="font-size: 0.875rem; margin-top: 0.5rem; opacity: 0.9;">
                                    <?php _e('Upgrade to Deluxe to unlock Volunteer Management', 'claws'); ?>
                                </div>
                            <?php endif; ?>
                        </div>
                        <?php if (!pur_fs()->is_plan('deluxe')): ?>
                            <a href="<?php echo esc_url(pur_fs()->get_upgrade_url()); ?>" 
                               style="background: white; color: #667eea; padding: 0.5rem 1.5rem; border-radius: 0.5rem; font-weight: 600; text-decoration: none; transition: all 0.2s;"
                               onmouseover="this.style.transform='scale(1.05)'" 
                               onmouseout="this.style.transform='scale(1)'">
                                <?php _e('Upgrade', 'claws'); ?> →
                            </a>
                        <?php else: ?>
                            <div style="background: rgba(255,255,255,0.2); padding: 0.5rem 1rem; border-radius: 0.5rem; font-weight: 600;">
                                <?php _e('Premium Active', 'claws'); ?> ✓
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endif; ?>
            
            <!-- Quick Stats -->
            <div class="claws-stats-grid">
                <div class="claws-stat-card">
                    <div class="stat-icon">📍</div>
                    <div class="stat-info">
                        <h3><?php _e('Total Colonies', 'claws'); ?></h3>
                        <p class="stat-number"><?php echo $total_colonies; ?></p>
                    </div>
                </div>
                
                <div class="claws-stat-card">
                    <div class="stat-icon">❤️</div>
                    <div class="stat-info">
                        <h3><?php _e('Total Cats', 'claws'); ?></h3>
                        <p class="stat-number"><?php echo $total_cats; ?></p>
                    </div>
                </div>
                
                <div class="claws-stat-card">
                    <div class="stat-icon">📝</div>
                    <div class="stat-info">
                        <h3><?php _e('Your Intakes', 'claws'); ?></h3>
                        <p class="stat-number"><?php echo count($user_intakes); ?></p>
                    </div>
                </div>
                
                <div class="claws-stat-card">
                    <div class="stat-icon">➡️</div>
                    <div class="stat-info">
                        <h3><?php _e('Your Discharges', 'claws'); ?></h3>
                        <p class="stat-number"><?php echo count($user_discharges); ?></p>
                    </div>
                </div>
            </div>
            
            <!-- Quick Actions -->
            <div class="claws-admin-section">
                <h2><?php _e('Quick Actions', 'claws'); ?></h2>
                <div class="claws-actions-grid">
                    <a href="<?php echo home_url('/claws-app/'); ?>" class="button button-primary button-large">
                        <?php _e('Open Purralytics App', 'claws'); ?>
                    </a>
                    <button onclick="exportData()" class="button button-secondary">
                        <?php _e('Export Your Data', 'claws'); ?>
                    </button>
                    <?php if (current_user_can('manage_options')): ?>
                    <a href="<?php echo admin_url('admin.php?page=claws-reports'); ?>" class="button button-secondary">
                        <?php _e('View Reports', 'claws'); ?>
                    </a>
                    <?php endif; ?>
                </div>
            </div>
            
            <!-- Recent Activity -->
            <div class="claws-admin-section">
                <h2><?php _e('Recent Activity', 'claws'); ?></h2>
                
                <?php if (!empty($user_feedings)): ?>
                <div class="claws-recent-activity">
                    <h3><?php _e('Recent Feeding Records', 'claws'); ?></h3>
                    <table class="wp-list-table widefat fixed striped">
                        <thead>
                            <tr>
                                <th><?php _e('Kitten Name', 'claws'); ?></th>
                                <th><?php _e('Date', 'claws'); ?></th>
                                <th><?php _e('Time', 'claws'); ?></th>
                                <th><?php _e('Weight Gain', 'claws'); ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach (array_slice($user_feedings, 0, 5) as $feeding): ?>
                            <tr>
                                <td><?php echo esc_html($feeding['kitten_name']); ?></td>
                                <td><?php echo esc_html($feeding['feeding_date']); ?></td>
                                <td><?php echo esc_html($feeding['feeding_time']); ?></td>
                                <td>
                                    <?php 
                                    $gain = floatval($feeding['post_weight']) - floatval($feeding['pre_weight']);
                                    echo $gain > 0 ? '+' . $gain . 'g' : $gain . 'g';
                                    ?>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <?php else: ?>
                <p><?php _e('No recent feeding records found.', 'claws'); ?></p>
                <?php endif; ?>
            </div>
            
            <!-- Usage Instructions -->
            <div class="claws-admin-section">
                <h2><?php _e('How to Use Purralytics', 'claws'); ?></h2>
                <div class="claws-instructions">
                    <div class="instruction-card">
                        <h3><?php _e('1. Add the App to a Page', 'claws'); ?></h3>
                        <p><?php _e('Use the shortcode', 'claws'); ?> <code>[claws_app]</code> <?php _e('on any page to display the full Purralytics application.', 'claws'); ?></p>
                    </div>
                    
                    <div class="instruction-card">
                        <h3><?php _e('2. Individual Components', 'claws'); ?></h3>
                        <p><?php _e('You can also use individual shortcodes:', 'claws'); ?></p>
                        <ul>
                            <li><code>[claws_colony_tracker]</code> - <?php _e('Colony tracking only', 'claws'); ?></li>
                            <li><code>[claws_intake_discharge]</code> - <?php _e('Intake & discharge forms only', 'claws'); ?></li>
                            <li><code>[claws_neonate_care]</code> - <?php _e('Neonate care tracking only', 'claws'); ?></li>
                        </ul>
                    </div>
                    
                    <div class="instruction-card">
                        <h3><?php _e('3. User Permissions', 'claws'); ?></h3>
                        <p><?php _e('Users must be logged in to save data. Only administrators can delete or edit colonies created by others.', 'claws'); ?></p>
                    </div>
                </div>
            </div>
        </div>
        
        <script>
        function exportData() {
            if (confirm('<?php _e('Export all your Purralytics data as CSV files?', 'claws'); ?>')) {
                fetch(clawsAdmin.apiUrl + 'user/export', {
                    credentials: 'include',
                    headers: {
                        'X-WP-Nonce': clawsAdmin.nonce
                    }
                })
                .then(response => response.blob())
                .then(blob => {
                    const url = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = 'claws-data-export-' + new Date().toISOString().split('T')[0] + '.zip';
                    a.click();
                    window.URL.revokeObjectURL(url);
                });
            }
        }
        </script>
        <?php
    }
    
    /**
     * Admin reports page
     */
    public function admin_reports() {
        if (!current_user_can('manage_options')) {
            wp_die(__('You do not have sufficient permissions to access this page.'));
        }
        
        $colonies = $this->database->get_colonies();
        $total_cats = array_sum(array_column($colonies, 'cats'));
        
        ?>
        <div class="wrap">
            <h1><?php _e('Purralytics Reports', 'claws'); ?></h1>
            
            <!-- Summary Stats -->
            <div class="claws-report-summary">
                <div class="report-stat">
                    <h3><?php echo count($colonies); ?></h3>
                    <p><?php _e('Total Colonies', 'claws'); ?></p>
                </div>
                <div class="report-stat">
                    <h3><?php echo $total_cats; ?></h3>
                    <p><?php _e('Total Cats', 'claws'); ?></p>
                </div>
                <div class="report-stat">
                    <h3><?php echo wp_count_posts('claws_intake')->publish; ?></h3>
                    <p><?php _e('Total Intakes', 'claws'); ?></p>
                </div>
                <div class="report-stat">
                    <h3><?php echo wp_count_posts('claws_discharge')->publish; ?></h3>
                    <p><?php _e('Total Discharges', 'claws'); ?></p>
                </div>
            </div>
            
            <!-- Aggregate Analytics Charts -->
            <div class="claws-admin-section">
                <h2><?php _e('Analytics Overview', 'claws'); ?></h2>
                <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px; margin-bottom: 30px;">
                    
                    <!-- Intake Type Chart -->
                    <div style="background: white; border: 1px solid #ddd; border-radius: 8px; padding: 20px;">
                        <h3><?php _e('Intakes by Type', 'claws'); ?></h3>
                        <canvas id="admin-intake-type-chart" style="max-height: 300px;"></canvas>
                    </div>
                    
                    <!-- Intake Gender Chart -->
                    <div style="background: white; border: 1px solid #ddd; border-radius: 8px; padding: 20px;">
                        <h3><?php _e('Intakes by Gender', 'claws'); ?></h3>
                        <canvas id="admin-intake-gender-chart" style="max-height: 300px;"></canvas>
                    </div>
                    
                    <!-- Intake Age Chart -->
                    <div style="background: white; border: 1px solid #ddd; border-radius: 8px; padding: 20px;">
                        <h3><?php _e('Intakes by Age', 'claws'); ?></h3>
                        <canvas id="admin-intake-age-chart" style="max-height: 300px;"></canvas>
                    </div>
                    
                    <!-- Discharge Outcomes Chart -->
                    <div style="background: white; border: 1px solid #ddd; border-radius: 8px; padding: 20px;">
                        <h3><?php _e('Discharge Outcomes', 'claws'); ?></h3>
                        <canvas id="admin-discharge-outcome-chart" style="max-height: 300px;"></canvas>
                    </div>
                    
                </div>
            </div>
            
            <!-- Export Options -->
            <div class="claws-admin-section">
                <h2><?php _e('Data Export', 'claws'); ?></h2>
                <p><?php _e('Export colony and activity data for analysis.', 'claws'); ?></p>
                
                <div class="export-buttons">
                    <button onclick="exportColonies()" class="button button-primary">
                        <?php _e('Export Colony Data', 'claws'); ?>
                    </button>
                    <button onclick="exportIntakes()" class="button button-secondary">
                        <?php _e('Export Intake Data', 'claws'); ?>
                    </button>
                    <button onclick="exportDischarges()" class="button button-secondary">
                        <?php _e('Export Discharge Data', 'claws'); ?>
                    </button>
                    <button onclick="exportFullReport()" class="button button-secondary">
                        <?php _e('Full Report', 'claws'); ?>
                    </button>
                </div>
            </div>
            
            <!-- Recent Feeding Records -->
            <div class="claws-admin-section">
                <h2><?php _e('Recent Feeding Records', 'claws'); ?></h2>
                <?php
                // Get recent feeding records across all users (admin only)
                $recent_feedings = $this->database->get_all_feeding_records(20);
                ?>
                
                <?php if (!empty($recent_feedings)): ?>
                <table class="wp-list-table widefat fixed striped">
                    <thead>
                        <tr>
                            <th><?php _e('Date', 'claws'); ?></th>
                            <th><?php _e('Time', 'claws'); ?></th>
                            <th><?php _e('Kitten Name', 'claws'); ?></th>
                            <th><?php _e('Weight Gain', 'claws'); ?></th>
                            <th><?php _e('User', 'claws'); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($recent_feedings as $feeding): ?>
                        <tr>
                            <td><?php echo esc_html($feeding['feeding_date']); ?></td>
                            <td><?php echo esc_html($feeding['feeding_time']); ?></td>
                            <td><strong><?php echo esc_html($feeding['kitten_name']); ?></strong></td>
                            <td>
                                <?php 
                                $gain = floatval($feeding['post_weight']) - floatval($feeding['pre_weight']);
                                echo $gain > 0 ? '+' . $gain . 'g' : $gain . 'g';
                                ?>
                            </td>
                            <td><?php echo esc_html($feeding['username'] ?? 'Unknown'); ?></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                <?php else: ?>
                <p><?php _e('No recent feeding records found.', 'claws'); ?></p>
                <?php endif; ?>
            </div>
            
            <!-- Database Management -->
            <div class="claws-admin-section">
                <h2><?php _e('Database Management', 'claws'); ?></h2>
                <div style="background: white; border: 1px solid #ddd; border-radius: 8px; padding: 20px; margin-bottom: 20px;">
                    
                    <!-- Feeding Records Cleanup -->
                    <div style="background: #fef3c7; border: 1px solid #f59e0b; border-radius: 0.5rem; padding: 1rem; margin-bottom: 1.5rem;">
                        <h4 style="font-size: 1.125rem; font-weight: 600; color: #92400e; margin: 0 0 0.5rem;">⚠️ Feeding Records Cleanup</h4>
                        <p style="color: #92400e; font-size: 0.875rem; margin: 0 0 1rem;">Delete feeding records by date range to keep the database manageable. Records for active kittens are protected by default.</p>
                        
                        <div style="display: grid; grid-template-columns: 1fr 1fr 1fr auto; gap: 1rem; align-items: end; margin-bottom: 1rem;">
                            <div>
                                <label style="display: block; font-weight: 600; color: #374151; margin-bottom: 0.25rem; font-size: 0.875rem;">Start Date</label>
                                <input type="date" id="admin-bulk-delete-start-date" style="width: 100%; padding: 0.5rem; border: 1px solid #d1d5db; border-radius: 0.375rem; font-size: 0.875rem;">
                            </div>
                            <div>
                                <label style="display: block; font-weight: 600; color: #374151; margin-bottom: 0.25rem; font-size: 0.875rem;">End Date</label>
                                <input type="date" id="admin-bulk-delete-end-date" style="width: 100%; padding: 0.5rem; border: 1px solid #d1d5db; border-radius: 0.375rem; font-size: 0.875rem;">
                            </div>
                            <div>
                                <label style="display: block; font-weight: 600; color: #374151; margin-bottom: 0.25rem; font-size: 0.875rem;">
                                    <input type="checkbox" id="admin-protect-active-kittens" checked style="margin-right: 0.5rem;">
                                    Protect Active Kittens
                                </label>
                                <p style="color: #6b7280; font-size: 0.75rem; margin: 0;">Only delete records for discharged kittens</p>
                            </div>
                            <div>
                                <button onclick="adminBulkDeleteFeedingRecords()" style="background: #dc2626; color: white; border: none; border-radius: 0.375rem; padding: 0.5rem 1rem; font-size: 0.875rem; font-weight: 600; cursor: pointer; transition: background-color 0.2s;" onmouseover="this.style.backgroundColor='#b91c1c'" onmouseout="this.style.backgroundColor='#dc2626'">
                                    🗑️ Delete Records
                                </button>
                            </div>
                        </div>
                        
                        <div id="admin-bulk-delete-result" style="display: none; padding: 0.75rem; border-radius: 0.375rem; font-size: 0.875rem; font-weight: 500;"></div>
                    </div>
                </div>
            </div>

            <!-- Colony Health Overview -->
            <div class="claws-admin-section">
                <h2><?php _e('Colony Health Overview', 'claws'); ?></h2>
                <table class="wp-list-table widefat fixed striped">
                    <thead>
                        <tr>
                            <th><?php _e('Colony Name', 'claws'); ?></th>
                            <th><?php _e('Total Cats', 'claws'); ?></th>
                            <th><?php _e('TNR Progress', 'claws'); ?></th>
                            <th><?php _e('Health Score', 'claws'); ?></th>
                            <th><?php _e('Added By', 'claws'); ?></th>
                            <th><?php _e('Last Updated', 'claws'); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($colonies as $colony): 
                            // TNR Progress - cats and seniors only (exclude newborns and kittens)
                            $cats_and_seniors = ($colony['adults'] ?? 0) + ($colony['seniors'] ?? 0);
                            $tnr_progress = $cats_and_seniors > 0 ? round(($colony['tippedEars'] / $cats_and_seniors) * 100) : 0;
                            $health_score = $this->calculate_health_score($colony);
                        ?>
                        <tr>
                            <td><strong><?php echo esc_html($colony['name']); ?></strong></td>
                            <td><?php echo $colony['cats']; ?></td>
                            <td>
                                <span class="health-indicator health-<?php echo $this->get_health_class($tnr_progress); ?>">
                                    <?php echo $tnr_progress; ?>%
                                </span>
                            </td>
                            <td>
                                <span class="health-indicator health-<?php echo $this->get_health_class($health_score); ?>">
                                    <?php echo $health_score; ?>%
                                </span>
                            </td>
                            <td><?php echo esc_html($colony['addedBy']); ?></td>
                            <td><?php echo $colony['lastUpdated'] ? date('Y-m-d', strtotime($colony['lastUpdated'])) : 'N/A'; ?></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
        
        <script>
        function exportColonies() {
            fetch(clawsAdmin.apiUrl + 'admin/report', {
                credentials: 'include',
                headers: { 'X-WP-Nonce': clawsAdmin.nonce }
            })
            .then(response => response.json())
            .then(data => {
                let csv = 'Colony Name,Total Cats,Babies,Kittens,Adults,Seniors,TNR Progress,Health Score,Added By,Last Updated,Address\n';
                data.colonies.forEach(colony => {
                    // TNR Progress - cats and seniors only (exclude newborns and kittens)
                    const catsAndSeniors = (colony.adults || 0) + (colony.seniors || 0);
                    const tnrProgress = catsAndSeniors > 0 ? Math.round((colony.tippedEars / catsAndSeniors) * 100) : 0;
                    csv += `"${colony.name}",${colony.cats},${colony.babies},${colony.kittens},${colony.adults},${colony.seniors},${tnrProgress}%,"${colony.addedBy}","${colony.lastUpdated}","${colony.address}"\n`;
                });
                downloadCSV(csv, 'claws-colonies-' + new Date().toISOString().split('T')[0] + '.csv');
            });
        }
        
        function exportIntakes() {
            // Similar export function for intakes
            alert('<?php _e('Intake export functionality will be implemented.', 'claws'); ?>');
        }
        
        function exportDischarges() {
            // Similar export function for discharges
            alert('<?php _e('Discharge export functionality will be implemented.', 'claws'); ?>');
        }
        
        function exportFullReport() {
            alert('<?php _e('Full report export functionality will be implemented.', 'claws'); ?>');
        }
        
        function downloadCSV(csv, filename) {
            const blob = new Blob([csv], { type: 'text/csv' });
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = filename;
            a.click();
            window.URL.revokeObjectURL(url);
        }
        
        // Load and display aggregate charts
        document.addEventListener('DOMContentLoaded', function() {
            loadAggregateCharts();
        });
        
        // Admin bulk delete feeding records function
        window.adminBulkDeleteFeedingRecords = async function() {
            const startDate = document.getElementById('admin-bulk-delete-start-date').value;
            const endDate = document.getElementById('admin-bulk-delete-end-date').value;
            const protectActive = document.getElementById('admin-protect-active-kittens').checked;
            const resultDiv = document.getElementById('admin-bulk-delete-result');
            
            // Validation
            if (!startDate || !endDate) {
                adminShowBulkDeleteResult('Please select both start and end dates.', 'error');
                return;
            }
            
            if (new Date(startDate) > new Date(endDate)) {
                adminShowBulkDeleteResult('Start date must be before or equal to end date.', 'error');
                return;
            }
            
            // Confirmation
            const protectionText = protectActive ? ' (records for active kittens will be protected)' : ' (ALL records in range will be deleted)';
            if (!confirm(`Are you sure you want to delete feeding records from ${startDate} to ${endDate}?${protectionText}\n\nThis action cannot be undone.`)) {
                return;
            }
            
            try {
                resultDiv.style.display = 'block';
                resultDiv.innerHTML = '⏳ Deleting records...';
                resultDiv.style.background = '#dbeafe';
                resultDiv.style.color = '#1e40af';
                
                const response = await fetch('<?php echo rest_url('claws/v1/feeding/bulk-delete'); ?>', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-WP-Nonce': clawsAdmin.nonce
                    },
                    body: JSON.stringify({
                        start_date: startDate,
                        end_date: endDate,
                        exclude_active_kittens: protectActive
                    })
                });
                
                const result = await response.json();
                
                if (response.ok && result.success) {
                    adminShowBulkDeleteResult(result.message, 'success');
                } else {
                    adminShowBulkDeleteResult(result.message || 'Failed to delete records.', 'error');
                }
                
            } catch (error) {
                console.error('Admin bulk delete error:', error);
                adminShowBulkDeleteResult('An error occurred while deleting records.', 'error');
            }
        };
        
        window.adminShowBulkDeleteResult = function(message, type) {
            const resultDiv = document.getElementById('admin-bulk-delete-result');
            resultDiv.style.display = 'block';
            resultDiv.innerHTML = message;
            
            if (type === 'success') {
                resultDiv.style.background = '#d1fae5';
                resultDiv.style.color = '#065f46';
            } else if (type === 'error') {
                resultDiv.style.background = '#fee2e2';
                resultDiv.style.color = '#991b1b';
            }
            
            // Auto-hide after 10 seconds
            setTimeout(() => {
                resultDiv.style.display = 'none';
            }, 10000);
        };
        
        function loadAggregateCharts() {
            // Load all intake data
            fetch(clawsAdmin.apiUrl + 'admin/intakes', {
                credentials: 'include',
                headers: { 'X-WP-Nonce': clawsAdmin.nonce }
            })
            .then(response => response.json())
            .then(intakes => {
                createAggregateIntakeTypeChart(intakes);
                createAggregateIntakeGenderChart(intakes);
                createAggregateIntakeAgeChart(intakes);
            })
            .catch(error => console.error('Error loading intake data:', error));
            
            // Load all discharge data
            fetch(clawsAdmin.apiUrl + 'admin/discharges', {
                credentials: 'include',
                headers: { 'X-WP-Nonce': clawsAdmin.nonce }
            })
            .then(response => response.json())
            .then(discharges => {
                createAggregateDischargeOutcomeChart(discharges);
            })
            .catch(error => console.error('Error loading discharge data:', error));
        }
        
        function createAggregateIntakeTypeChart(intakes) {
            const canvas = document.getElementById('admin-intake-type-chart');
            if (!canvas) return;
            
            const typeCounts = {};
            intakes.forEach(intake => {
                const type = intake.type || 'Unknown';
                typeCounts[type] = (typeCounts[type] || 0) + 1;
            });
            
            const colors = ['#ef4444', '#f97316', '#eab308', '#22c55e', '#06b6d4', '#3b82f6', '#8b5cf6', '#ec4899'];
            const chartData = Object.entries(typeCounts).map(([type, count], index) => ({
                label: type,
                data: count,
                backgroundColor: colors[index % colors.length]
            }));
            
            new Chart(canvas.getContext('2d'), {
                type: 'pie',
                data: {
                    labels: chartData.map(d => d.label),
                    datasets: [{
                        data: chartData.map(d => d.data),
                        backgroundColor: chartData.map(d => d.backgroundColor)
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false
                }
            });
        }
        
        function createAggregateIntakeGenderChart(intakes) {
            const canvas = document.getElementById('admin-intake-gender-chart');
            if (!canvas) return;
            
            const genderCounts = {};
            intakes.forEach(intake => {
                const gender = intake.gender || 'Unknown';
                genderCounts[gender] = (genderCounts[gender] || 0) + 1;
            });
            
            const colors = ['#ef4444', '#f97316', '#eab308', '#22c55e', '#06b6d4', '#3b82f6', '#8b5cf6', '#ec4899'];
            const chartData = Object.entries(genderCounts).map(([gender, count], index) => ({
                label: gender,
                data: count,
                backgroundColor: colors[index % colors.length]
            }));
            
            new Chart(canvas.getContext('2d'), {
                type: 'pie',
                data: {
                    labels: chartData.map(d => d.label),
                    datasets: [{
                        data: chartData.map(d => d.data),
                        backgroundColor: chartData.map(d => d.backgroundColor)
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false
                }
            });
        }
        
        function createAggregateIntakeAgeChart(intakes) {
            const canvas = document.getElementById('admin-intake-age-chart');
            if (!canvas) return;
            
            const ageCounts = {};
            intakes.forEach(intake => {
                const age = intake.age || 'Unknown';
                ageCounts[age] = (ageCounts[age] || 0) + 1;
            });
            
            const colors = ['#ef4444', '#f97316', '#eab308', '#22c55e', '#06b6d4', '#3b82f6', '#8b5cf6', '#ec4899'];
            const chartData = Object.entries(ageCounts).map(([age, count], index) => ({
                label: age,
                data: count,
                backgroundColor: colors[index % colors.length]
            }));
            
            new Chart(canvas.getContext('2d'), {
                type: 'pie',
                data: {
                    labels: chartData.map(d => d.label),
                    datasets: [{
                        data: chartData.map(d => d.data),
                        backgroundColor: chartData.map(d => d.backgroundColor)
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false
                }
            });
        }
        
        function createAggregateDischargeOutcomeChart(discharges) {
            const canvas = document.getElementById('admin-discharge-outcome-chart');
            if (!canvas) return;
            
            const outcomeCounts = {};
            discharges.forEach(discharge => {
                const outcome = discharge.outcome || 'Unknown';
                outcomeCounts[outcome] = (outcomeCounts[outcome] || 0) + 1;
            });
            
            const colors = ['#ef4444', '#f97316', '#eab308', '#22c55e', '#06b6d4', '#3b82f6', '#8b5cf6', '#ec4899'];
            const chartData = Object.entries(outcomeCounts).map(([outcome, count], index) => ({
                label: outcome,
                data: count,
                backgroundColor: colors[index % colors.length]
            }));
            
            new Chart(canvas.getContext('2d'), {
                type: 'pie',
                data: {
                    labels: chartData.map(d => d.label),
                    datasets: [{
                        data: chartData.map(d => d.data),
                        backgroundColor: chartData.map(d => d.backgroundColor)
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false
                }
            });
        }
        </script>
        <?php
    }
    
    /**
     * Admin settings page
     */
    public function admin_settings() {
        if (!current_user_can('manage_options')) {
            wp_die(__('You do not have sufficient permissions to access this page.'));
        }
        
        // Handle form submissions
        if (isset($_POST['submit']) && wp_verify_nonce($_POST['claws_settings_nonce'], 'claws_settings')) {
            update_option('claws_default_location', sanitize_text_field($_POST['default_location']));
            
            
            // New branding options
            update_option('claws_organization_name', sanitize_text_field($_POST['organization_name']));
            update_option('claws_organization_tagline', sanitize_text_field($_POST['organization_tagline']));
            
            // Handle logo upload
            if (isset($_POST['organization_logo'])) {
                $logo_id = absint($_POST['organization_logo']);
                if ($logo_id > 0) {
                    // Verify the attachment exists and is an image
                    $attachment = get_post($logo_id);
                    if ($attachment && $attachment->post_type === 'attachment' && strpos($attachment->post_mime_type, 'image/') === 0) {
                        update_option('claws_organization_logo', $logo_id);
                    }
                } else {
                    // Remove logo if empty
                    update_option('claws_organization_logo', 0);
                }
            }
            
            // Color scheme options
            update_option('claws_color_scheme_type', sanitize_text_field($_POST['color_scheme_type']));
            update_option('claws_primary_color', sanitize_hex_color($_POST['primary_color']));
            update_option('claws_secondary_color', sanitize_hex_color($_POST['secondary_color']));
            update_option('claws_header_text_color', in_array($_POST['header_text_color'], ['white', 'black']) ? $_POST['header_text_color'] : 'white');
            
            // Map coordinates with validation
            $latitude = isset($_POST['default_latitude']) ? floatval($_POST['default_latitude']) : 39.8283;
            $longitude = isset($_POST['default_longitude']) ? floatval($_POST['default_longitude']) : -98.5795;
            
            // Validate latitude/longitude ranges
            if ($latitude < -90 || $latitude > 90) $latitude = 39.8283;
            if ($longitude < -180 || $longitude > 180) $longitude = -98.5795;
            
            update_option('claws_default_latitude', $latitude);
            update_option('claws_default_longitude', $longitude);
            
            // Zapier integration settings
            if (isset($_POST['zapier_enabled'])) {
                update_option('claws_zapier_enabled', 1);
            } else {
                update_option('claws_zapier_enabled', 0);
            }
            
            if (isset($_POST['zapier_webhook_url'])) {
                update_option('claws_zapier_webhook_url', esc_url_raw($_POST['zapier_webhook_url']));
            }
            
            // Zapier event triggers
            $zapier_events = array();
            if (isset($_POST['zapier_trigger_intake'])) $zapier_events[] = 'intake';
            if (isset($_POST['zapier_trigger_discharge'])) $zapier_events[] = 'discharge';
            if (isset($_POST['zapier_trigger_colony'])) $zapier_events[] = 'colony';
            update_option('claws_zapier_events', $zapier_events);
            
            // AI integration settings
            if (isset($_POST['ai_enabled'])) {
                update_option('claws_ai_enabled', 1);
            } else {
                update_option('claws_ai_enabled', 0);
            }
            
            if (isset($_POST['ai_provider'])) {
                update_option('claws_ai_provider', sanitize_text_field($_POST['ai_provider']));
            }
            
            if (isset($_POST['ai_api_key'])) {
                update_option('claws_ai_api_key', sanitize_text_field($_POST['ai_api_key']));
            }
            
            if (isset($_POST['ai_custom_url'])) {
                update_option('claws_ai_custom_url', esc_url_raw($_POST['ai_custom_url']));
            }
            
            // Advanced feature visibility settings
            if (isset($_POST['enable_neonate_feeding'])) {
                update_option('claws_enable_neonate_feeding', 1);
            } else {
                update_option('claws_enable_neonate_feeding', 0);
            }
            
            // Colony help options management
            if (isset($_POST['colony_help_options'])) {
                $help_options = array();
                $option_keys = $_POST['colony_help_option_keys'];
                $option_labels = $_POST['colony_help_option_labels'];
                $option_emails = $_POST['colony_help_option_emails'];
                
                if (is_array($option_keys) && is_array($option_labels)) {
                    for ($i = 0; $i < count($option_keys); $i++) {
                        if (!empty($option_keys[$i]) && !empty($option_labels[$i])) {
                            $help_options[$option_keys[$i]] = array(
                                'label' => sanitize_text_field($option_labels[$i]),
                                'email' => isset($option_emails[$i]) ? sanitize_email($option_emails[$i]) : ''
                            );
                        }
                    }
                }
                update_option('claws_colony_help_options', $help_options);
            }
            
            // Colony help email template
            if (isset($_POST['colony_help_email_template'])) {
                update_option('claws_colony_help_email_template', wp_kses_post($_POST['colony_help_email_template']));
            }
            
            // Set opportunity creation to editors only (coordinators)
            update_option('claws_opportunity_creation_level', 'editors');
            
            // Opportunity categories management
            if (isset($_POST['opportunity_categories'])) {
                $categories = array();
                $category_keys = $_POST['opportunity_category_keys'];
                $category_labels = $_POST['opportunity_category_labels'];
                
                if (is_array($category_keys) && is_array($category_labels)) {
                    for ($i = 0; $i < count($category_keys); $i++) {
                        if (!empty($category_keys[$i]) && !empty($category_labels[$i])) {
                            $categories[$category_keys[$i]] = sanitize_text_field($category_labels[$i]);
                        }
                    }
                }
                update_option('claws_opportunity_categories', $categories);
            }
            
            // Task types management
            if (isset($_POST['task_types'])) {
                $types = array();
                $type_keys = $_POST['task_type_keys'];
                $type_labels = $_POST['task_type_labels'];
                
                if (is_array($type_keys) && is_array($type_labels)) {
                    for ($i = 0; $i < count($type_keys); $i++) {
                        if (!empty($type_keys[$i]) && !empty($type_labels[$i])) {
                            $types[$type_keys[$i]] = sanitize_text_field($type_labels[$i]);
                        }
                    }
                }
                update_option('claws_task_types', $types);
            }
            
            // Teams management
            if (isset($_POST['teams'])) {
                $teams_data = array();
                $team_keys = $_POST['team_keys'];
                $team_names = $_POST['team_names'];
                $team_descriptions = $_POST['team_descriptions'];
                
                if (is_array($team_keys) && is_array($team_names) && is_array($team_descriptions)) {
                    for ($i = 0; $i < count($team_keys); $i++) {
                        if (!empty($team_keys[$i]) && !empty($team_names[$i])) {
                            $teams_data[$team_keys[$i]] = array(
                                'name' => sanitize_text_field($team_names[$i]),
                                'description' => sanitize_textarea_field($team_descriptions[$i])
                            );
                        }
                    }
                }
                update_option('claws_teams', $teams_data);
            }
            
            // Task notification template
            if (isset($_POST['task_notification_template'])) {
                update_option('claws_task_notification_template', wp_kses_post($_POST['task_notification_template']));
            }
            
            // Event notification templates
            if (isset($_POST['event_created_template'])) {
                update_option('claws_event_created_template', wp_kses_post($_POST['event_created_template']));
            }
            
            if (isset($_POST['spot_reserved_template'])) {
                update_option('claws_spot_reserved_template', wp_kses_post($_POST['spot_reserved_template']));
            }
            
            if (isset($_POST['reservation_declined_template'])) {
                update_option('claws_reservation_declined_template', wp_kses_post($_POST['reservation_declined_template']));
            }
            
            if (isset($_POST['ai_confidence_threshold'])) {
                $confidence = floatval($_POST['ai_confidence_threshold']);
                if ($confidence >= 0.1 && $confidence <= 1.0) {
                    update_option('claws_ai_confidence_threshold', $confidence);
                }
            }
            
            if (isset($_POST['ai_fallback'])) {
                update_option('claws_ai_fallback', sanitize_text_field($_POST['ai_fallback']));
            }
            
            echo '<div class="notice notice-success"><p>' . __('Settings saved successfully!', 'claws') . '</p></div>';
        }
        
        $default_location = get_option('claws_default_location', 'Lebanon, VA');
        
        // New branding options
        $organization_name = get_option('claws_organization_name', 'Purralytics');
        $organization_tagline = get_option('claws_organization_tagline', 'Where Data Meets Compassion');
        
        // Color scheme options
        $color_scheme_type = get_option('claws_color_scheme_type', 'gradient');
        $primary_color = get_option('claws_primary_color', '#C1292E');
        $secondary_color = get_option('claws_secondary_color', '#00274D');
        
        // Map coordinates  
        $default_latitude = get_option('claws_default_latitude', 39.8283);  // US center default
        $default_longitude = get_option('claws_default_longitude', -98.5795);
        
        // Zapier integration settings
        $zapier_enabled = get_option('claws_zapier_enabled', 0);
        $zapier_webhook_url = get_option('claws_zapier_webhook_url', '');
        $zapier_events = get_option('claws_zapier_events', array());
        
        // AI integration settings
        $ai_enabled = get_option('claws_ai_enabled', 0);
        $ai_provider = get_option('claws_ai_provider', '');
        $ai_api_key = get_option('claws_ai_api_key', '');
        $ai_custom_url = get_option('claws_ai_custom_url', '');
        $ai_confidence_threshold = get_option('claws_ai_confidence_threshold', 0.7);
        $ai_fallback = get_option('claws_ai_fallback', 'mock');
        
        // Advanced feature visibility settings
        $enable_neonate_feeding = get_option('claws_enable_neonate_feeding', 0);
        
        // Colony help options
        $colony_help_options = get_option('claws_colony_help_options', array(
            'traps' => array('label' => 'Traps or other equipment', 'email' => ''),
            'trapping' => array('label' => 'Trapping', 'email' => ''),
            'appointments' => array('label' => 'Spay/neuter appointments', 'email' => ''),
            'food' => array('label' => 'Cat food', 'email' => ''),
            'caretaking' => array('label' => 'Caretaking assistance', 'email' => ''),
            'shelters' => array('label' => 'Winter shelters', 'email' => '')
        ));
        $colony_help_email_template = get_option('claws_colony_help_email_template', '{{username}} has requested assistance with {{help_type}}. Please contact {{username}} at {{contact_info}}');
        
        // Volunteer opportunity settings (always set to editors only)
        $opportunity_creation_level = 'editors';
        $opportunity_categories = get_option('claws_opportunity_categories', array(
            'colony-feeding' => 'Colony Care - Feeding Assistance',
            'colony-shelter' => 'Colony Care - Winter Shelter Builds',
            'colony-safety' => 'Colony Care - Improve Safety',
            'tnr-party' => 'TNR Party',
            'education' => 'Education'
        ));
        
        // Task types for completed task submissions
        $task_types = get_option('claws_task_types', array(
            'administrative' => 'Administrative Work',
            'outreach' => 'Community Outreach',
            'fundraising' => 'Fundraising',
            'education' => 'Education/Training',
            'tnr' => 'TNR Activities',
            'transport' => 'Animal Transport',
            'foster' => 'Foster Care',
            'maintenance' => 'Equipment/Facility Maintenance',
            'event' => 'Event Support',
            'other' => 'Other'
        ));
        
        // Volunteer teams based on task types
        $teams = get_option('claws_teams', array(
            'feeding' => array(
                'name' => 'Feeding',
                'description' => 'Colony feeding, water stations, and food distribution activities'
            ),
            'shelter-builds' => array(
                'name' => 'Shelter Builds',
                'description' => 'Building and maintaining winter shelters for colony cats'
            ),
            'education' => array(
                'name' => 'Education',
                'description' => 'Community outreach, training, and educational programs'
            ),
            'administration' => array(
                'name' => 'Administration',
                'description' => 'Administrative support, data entry, and organizational tasks'
            )
        ));
        
        ?>
        <div class="wrap">
            <h1><?php _e('Purralytics Settings', 'claws'); ?></h1>
            
            <!-- Tab Navigation -->
            <h2 class="nav-tab-wrapper">
                <a href="#general" class="nav-tab nav-tab-active" id="general-tab"><?php _e('General', 'claws'); ?></a>
                <a href="#colony" class="nav-tab" id="colony-tab"><?php _e('Colony', 'claws'); ?></a>
                <a href="#volunteer" class="nav-tab" id="volunteer-tab"><?php _e('Volunteer', 'claws'); ?></a>
            </h2>
            
            <!-- General Tab -->
            <div id="general-content" class="tab-content">
                <form method="post" action="">
                    <?php wp_nonce_field('claws_settings', 'claws_settings_nonce'); ?>
                
                <h2><?php _e('Organization Branding', 'claws'); ?></h2>
                <table class="form-table">
                    <tr>
                        <th scope="row"><?php _e('Organization Name', 'claws'); ?></th>
                        <td>
                            <input type="text" name="organization_name" value="<?php echo esc_attr($organization_name); ?>" class="regular-text" />
                            <p class="description"><?php _e('Your organization name (will replace "Purralytics" throughout the application)', 'claws'); ?></p>
                        </td>
                    </tr>
                    
                    <tr>
                        <th scope="row"><?php _e('Organization Tagline', 'claws'); ?></th>
                        <td>
                            <input type="text" name="organization_tagline" value="<?php echo esc_attr($organization_tagline); ?>" class="large-text" />
                            <p class="description"><?php _e('Your organization tagline or mission statement', 'claws'); ?></p>
                        </td>
                    </tr>
                    
                    <tr>
                        <th scope="row"><?php _e('Organization Logo', 'claws'); ?></th>
                        <td>
                            <?php
                            $logo_id = get_option('claws_organization_logo', 0);
                            $logo_url = $logo_id ? wp_get_attachment_url($logo_id) : '';
                            ?>
                            <div id="logo-upload-container">
                                <div id="logo-preview" style="margin-bottom: 10px;">
                                    <?php if ($logo_url): ?>
                                        <img src="<?php echo esc_url($logo_url); ?>" style="max-width: 60px; max-height: 60px; border-radius: 50%; border: 2px solid #ddd; display: block;" id="logo-preview-img" />
                                        <p style="margin: 5px 0 0; font-size: 12px; color: #666;">Current logo</p>
                                    <?php else: ?>
                                        <div style="width: 60px; height: 60px; background: #f0f0f0; border-radius: 50%; display: flex; align-items: center; justify-content: center; border: 2px solid #ddd;" id="logo-placeholder">
                                            <span style="color: #999; font-size: 24px;">❤</span>
                                        </div>
                                        <p style="margin: 5px 0 0; font-size: 12px; color: #666;">Default heart icon</p>
                                    <?php endif; ?>
                                </div>
                                
                                <input type="hidden" name="organization_logo" id="organization_logo" value="<?php echo esc_attr($logo_id); ?>" />
                                <button type="button" id="upload-logo-btn" class="button"><?php _e('Upload Logo', 'claws'); ?></button>
                                <?php if ($logo_url): ?>
                                    <button type="button" id="remove-logo-btn" class="button" style="margin-left: 10px;"><?php _e('Remove Logo', 'claws'); ?></button>
                                <?php endif; ?>
                            </div>
                            <p class="description"><?php _e('Upload a small logo image to replace the heart icon in the app header. Recommended size: 60x60 pixels. The image will be automatically cropped to a circle.', 'claws'); ?></p>
                        </td>
                    </tr>
                </table>
                
                <h2><?php _e('Color Scheme', 'claws'); ?></h2>
                <table class="form-table">
                    <tr>
                        <th scope="row"><?php _e('Color Scheme Type', 'claws'); ?></th>
                        <td>
                            <label>
                                <input type="radio" name="color_scheme_type" value="gradient" <?php checked($color_scheme_type, 'gradient'); ?> /> 
                                <?php _e('Gradient (two colors)', 'claws'); ?>
                            </label><br>
                            <label>
                                <input type="radio" name="color_scheme_type" value="solid" <?php checked($color_scheme_type, 'solid'); ?> /> 
                                <?php _e('Solid color (one color)', 'claws'); ?>
                            </label>
                            <p class="description"><?php _e('Choose whether to use a gradient background or a solid color for your app header.', 'claws'); ?></p>
                        </td>
                    </tr>
                    
                    <tr>
                        <th scope="row"><?php _e('Primary Color', 'claws'); ?></th>
                        <td>
                            <input type="color" name="primary_color" value="<?php echo esc_attr($primary_color); ?>" />
                            <input type="text" name="primary_color_text" value="<?php echo esc_attr($primary_color); ?>" class="regular-text" style="margin-left: 10px;" readonly />
                            <p class="description"><?php _e('Primary color (left side of gradient, or the solid color if using solid scheme)', 'claws'); ?></p>
                        </td>
                    </tr>
                    
                    <tr id="secondary-color-row">
                        <th scope="row"><?php _e('Secondary Color', 'claws'); ?></th>
                        <td>
                            <input type="color" name="secondary_color" value="<?php echo esc_attr($secondary_color); ?>" />
                            <input type="text" name="secondary_color_text" value="<?php echo esc_attr($secondary_color); ?>" class="regular-text" style="margin-left: 10px;" readonly />
                            <p class="description"><?php _e('Secondary color (right side of gradient, ignored for solid color scheme)', 'claws'); ?></p>
                        </td>
                    </tr>
                    
                    <tr>
                        <th scope="row"><?php _e('Header Text Color', 'claws'); ?></th>
                        <td>
                            <?php $header_text_color = get_option('claws_header_text_color', 'white'); ?>
                            <label style="margin-right: 20px;">
                                <input type="radio" name="header_text_color" value="white" <?php checked($header_text_color, 'white'); ?> style="margin-right: 5px;" />
                                <?php _e('White Text', 'claws'); ?>
                            </label>
                            <label>
                                <input type="radio" name="header_text_color" value="black" <?php checked($header_text_color, 'black'); ?> style="margin-right: 5px;" />
                                <?php _e('Black Text', 'claws'); ?>
                            </label>
                            <p class="description"><?php _e('Choose white or black text for optimal contrast with your header colors.', 'claws'); ?></p>
                        </td>
                    </tr>
                    
                    <tr>
                        <th scope="row"><?php _e('Preview', 'claws'); ?></th>
                        <td>
                            <div id="color-preview" style="height: 60px; border-radius: 8px; display: flex; align-items: center; justify-content: center; color: <?php echo esc_attr(get_option('claws_header_text_color', 'white')); ?>; font-weight: bold; margin-bottom: 10px; background: linear-gradient(to right, <?php echo esc_attr($primary_color); ?>, <?php echo esc_attr($secondary_color); ?>);">
                                <?php echo esc_html($organization_name); ?> Header Preview
                            </div>
                            <p class="description"><?php _e('Live preview of how your header will look with the selected colors.', 'claws'); ?></p>
                        </td>
                    </tr>
                </table>
                
                <h2><?php _e('Map Settings', 'claws'); ?></h2>
                <table class="form-table">
                    <tr>
                        <th scope="row"><?php _e('Default Map Center', 'claws'); ?></th>
                        <td>
                            <div style="margin-bottom: 15px;">
                                <input type="text" name="default_location" value="<?php echo esc_attr($default_location); ?>" class="regular-text" placeholder="Search for your location..." />
                                <button type="button" id="search-location-btn" class="button" style="margin-left: 10px;"><?php _e('Search', 'claws'); ?></button>
                                <p class="description"><?php _e('Enter your location name for geocoding, or use the map below to set precise coordinates.', 'claws'); ?></p>
                            </div>
                            
                            <div id="settings-map" style="height: 400px; width: 100%; border: 1px solid #ddd; margin-bottom: 15px;"></div>
                            
                            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 15px;">
                                <div>
                                    <label><strong><?php _e('Latitude:', 'claws'); ?></strong></label>
                                    <input type="number" name="default_latitude" id="default_latitude" value="<?php echo esc_attr($default_latitude); ?>" step="0.0001" class="regular-text" readonly />
                                </div>
                                <div>
                                    <label><strong><?php _e('Longitude:', 'claws'); ?></strong></label>
                                    <input type="number" name="default_longitude" id="default_longitude" value="<?php echo esc_attr($default_longitude); ?>" step="0.0001" class="regular-text" readonly />
                                </div>
                            </div>
                            
                            <button type="button" id="set-default-location-btn" class="button button-primary">
                                <?php _e('📍 Set This as Default Map Center', 'claws'); ?>
                            </button>
                            
                            <p class="description" style="margin-top: 10px;">
                                <?php _e('Click anywhere on the map to move the red marker to that location, or drag the marker for precise positioning. Navigate by zooming and panning, then click "Set This as Default Map Center" when you find your desired location.', 'claws'); ?>
                            </p>
                        </td>
                    </tr>
                    
                    
                </table>
                
                <h2><?php _e('Zapier Integration', 'claws'); ?></h2>
                <table class="form-table">
                    <tr>
                        <th scope="row"><?php _e('Enable Zapier Integration', 'claws'); ?></th>
                        <td>
                            <label>
                                <input type="checkbox" name="zapier_enabled" value="1" <?php checked($zapier_enabled, 1); ?> />
                                <?php _e('Enable webhook triggers for Zapier automation', 'claws'); ?>
                            </label>
                            <p class="description">
                                <?php _e('When enabled, Purralytics will send data to your Zapier webhook URL when specific events occur.', 'claws'); ?>
                            </p>
                        </td>
                    </tr>
                    
                    <tr>
                        <th scope="row"><?php _e('Zapier Webhook URL', 'claws'); ?></th>
                        <td>
                            <input type="url" name="zapier_webhook_url" value="<?php echo esc_attr($zapier_webhook_url); ?>" class="large-text" placeholder="https://hooks.zapier.com/hooks/catch/..." />
                            <p class="description">
                                <?php _e('Get this URL from your Zapier "Webhooks by Zapier" trigger. It should start with https://hooks.zapier.com/hooks/catch/', 'claws'); ?>
                                <br><a href="https://zapier.com/apps/webhook/help" target="_blank"><?php _e('Learn how to create a webhook in Zapier →', 'claws'); ?></a>
                            </p>
                        </td>
                    </tr>
                    
                    <tr>
                        <th scope="row"><?php _e('Trigger Events', 'claws'); ?></th>
                        <td>
                            <fieldset>
                                <label>
                                    <input type="checkbox" name="zapier_trigger_intake" value="1" <?php checked(in_array('intake', $zapier_events)); ?> />
                                    <?php _e('New Cat Intake', 'claws'); ?>
                                </label><br>
                                
                                <label>
                                    <input type="checkbox" name="zapier_trigger_discharge" value="1" <?php checked(in_array('discharge', $zapier_events)); ?> />
                                    <?php _e('Cat Discharge/Outcome', 'claws'); ?>
                                </label><br>
                                
                                <label>
                                    <input type="checkbox" name="zapier_trigger_colony" value="1" <?php checked(in_array('colony', $zapier_events)); ?> />
                                    <?php _e('New Colony Added', 'claws'); ?>
                                </label>
                            </fieldset>
                            <p class="description">
                                <?php _e('Select which events should trigger webhook notifications to Zapier.', 'claws'); ?>
                            </p>
                        </td>
                    </tr>
                    
                    <tr>
                        <th scope="row"><?php _e('Test Integration', 'claws'); ?></th>
                        <td>
                            <button type="button" id="test-zapier-webhook" class="button button-secondary" onclick="testZapierWebhook()">
                                <?php _e('Send Test Data to Zapier', 'claws'); ?>
                            </button>
                            <p class="description">
                                <?php _e('Send a test payload to verify your webhook URL is working correctly.', 'claws'); ?>
                            </p>
                            <div id="zapier-test-result" style="margin-top: 10px;"></div>
                        </td>
                    </tr>
                </table>
                
                <h2><?php _e('AI Integration', 'claws'); ?></h2>
                <table class="form-table">
                    <tr>
                        <th scope="row"><?php _e('Enable AI Photo Analysis', 'claws'); ?></th>
                        <td>
                            <label>
                                <input type="checkbox" name="ai_enabled" value="1" <?php checked($ai_enabled, 1); ?> />
                                <?php _e('Enable AI-powered coat and color detection for intake photos', 'claws'); ?>
                            </label>
                            <p class="description">
                                <?php _e('When enabled, users can upload cat photos and get AI suggestions for coat type and color during intake.', 'claws'); ?>
                            </p>
                        </td>
                    </tr>
                    
                    <tr>
                        <th scope="row"><?php _e('AI Service Provider', 'claws'); ?></th>
                        <td>
                            <select name="ai_provider" id="ai_provider" onchange="toggleAISettings()">
                                <option value=""><?php _e('Select AI Service', 'claws'); ?></option>
                                <option value="nyckel" <?php selected($ai_provider, 'nyckel'); ?>>Nyckel (Cat Breed Detection)</option>
                                <option value="siwalu" <?php selected($ai_provider, 'siwalu'); ?>>Siwalu (Animal Breed Recognition)</option>
                                <option value="vision" <?php selected($ai_provider, 'vision'); ?>>Google Vision API</option>
                                <option value="custom" <?php selected($ai_provider, 'custom'); ?>>Custom API Endpoint</option>
                            </select>
                            <p class="description">
                                <?php _e('Choose your preferred AI service for photo analysis. Each service has different capabilities and pricing.', 'claws'); ?>
                            </p>
                        </td>
                    </tr>
                    
                    <tr id="ai-api-key-row" style="<?php echo empty($ai_provider) ? 'display: none;' : ''; ?>">
                        <th scope="row"><?php _e('API Key', 'claws'); ?></th>
                        <td>
                            <input type="password" name="ai_api_key" value="<?php echo esc_attr($ai_api_key); ?>" class="large-text" placeholder="Enter your API key..." />
                            <button type="button" onclick="togglePasswordVisibility('ai_api_key')" class="button button-secondary" style="margin-left: 5px;">👁️</button>
                            <p class="description" id="ai-key-description">
                                <span id="nyckel-desc" style="display: none;">Get your API key from <a href="https://www.nyckel.com/" target="_blank">Nyckel Dashboard</a>. Format: nyckel_xxxxx</span>
                                <span id="siwalu-desc" style="display: none;">Get your API key from <a href="https://siwalusoftware.com/business/api/" target="_blank">Siwalu Business API</a>.</span>
                                <span id="vision-desc" style="display: none;">Get your API key from <a href="https://cloud.google.com/vision/docs/setup" target="_blank">Google Cloud Console</a>.</span>
                                <span id="custom-desc" style="display: none;">Enter the API key required by your custom endpoint.</span>
                            </p>
                        </td>
                    </tr>
                    
                    <tr id="ai-custom-url-row" style="display: none;">
                        <th scope="row"><?php _e('Custom API Endpoint', 'claws'); ?></th>
                        <td>
                            <input type="url" name="ai_custom_url" value="<?php echo esc_attr($ai_custom_url); ?>" class="large-text" placeholder="https://your-api.com/analyze" />
                            <p class="description">
                                <?php _e('URL for your custom AI service. Should accept POST requests with image data and return coat/color information.', 'claws'); ?>
                            </p>
                        </td>
                    </tr>
                    
                    <tr id="ai-confidence-row" style="<?php echo empty($ai_provider) ? 'display: none;' : ''; ?>">
                        <th scope="row"><?php _e('Confidence Threshold', 'claws'); ?></th>
                        <td>
                            <input type="range" name="ai_confidence_threshold" value="<?php echo esc_attr($ai_confidence_threshold); ?>" min="0.1" max="1.0" step="0.1" oninput="updateConfidenceValue(this.value)" />
                            <span id="confidence-value"><?php echo esc_attr($ai_confidence_threshold * 100); ?>%</span>
                            <p class="description">
                                <?php _e('Minimum confidence level required for AI suggestions. Lower values = more suggestions but potentially less accurate.', 'claws'); ?>
                            </p>
                        </td>
                    </tr>
                    
                    <tr id="ai-test-row" style="<?php echo empty($ai_provider) ? 'display: none;' : ''; ?>">
                        <th scope="row"><?php _e('Test AI Integration', 'claws'); ?></th>
                        <td>
                            <button type="button" id="test-ai-service" class="button button-secondary" onclick="testAIService()">
                                <?php _e('Test AI Service', 'claws'); ?>
                            </button>
                            <p class="description">
                                <?php _e('Test your AI configuration with a sample cat image to verify the integration is working.', 'claws'); ?>
                            </p>
                            <div id="ai-test-result" style="margin-top: 10px;"></div>
                        </td>
                    </tr>
                    
                    <tr>
                        <th scope="row"><?php _e('Fallback Behavior', 'claws'); ?></th>
                        <td>
                            <fieldset>
                                <label>
                                    <input type="radio" name="ai_fallback" value="disable" <?php checked($ai_fallback, 'disable'); ?> />
                                    <?php _e('Disable AI button if service unavailable', 'claws'); ?>
                                </label><br>
                                
                                <label>
                                    <input type="radio" name="ai_fallback" value="mock" <?php checked($ai_fallback, 'mock'); ?> />
                                    <?php _e('Use mock suggestions if service unavailable', 'claws'); ?>
                                </label><br>
                                
                                <label>
                                    <input type="radio" name="ai_fallback" value="manual" <?php checked($ai_fallback, 'manual'); ?> />
                                    <?php _e('Show manual input prompt if service unavailable', 'claws'); ?>
                                </label>
                            </fieldset>
                            <p class="description">
                                <?php _e('Choose what happens when the AI service is unavailable or returns an error.', 'claws'); ?>
                            </p>
                        </td>
                    </tr>
                </table>
                
                <h2><?php _e('Advanced Feature Visibility', 'claws'); ?></h2>
                <table class="form-table">
                    <tr>
                        <th scope="row"><?php _e('Neonate Feeding Tab', 'claws'); ?></th>
                        <td>
                            <label>
                                <input type="checkbox" name="enable_neonate_feeding" value="1" <?php checked($enable_neonate_feeding, 1); ?> />
                                <?php _e('Show Neonate Care tab in the application', 'claws'); ?>
                            </label>
                            <p class="description">
                                <?php _e('When enabled, users will see a "NeoNate Care" tab for tracking feeding records and kitten care. This feature is hidden by default as not all organizations need detailed neonate tracking.', 'claws'); ?>
                            </p>
                        </td>
                    </tr>
                </table>
                
                <?php submit_button(__('Save General Settings', 'claws')); ?>
                <p class="description" style="margin-top: -10px; font-style: italic; color: #666;">
                    <?php _e('Save any changes to this tab before switching to any other tab!', 'claws'); ?>
                </p>
                </form>
            </div>
            
            <!-- Colony Tab -->
            <div id="colony-content" class="tab-content" style="display: none;">
                <form method="post" action="">
                    <?php wp_nonce_field('claws_settings', 'claws_settings_nonce'); ?>
                
                <h2><?php _e('Colony Help Options', 'claws'); ?></h2>
                <p><?php _e('Configure the help options available in the "Colony Help: I need assistance with" section of the colony form.', 'claws'); ?></p>
                
                <div id="colony-help-options-container">
                    <input type="hidden" name="colony_help_options" value="1" />
                    <?php $index = 0; foreach ($colony_help_options as $key => $option): ?>
                    <div class="colony-help-option" style="margin-bottom: 15px; padding: 15px; border: 1px solid #ddd; border-radius: 5px; background: #f9f9f9;">
                        <table class="form-table" style="margin: 0;">
                            <tr>
                                <th style="width: 120px;"><?php _e('Key', 'claws'); ?></th>
                                <td>
                                    <input type="text" name="colony_help_option_keys[]" value="<?php echo esc_attr($key); ?>" class="regular-text" placeholder="unique_key" />
                                    <p class="description"><?php _e('Unique identifier (no spaces, lowercase)', 'claws'); ?></p>
                                </td>
                            </tr>
                            <tr>
                                <th><?php _e('Label', 'claws'); ?></th>
                                <td>
                                    <input type="text" name="colony_help_option_labels[]" value="<?php echo esc_attr($option['label']); ?>" class="regular-text" placeholder="Option display text" />
                                    <p class="description"><?php _e('Text shown to users', 'claws'); ?></p>
                                </td>
                            </tr>
                            <tr>
                                <th><?php _e('Email', 'claws'); ?></th>
                                <td>
                                    <input type="email" name="colony_help_option_emails[]" value="<?php echo esc_attr($option['email']); ?>" class="regular-text" placeholder="help@example.com" />
                                    <p class="description"><?php _e('Email address to receive help requests for this option', 'claws'); ?></p>
                                </td>
                            </tr>
                        </table>
                        <button type="button" class="button remove-help-option" style="margin-top: 10px; color: #a00;"><?php _e('Remove Option', 'claws'); ?></button>
                    </div>
                    <?php $index++; endforeach; ?>
                </div>
                
                <button type="button" id="add-help-option" class="button"><?php _e('Add New Help Option', 'claws'); ?></button>
                
                <table class="form-table" style="margin-top: 20px;">
                    <tr>
                        <th scope="row"><?php _e('Email Template', 'claws'); ?></th>
                        <td>
                            <textarea name="colony_help_email_template" rows="4" cols="50" class="large-text"><?php echo esc_textarea($colony_help_email_template); ?></textarea>
                            <p class="description">
                                <?php _e('Email template for help requests. Available placeholders: {{username}}, {{help_type}}, {{contact_info}}, {{colony_name}}, {{colony_location}}', 'claws'); ?>
                            </p>
                        </td>
                    </tr>
                </table>
                
                <?php submit_button(__('Save Colony Settings', 'claws')); ?>
                <p class="description" style="margin-top: -10px; font-style: italic; color: #666;">
                    <?php _e('Save any changes to this tab before switching to any other tab!', 'claws'); ?>
                </p>
                </form>
            </div>
            
            <!-- Volunteer Tab -->
            <div id="volunteer-content" class="tab-content" style="display: none;">
                <form method="post" action="">
                    <?php wp_nonce_field('claws_settings', 'claws_settings_nonce'); ?>
                
                <h2><?php _e('Task/Event/Project Management', 'claws'); ?></h2>
                <p><?php _e('Configure the unified task, event, and project types used throughout the volunteer system. These types are used for tasks, events, and automatic team assignment.', 'claws'); ?></p>
                
                <table class="form-table">
                    <tr>
                        <th scope="row"><?php _e('Task/Event/Project Types', 'claws'); ?></th>
                        <td>
                            <div id="unified-types-container">
                                <input type="hidden" name="unified_types" value="1" />
                                <?php 
                                // Get unified types - merge task types and opportunity categories
                                $unified_types = array_merge($task_types, $opportunity_categories);
                                foreach ($unified_types as $key => $label): 
                                ?>
                                <div class="unified-type" style="margin-bottom: 15px; padding: 15px; border: 1px solid #ddd; border-radius: 5px; background: #f9f9f9;">
                                    <table class="form-table" style="margin: 0;">
                                        <tr>
                                            <th style="width: 120px;"><?php _e('Key', 'claws'); ?></th>
                                            <td>
                                                <input type="text" name="unified_type_keys[]" value="<?php echo esc_attr($key); ?>" class="regular-text" placeholder="unique-key" />
                                                <p class="description"><?php _e('Unique identifier (no spaces, use hyphens)', 'claws'); ?></p>
                                            </td>
                                        </tr>
                                        <tr>
                                            <th><?php _e('Label', 'claws'); ?></th>
                                            <td>
                                                <input type="text" name="unified_type_labels[]" value="<?php echo esc_attr($label); ?>" class="regular-text" placeholder="Type display name" />
                                                <p class="description"><?php _e('Text shown to volunteers in dropdowns', 'claws'); ?></p>
                                            </td>
                                        </tr>
                                        <tr>
                                            <th><?php _e('Requires Colony', 'claws'); ?></th>
                                            <td>
                                                <label>
                                                    <input type="checkbox" name="unified_type_colony_required[]" value="<?php echo esc_attr($key); ?>" <?php checked(strpos($key, 'colony-') === 0); ?> />
                                                    <?php _e('This type requires colony selection', 'claws'); ?>
                                                </label>
                                                <p class="description"><?php _e('Check if this type should show colony selection dropdown', 'claws'); ?></p>
                                            </td>
                                        </tr>
                                    </table>
                                    <button type="button" class="button remove-unified-type" style="margin-top: 10px; color: #a00;"><?php _e('Remove Type', 'claws'); ?></button>
                                </div>
                                <?php endforeach; ?>
                            </div>
                            
                            <button type="button" id="add-unified-type" class="button"><?php _e('Add New Type', 'claws'); ?></button>
                            <p class="description" style="margin-top: 10px;">
                                <?php _e('Configure the types available for tasks, events, and team assignments. These appear in all volunteer forms and determine team membership.', 'claws'); ?>
                            </p>
                        </td>
                    </tr>
                </table>
                </table>
                
                <h2><?php _e('Task Notification Templates', 'claws'); ?></h2>
                <p><?php _e('Configure email templates for volunteer task notifications.', 'claws'); ?></p>
                
                <table class="form-table">
                    <tr>
                        <th scope="row"><?php _e('Completed Task Notification Template', 'claws'); ?></th>
                        <td>
                            <textarea name="task_notification_template" rows="4" cols="50" class="large-text"><?php echo esc_textarea(get_option('claws_task_notification_template', '{{coordinator_name}}, you have a new completed task to review and approve. Please log in at your earliest convenience.')); ?></textarea>
                            <p class="description">
                                <?php _e('Email template sent to coordinators when volunteers submit completed tasks. Available placeholders: {{coordinator_name}}, {{volunteer_name}}, {{task_type}}, {{task_date}}, {{task_description}}', 'claws'); ?>
                            </p>
                        </td>
                    </tr>
                </table>
                
                <h2><?php _e('Event/Project Notification Templates', 'claws'); ?></h2>
                <p><?php _e('Configure email templates for volunteer event and project notifications.', 'claws'); ?></p>
                
                <table class="claws-form-table">
                    <tr>
                        <th scope="row"><?php _e('New Opportunity Created Template', 'claws'); ?></th>
                        <td>
                            <textarea name="event_created_template" rows="6" cols="50" class="large-text"><?php echo esc_textarea(get_option('claws_event_created_template', 'Hi {{volunteer_name}},

A new volunteer opportunity has been created!

Opportunity: {{event_name}}
Date: {{event_date}}
Time: {{event_time}}

Log in to view full details and sign up:
{{app_url}}

Thank you for being part of our volunteer community!')); ?></textarea>
                            <p class="description">
                                <?php _e('Email sent to ALL volunteers when a new event or project is created. Available placeholders: {{volunteer_name}}, {{event_name}}, {{event_date}}, {{event_time}}, {{coordinator_name}}, {{app_url}}, {{site_name}}', 'claws'); ?>
                            </p>
                        </td>
                    </tr>
                    
                    <tr>
                        <th scope="row"><?php _e('Spot Reserved Template', 'claws'); ?></th>
                        <td>
                            <textarea name="spot_reserved_template" rows="8" cols="50" class="large-text"><?php echo esc_textarea(get_option('claws_spot_reserved_template', 'Hi {{volunteer_name}},

A spot has been reserved for you on {{event_name}}.

Event Details:
- Event: {{event_name}}
- Date: {{event_date}}
- Time: {{event_time}}
- Coordinator: {{coordinator_name}}

Please log in to confirm your attendance or decline if you\'re unable to participate:
{{app_url}}

If you need to decline, you can provide a note explaining why, which will be sent to the event coordinator.

Thank you for volunteering!')); ?></textarea>
                            <p class="description">
                                <?php _e('Email sent to specific volunteers when a spot is reserved for them. Available placeholders: {{volunteer_name}}, {{event_name}}, {{event_date}}, {{event_time}}, {{coordinator_name}}, {{app_url}}, {{site_name}}', 'claws'); ?>
                            </p>
                        </td>
                    </tr>
                    
                    <tr>
                        <th scope="row"><?php _e('Reservation Declined Template', 'claws'); ?></th>
                        <td>
                            <textarea name="reservation_declined_template" rows="6" cols="50" class="large-text"><?php echo esc_textarea(get_option('claws_reservation_declined_template', 'Hi {{coordinator_name}},

{{volunteer_name}} has declined their reserved spot for {{event_name}}.

{{decline_note}}

The spot is now available for other volunteers to sign up.

Thank you,
{{site_name}}')); ?></textarea>
                            <p class="description">
                                <?php _e('Email sent to event coordinator when a volunteer declines their reserved spot. Available placeholders: {{coordinator_name}}, {{volunteer_name}}, {{event_name}}, {{decline_note}}, {{site_name}}', 'claws'); ?>
                            </p>
                        </td>
                    </tr>
                </table>
                
                <?php submit_button(__('Save Volunteer Settings', 'claws')); ?>
                <p class="description" style="margin-top: -10px; font-style: italic; color: #666;">
                    <?php _e('Save any changes to this tab before switching to any other tab!', 'claws'); ?>
                </p>
                </form>
            </div>
        </div>
        
        <script>
        let settingsMap;
        let settingsMarker;
        
        document.addEventListener('DOMContentLoaded', function() {
            // Wait a moment for CSS to load
            setTimeout(function() {
                // Initialize the map
                initializeSettingsMap();
                
                // Initialize color pickers
                initializeColorPickers();
                
                // Initialize logo uploader
                initializeLogoUploader();
                
                // Handle search button
                const searchBtn = document.getElementById('search-location-btn');
                if (searchBtn) {
                    searchBtn.addEventListener('click', searchLocation);
                }
                
                // Handle set location button
                const setBtn = document.getElementById('set-default-location-btn');
                if (setBtn) {
                    setBtn.addEventListener('click', setDefaultLocation);
                }
                
                // Initialize colony help options management
                initializeColonyHelpOptions();
                
                // Initialize opportunity categories management
                initializeOpportunityCategoriesManagement();
                
                // Initialize task types management
                initializeTaskTypesManagement();
                
                // Initialize teams management
                initializeTeamsManagement();
            }, 250);
        });
        
        function initializeColonyHelpOptions() {
            // Add new help option
            document.getElementById('add-help-option').addEventListener('click', function() {
                const container = document.getElementById('colony-help-options-container');
                const newOption = document.createElement('div');
                newOption.className = 'colony-help-option';
                newOption.style.cssText = 'margin-bottom: 15px; padding: 15px; border: 1px solid #ddd; border-radius: 5px; background: #f9f9f9;';
                newOption.innerHTML = `
                    <table class="form-table" style="margin: 0;">
                        <tr>
                            <th style="width: 120px;">Key</th>
                            <td>
                                <input type="text" name="colony_help_option_keys[]" value="" class="regular-text" placeholder="unique_key" />
                                <p class="description">Unique identifier (no spaces, lowercase)</p>
                            </td>
                        </tr>
                        <tr>
                            <th>Label</th>
                            <td>
                                <input type="text" name="colony_help_option_labels[]" value="" class="regular-text" placeholder="Option display text" />
                                <p class="description">Text shown to users</p>
                            </td>
                        </tr>
                        <tr>
                            <th>Email</th>
                            <td>
                                <input type="email" name="colony_help_option_emails[]" value="" class="regular-text" placeholder="help@example.com" />
                                <p class="description">Email address to receive help requests for this option</p>
                            </td>
                        </tr>
                    </table>
                    <button type="button" class="button remove-help-option" style="margin-top: 10px; color: #a00;">Remove Option</button>
                `;
                container.appendChild(newOption);
                
                // Add remove handler to new option
                newOption.querySelector('.remove-help-option').addEventListener('click', function() {
                    newOption.remove();
                });
            });
            
            // Remove help option handlers
            document.querySelectorAll('.remove-help-option').forEach(function(button) {
                button.addEventListener('click', function() {
                    button.closest('.colony-help-option').remove();
                });
            });
        }
        
        function initializeOpportunityCategoriesManagement() {
            // Add new opportunity category
            const addBtn = document.getElementById('add-opportunity-category');
            if (addBtn) {
                addBtn.addEventListener('click', function() {
                    const container = document.getElementById('opportunity-categories-container');
                    const newCategory = document.createElement('div');
                    newCategory.className = 'opportunity-category';
                    newCategory.style.cssText = 'margin-bottom: 15px; padding: 15px; border: 1px solid #ddd; border-radius: 5px; background: #f9f9f9;';
                    newCategory.innerHTML = `
                        <table class="form-table" style="margin: 0;">
                            <tr>
                                <th style="width: 120px;">Key</th>
                                <td>
                                    <input type="text" name="opportunity_category_keys[]" value="" class="regular-text" placeholder="unique-key" />
                                    <p class="description">Unique identifier (no spaces, use hyphens)</p>
                                </td>
                            </tr>
                            <tr>
                                <th>Label</th>
                                <td>
                                    <input type="text" name="opportunity_category_labels[]" value="" class="regular-text" placeholder="Category display name" />
                                    <p class="description">Text shown to users in the dropdown</p>
                                </td>
                            </tr>
                        </table>
                        <button type="button" class="button remove-category" style="margin-top: 10px; color: #a00;">Remove Category</button>
                    `;
                    container.appendChild(newCategory);
                    
                    // Add remove handler to new category
                    newCategory.querySelector('.remove-category').addEventListener('click', function() {
                        newCategory.remove();
                    });
                });
            }
            
            // Remove category handlers
            document.querySelectorAll('.remove-category').forEach(function(button) {
                button.addEventListener('click', function() {
                    button.closest('.opportunity-category').remove();
                });
            });
        }
        
        function initializeTaskTypesManagement() {
            // Add new task type
            const addBtn = document.getElementById('add-task-type');
            if (addBtn) {
                addBtn.addEventListener('click', function() {
                    const container = document.getElementById('task-types-container');
                    const newTaskType = document.createElement('div');
                    newTaskType.className = 'task-type';
                    newTaskType.style.cssText = 'margin-bottom: 15px; padding: 15px; border: 1px solid #ddd; border-radius: 5px; background: #f9f9f9;';
                    newTaskType.innerHTML = `
                        <table class="form-table" style="margin: 0;">
                            <tr>
                                <th style="width: 120px;">Key</th>
                                <td>
                                    <input type="text" name="task_type_keys[]" value="" class="regular-text" placeholder="unique-key" />
                                    <p class="description">Unique identifier (no spaces, use hyphens)</p>
                                </td>
                            </tr>
                            <tr>
                                <th>Label</th>
                                <td>
                                    <input type="text" name="task_type_labels[]" value="" class="regular-text" placeholder="Task type display name" />
                                    <p class="description">Text shown to volunteers in the dropdown</p>
                                </td>
                            </tr>
                        </table>
                        <button type="button" class="button remove-task-type" style="margin-top: 10px; color: #a00;">Remove Task Type</button>
                    `;
                    container.appendChild(newTaskType);
                    
                    // Add remove handler to new task type
                    newTaskType.querySelector('.remove-task-type').addEventListener('click', function() {
                        newTaskType.remove();
                    });
                });
            }
            
            // Remove task type handlers
            document.querySelectorAll('.remove-task-type').forEach(function(button) {
                button.addEventListener('click', function() {
                    button.closest('.task-type').remove();
                });
            });
        }
        
        function initializeTeamsManagement() {
            // Add new team
            const addBtn = document.getElementById('add-team');
            if (addBtn) {
                addBtn.addEventListener('click', function() {
                    const container = document.getElementById('teams-container');
                    const newTeam = document.createElement('div');
                    newTeam.className = 'team';
                    newTeam.style.cssText = 'margin-bottom: 15px; padding: 15px; border: 1px solid #ddd; border-radius: 5px; background: #f9f9f9;';
                    newTeam.innerHTML = `
                        <table class="form-table" style="margin: 0;">
                            <tr>
                                <th style="width: 120px;">Key</th>
                                <td>
                                    <input type="text" name="team_keys[]" value="" class="regular-text" placeholder="unique-key" />
                                    <p class="description">Unique identifier (no spaces, use hyphens)</p>
                                </td>
                            </tr>
                            <tr>
                                <th>Team Name</th>
                                <td>
                                    <input type="text" name="team_names[]" value="" class="regular-text" placeholder="Team display name" />
                                    <p class="description">Team name shown to volunteers</p>
                                </td>
                            </tr>
                            <tr>
                                <th>Description</th>
                                <td>
                                    <textarea name="team_descriptions[]" rows="2" cols="50" class="regular-text" placeholder="Brief description of team activities"></textarea>
                                    <p class="description">Brief description of what this team does</p>
                                </td>
                            </tr>
                        </table>
                        <button type="button" class="button remove-team" style="margin-top: 10px; color: #a00;">Remove Team</button>
                    `;
                    container.appendChild(newTeam);
                    
                    // Add remove handler to new team
                    newTeam.querySelector('.remove-team').addEventListener('click', function() {
                        newTeam.remove();
                    });
                });
            }
            
            // Remove team handlers
            document.querySelectorAll('.remove-team').forEach(function(button) {
                button.addEventListener('click', function() {
                    button.closest('.team').remove();
                });
            });
        }
        
        function initializeSettingsMap() {
            // Check if Leaflet is loaded
            if (typeof L === 'undefined') {
                console.error('Leaflet is not loaded yet, retrying...');
                setTimeout(initializeSettingsMap, 500);
                return;
            }
            
            // Check if map container exists
            const mapContainer = document.getElementById('settings-map');
            if (!mapContainer) {
                console.error('Map container not found');
                return;
            }
            
            try {
                // Initialize map with current coordinates
                const lat = parseFloat(document.getElementById('default_latitude').value) || 39.8283;
                const lng = parseFloat(document.getElementById('default_longitude').value) || -98.5795;
                
                console.log('Initializing settings map with coordinates:', lat, lng);
                
                settingsMap = L.map('settings-map').setView([lat, lng], 13);
            
            // Add tile layer
            L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                attribution: '© OpenStreetMap contributors'
            }).addTo(settingsMap);
            
            // Add draggable marker
            settingsMarker = L.marker([lat, lng], {
                draggable: true,
                icon: L.icon({
                    iconUrl: 'data:image/svg+xml;base64,' + btoa(`
                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="red" width="30" height="30">
                            <path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z"/>
                        </svg>
                    `),
                    iconSize: [30, 30],
                    iconAnchor: [15, 30]
                })
            }).addTo(settingsMap);
            
                // Update coordinates when marker is dragged
                settingsMarker.on('dragend', function(e) {
                    const position = e.target.getLatLng();
                    document.getElementById('default_latitude').value = position.lat.toFixed(6);
                    document.getElementById('default_longitude').value = position.lng.toFixed(6);
                });
                
                // Add click event to move pin to clicked location
                settingsMap.on('click', function(e) {
                    const lat = e.latlng.lat;
                    const lng = e.latlng.lng;
                    
                    // Move marker to clicked location
                    settingsMarker.setLatLng([lat, lng]);
                    
                    // Update coordinate fields
                    document.getElementById('default_latitude').value = lat.toFixed(6);
                    document.getElementById('default_longitude').value = lng.toFixed(6);
                    
                    console.log('Pin moved to clicked location:', lat, lng);
                });
                
                console.log('Settings map initialized successfully');
                
            } catch (error) {
                console.error('Error initializing settings map:', error);
                // Show error message to user
                const mapContainer = document.getElementById('settings-map');
                if (mapContainer) {
                    mapContainer.innerHTML = '<div style="height: 100%; display: flex; align-items: center; justify-content: center; background: #f3f4f6; border: 1px solid #d1d5db; border-radius: 0.5rem;"><p style="color: #ef4444; text-align: center;">Map failed to load.<br><small>Please refresh the page and try again.</small></p></div>';
                }
            }
        }
        
        function searchLocation() {
            const location = document.querySelector('input[name="default_location"]').value;
            
            if (!location.trim()) {
                alert('Please enter a location to search for.');
                return;
            }
            
            // Use Nominatim geocoding API
            fetch(`https://nominatim.openstreetmap.org/search?format=json&q=${encodeURIComponent(location)}&limit=1`)
                .then(response => response.json())
                .then(data => {
                    if (data && data.length > 0) {
                        const result = data[0];
                        const lat = parseFloat(result.lat);
                        const lng = parseFloat(result.lon);
                        
                        // Update map and marker
                        settingsMap.setView([lat, lng], 13);
                        settingsMarker.setLatLng([lat, lng]);
                        
                        // Update coordinate fields
                        document.getElementById('default_latitude').value = lat.toFixed(6);
                        document.getElementById('default_longitude').value = lng.toFixed(6);
                        
                        // Show success message
                        showLocationMessage('Location found! Drag the marker to fine-tune the position if needed.', 'success');
                    } else {
                        showLocationMessage('Location not found. Please try a different search term.', 'error');
                    }
                })
                .catch(error => {
                    console.error('Geocoding error:', error);
                    showLocationMessage('Error searching for location. Please try again.', 'error');
                });
        }
        
        function setDefaultLocation() {
            const lat = document.getElementById('default_latitude').value;
            const lng = document.getElementById('default_longitude').value;
            
            if (!lat || !lng) {
                alert('Please select a location on the map first.');
                return;
            }
            
            // Show confirmation
            showLocationMessage(`Default map center set to: ${lat}, ${lng}. Click "Save Changes" to apply.`, 'success');
            
            // Scroll to save button
            document.querySelector('.submit').scrollIntoView({ behavior: 'smooth' });
        }
        
        function showLocationMessage(message, type) {
            // Remove any existing messages
            const existingMessages = document.querySelectorAll('.location-message');
            existingMessages.forEach(msg => msg.remove());
            
            // Create new message
            const messageDiv = document.createElement('div');
            messageDiv.className = `notice location-message ${type === 'success' ? 'notice-success' : 'notice-error'}`;
            messageDiv.style.margin = '10px 0';
            messageDiv.innerHTML = `<p><strong>${message}</strong></p>`;
            
            // Insert after the set location button
            const setButton = document.getElementById('set-default-location-btn');
            setButton.parentNode.insertBefore(messageDiv, setButton.nextSibling);
            
            // Auto-remove after 5 seconds
            setTimeout(() => {
                if (messageDiv.parentNode) {
                    messageDiv.remove();
                }
            }, 5000);
        }
        
        function initializeColorPickers() {
            const colorSchemeRadios = document.querySelectorAll('input[name="color_scheme_type"]');
            const primaryColorPicker = document.querySelector('input[name="primary_color"]');
            const primaryColorText = document.querySelector('input[name="primary_color_text"]');
            const secondaryColorPicker = document.querySelector('input[name="secondary_color"]');
            const secondaryColorText = document.querySelector('input[name="secondary_color_text"]');
            const secondaryColorRow = document.getElementById('secondary-color-row');
            const colorPreview = document.getElementById('color-preview');
            const organizationNameInput = document.querySelector('input[name="organization_name"]');
            
            if (!primaryColorPicker || !secondaryColorPicker || !colorPreview) {
                console.log('Color picker elements not found, skipping initialization');
                return;
            }
            
            // Update text field when color picker changes
            if (primaryColorPicker && primaryColorText) {
                primaryColorPicker.addEventListener('input', function() {
                    primaryColorText.value = this.value;
                    updateColorPreview();
                });
            }
            
            if (secondaryColorPicker && secondaryColorText) {
                secondaryColorPicker.addEventListener('input', function() {
                    secondaryColorText.value = this.value;
                    updateColorPreview();
                });
            }
            
            // Handle color scheme type changes
            colorSchemeRadios.forEach(radio => {
                radio.addEventListener('change', function() {
                    toggleSecondaryColorVisibility();
                    updateColorPreview();
                });
            });
            
            // Update preview when organization name changes
            if (organizationNameInput) {
                organizationNameInput.addEventListener('input', updateColorPreview);
            }
            
            // Update preview when text color changes
            const textColorRadios = document.querySelectorAll('input[name="header_text_color"]');
            textColorRadios.forEach(radio => {
                radio.addEventListener('change', updateColorPreview);
            });
            
            // Set initial visibility and preview
            toggleSecondaryColorVisibility();
            updateColorPreview();
            
            function toggleSecondaryColorVisibility() {
                const isGradient = document.querySelector('input[name="color_scheme_type"]:checked')?.value === 'gradient';
                if (secondaryColorRow) {
                    secondaryColorRow.style.display = isGradient ? 'table-row' : 'none';
                }
            }
            
            function updateColorPreview() {
                if (!colorPreview) return;
                
                const colorSchemeType = document.querySelector('input[name="color_scheme_type"]:checked')?.value || 'gradient';
                const primaryColor = primaryColorPicker?.value || '#C1292E';
                const secondaryColor = secondaryColorPicker?.value || '#00274D';
                const textColor = document.querySelector('input[name="header_text_color"]:checked')?.value || 'white';
                const organizationName = organizationNameInput?.value || 'CLAWS';
                
                if (colorSchemeType === 'solid') {
                    colorPreview.style.background = primaryColor;
                } else {
                    colorPreview.style.background = `linear-gradient(to right, ${primaryColor}, ${secondaryColor})`;
                }
                
                colorPreview.style.color = textColor;
                colorPreview.textContent = `${organizationName} Header Preview`;
            }
        }
        
        function initializeLogoUploader() {
            const uploadBtn = document.getElementById('upload-logo-btn');
            const removeBtn = document.getElementById('remove-logo-btn');
            const logoInput = document.getElementById('organization_logo');
            const logoPreview = document.getElementById('logo-preview');
            
            if (!uploadBtn) {
                console.log('Logo upload button not found');
                return;
            }
            
            // Handle logo upload
            uploadBtn.addEventListener('click', function(e) {
                e.preventDefault();
                
                // Create file frame if it doesn't exist
                if (typeof wp !== 'undefined' && wp.media) {
                    const frame = wp.media({
                        title: 'Select Organization Logo',
                        button: {
                            text: 'Use as Logo'
                        },
                        multiple: false,
                        library: {
                            type: 'image'
                        }
                    });
                    
                    frame.on('select', function() {
                        const attachment = frame.state().get('selection').first().toJSON();
                        logoInput.value = attachment.id;
                        updateLogoPreview(attachment.url);
                    });
                    
                    frame.open();
                } else {
                    // Fallback for when WordPress media library isn't available
                    alert('WordPress media library not available. Please refresh the page and try again.');
                }
            });
            
            // Handle logo removal
            if (removeBtn) {
                removeBtn.addEventListener('click', function(e) {
                    e.preventDefault();
                    if (confirm('Are you sure you want to remove the logo?')) {
                        logoInput.value = '';
                        updateLogoPreview('');
                    }
                });
            }
            
            function updateLogoPreview(logoUrl) {
                if (logoUrl) {
                    logoPreview.innerHTML = `
                        <img src="${logoUrl}" style="max-width: 60px; max-height: 60px; border-radius: 50%; border: 2px solid #ddd; display: block;" id="logo-preview-img" />
                        <p style="margin: 5px 0 0; font-size: 12px; color: #666;">New logo (save to apply)</p>
                        <button type="button" id="remove-logo-btn" class="button" style="margin-top: 5px;">Remove Logo</button>
                    `;
                    
                    // Re-attach remove event listener
                    const newRemoveBtn = document.getElementById('remove-logo-btn');
                    if (newRemoveBtn) {
                        newRemoveBtn.addEventListener('click', function(e) {
                            e.preventDefault();
                            if (confirm('Are you sure you want to remove the logo?')) {
                                logoInput.value = '';
                                updateLogoPreview('');
                            }
                        });
                    }
                } else {
                    logoPreview.innerHTML = `
                        <div style="width: 60px; height: 60px; background: #f0f0f0; border-radius: 50%; display: flex; align-items: center; justify-content: center; border: 2px solid #ddd;" id="logo-placeholder">
                            <span style="color: #999; font-size: 24px;">❤</span>
                        </div>
                        <p style="margin: 5px 0 0; font-size: 12px; color: #666;">Default heart icon</p>
                    `;
                }
            }
        }
        
        function testZapierWebhook() {
            const webhookUrl = document.querySelector('input[name="zapier_webhook_url"]').value;
            const resultDiv = document.getElementById('zapier-test-result');
            
            if (!webhookUrl.trim()) {
                resultDiv.innerHTML = '<div style="color: #dc3545; font-weight: bold;">⚠️ Please enter a webhook URL first.</div>';
                return;
            }
            
            // Show loading
            resultDiv.innerHTML = '<div style="color: #007cba;">🔄 Sending test data...</div>';
            
            // Test payload
            const testData = {
                event: 'test',
                timestamp: new Date().toISOString(),
                data: {
                    test_message: 'This is a test from CLAWS',
                    site_url: '<?php echo esc_js(site_url()); ?>',
                    plugin_version: '1.0.0',
                    cat: {
                        name: 'Test Cat',
                        age: 'Adult',
                        gender: 'Male',
                        coat: 'Domestic Short Hair',
                        color: 'Orange tabby',
                        type: 'Stray'
                    },
                    contact: {
                        name: 'Test Contact',
                        email: 'test@example.com',
                        phone: '(555) 123-4567'
                    }
                }
            };
            
            // Send to webhook
            fetch(webhookUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(testData)
            })
            .then(response => {
                if (response.ok) {
                    resultDiv.innerHTML = '<div style="color: #28a745; font-weight: bold;">✅ Test successful! Check your Zapier dashboard for the test data.</div>';
                } else {
                    resultDiv.innerHTML = `<div style="color: #dc3545; font-weight: bold;">❌ Test failed. HTTP ${response.status}: ${response.statusText}</div>`;
                }
            })
            .catch(error => {
                console.error('Webhook test error:', error);
                resultDiv.innerHTML = '<div style="color: #dc3545; font-weight: bold;">❌ Test failed. Please check the webhook URL and try again.</div>';
            });
        }
        
        function toggleAISettings() {
            const provider = document.getElementById('ai_provider').value;
            const apiKeyRow = document.getElementById('ai-api-key-row');
            const customUrlRow = document.getElementById('ai-custom-url-row');
            const confidenceRow = document.getElementById('ai-confidence-row');
            const testRow = document.getElementById('ai-test-row');
            
            // Show/hide rows based on provider selection
            if (provider) {
                apiKeyRow.style.display = 'table-row';
                confidenceRow.style.display = 'table-row';
                testRow.style.display = 'table-row';
                
                if (provider === 'custom') {
                    customUrlRow.style.display = 'table-row';
                } else {
                    customUrlRow.style.display = 'none';
                }
                
                // Show appropriate description
                document.querySelectorAll('#ai-key-description span').forEach(span => {
                    span.style.display = 'none';
                });
                const desc = document.getElementById(provider + '-desc');
                if (desc) {
                    desc.style.display = 'inline';
                }
            } else {
                apiKeyRow.style.display = 'none';
                customUrlRow.style.display = 'none';
                confidenceRow.style.display = 'none';
                testRow.style.display = 'none';
            }
        }
        
        function updateConfidenceValue(value) {
            document.getElementById('confidence-value').textContent = Math.round(value * 100) + '%';
        }
        
        function togglePasswordVisibility(fieldId) {
            const field = document.querySelector('input[name="' + fieldId + '"]');
            const button = event.target;
            
            if (field.type === 'password') {
                field.type = 'text';
                button.textContent = '🙈';
            } else {
                field.type = 'password';
                button.textContent = '👁️';
            }
        }
        
        function testAIService() {
            const provider = document.getElementById('ai_provider').value;
            const apiKey = document.querySelector('input[name="ai_api_key"]').value;
            const customUrl = document.querySelector('input[name="ai_custom_url"]').value;
            const resultDiv = document.getElementById('ai-test-result');
            
            if (!provider) {
                resultDiv.innerHTML = '<div style="color: #dc3545; font-weight: bold;">⚠️ Please select an AI service provider first.</div>';
                return;
            }
            
            if (!apiKey) {
                resultDiv.innerHTML = '<div style="color: #dc3545; font-weight: bold;">⚠️ Please enter an API key first.</div>';
                return;
            }
            
            if (provider === 'custom' && !customUrl) {
                resultDiv.innerHTML = '<div style="color: #dc3545; font-weight: bold;">⚠️ Please enter a custom API endpoint URL.</div>';
                return;
            }
            
            // Show loading
            resultDiv.innerHTML = '<div style="color: #007cba;">🔄 Testing AI service connection...</div>';
            
            // Test the AI service
            fetch('<?php echo admin_url('admin-ajax.php'); ?>', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({
                    action: 'claws_test_ai_service',
                    provider: provider,
                    api_key: apiKey,
                    custom_url: customUrl,
                    nonce: '<?php echo wp_create_nonce('claws_test_ai'); ?>'
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    resultDiv.innerHTML = '<div style="color: #28a745; font-weight: bold;">✅ AI service test successful!</div>';
                } else {
                    resultDiv.innerHTML = '<div style="color: #dc3545; font-weight: bold;">❌ Test failed: ' + (data.data || 'Unknown error') + '</div>';
                }
            })
            .catch(error => {
                console.error('AI test error:', error);
                resultDiv.innerHTML = '<div style="color: #dc3545; font-weight: bold;">❌ Test failed. Please check your settings and try again.</div>';
            });
        }
        
        // Initialize AI settings on page load
        document.addEventListener('DOMContentLoaded', function() {
            toggleAISettings();
            initializeTabs();
        });
        
        // Tab switching functionality
        function initializeTabs() {
            const generalTab = document.getElementById('general-tab');
            const colonyTab = document.getElementById('colony-tab');
            const volunteerTab = document.getElementById('volunteer-tab');
            const generalContent = document.getElementById('general-content');
            const colonyContent = document.getElementById('colony-content');
            const volunteerContent = document.getElementById('volunteer-content');
            
            generalTab.addEventListener('click', function(e) {
                e.preventDefault();
                // Remove active class from all tabs
                document.querySelectorAll('.nav-tab').forEach(tab => tab.classList.remove('nav-tab-active'));
                // Hide all content
                document.querySelectorAll('.tab-content').forEach(content => content.style.display = 'none');
                // Show general tab
                generalTab.classList.add('nav-tab-active');
                generalContent.style.display = 'block';
            });
            
            colonyTab.addEventListener('click', function(e) {
                e.preventDefault();
                // Remove active class from all tabs
                document.querySelectorAll('.nav-tab').forEach(tab => tab.classList.remove('nav-tab-active'));
                // Hide all content
                document.querySelectorAll('.tab-content').forEach(content => content.style.display = 'none');
                // Show colony tab
                colonyTab.classList.add('nav-tab-active');
                colonyContent.style.display = 'block';
            });
            
            volunteerTab.addEventListener('click', function(e) {
                e.preventDefault();
                // Remove active class from all tabs
                document.querySelectorAll('.nav-tab').forEach(tab => tab.classList.remove('nav-tab-active'));
                // Hide all content
                document.querySelectorAll('.tab-content').forEach(content => content.style.display = 'none');
                // Show volunteer tab
                volunteerTab.classList.add('nav-tab-active');
                volunteerContent.style.display = 'block';
            });
        }
        </script>
        
        <?php
    }
    
    
    /**
     * Admin help page
     */
    public function admin_help() {
        ?>
        <div class="wrap">
            <h1><?php _e('Purralytics Help', 'claws'); ?></h1>
            
            <div class="claws-help-section">
                <h2><?php _e('Getting Started', 'claws'); ?></h2>
                <p><?php _e('Purralytics is a comprehensive cat colony management system. Here\'s how to get started:', 'claws'); ?></p>
                
                <ol>
                    <li><?php _e('Create a page and add the [claws_app] shortcode', 'claws'); ?></li>
                    <li><?php _e('Users must log in to save data permanently', 'claws'); ?></li>
                    <li><?php _e('Start adding colonies, tracking intakes, and managing care', 'claws'); ?></li>
                </ol>
            </div>
            
            <div class="claws-help-section">
                <h2><?php _e('Available Shortcodes', 'claws'); ?></h2>
                <table class="wp-list-table widefat fixed striped">
                    <thead>
                        <tr>
                            <th><?php _e('Shortcode', 'claws'); ?></th>
                            <th><?php _e('Description', 'claws'); ?></th>
                            <th><?php _e('Parameters', 'claws'); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td><code>[claws_app]</code></td>
                            <td><?php _e('Full CLAWS application', 'claws'); ?></td>
                            <td>height, show_login_prompt</td>
                        </tr>
                        <tr>
                            <td><code>[claws_colony_tracker]</code></td>
                            <td><?php _e('Colony tracking only', 'claws'); ?></td>
                            <td>show_map, show_statistics, show_pie_chart</td>
                        </tr>
                        <tr>
                            <td><code>[claws_intake_discharge]</code></td>
                            <td><?php _e('Intake & discharge forms', 'claws'); ?></td>
                            <td>default_tab</td>
                        </tr>
                        <tr>
                            <td><code>[claws_neonate_care]</code></td>
                            <td><?php _e('Neonate care tracking', 'claws'); ?></td>
                            <td>default_age_range</td>
                        </tr>
                        <tr>
                            <td><code>[Admin_Reports]</code></td>
                            <td><?php _e('Analytics overview with summary statistics and charts', 'claws'); ?></td>
                            <td>show_summary, show_charts, title</td>
                        </tr>
                        <tr>
                            <td><code>[claws_summary]</code></td>
                            <td><?php _e('Simple summary statistics display', 'claws'); ?></td>
                            <td>style, title, show_title</td>
                        </tr>
                    </tbody>
                </table>
            </div>
            
            <div class="claws-help-section">
                <h2><?php _e('Troubleshooting', 'claws'); ?></h2>
                <div class="help-item">
                    <h4><?php _e('App not loading?', 'claws'); ?></h4>
                    <p><?php _e('Make sure JavaScript is enabled and there are no console errors. Try refreshing the page.', 'claws'); ?></p>
                </div>
                
                <div class="help-item">
                    <h4><?php _e('Can\'t save data?', 'claws'); ?></h4>
                    <p><?php _e('Users must be logged in to save data. Check that WordPress REST API is working.', 'claws'); ?></p>
                </div>
                
                <div class="help-item">
                    <h4><?php _e('Maps not showing?', 'claws'); ?></h4>
                    <p><?php _e('Check that the maps setting is enabled and that external scripts can load.', 'claws'); ?></p>
                </div>
            </div>
            
            <div class="claws-help-section">
                <h2><?php _e('Support', 'claws'); ?></h2>
                <p><?php _e('For additional support, please contact the Purralytics development team at ', 'claws'); ?><a href="mailto:clawsva@gmail.com">clawsva@gmail.com</a></p>
            </div>
        </div>
        <?php
    }
    
    /**
     * Helper function to calculate colony health score
     */
    private function calculate_health_score($colony) {
        // TNR Progress - cats and seniors only (exclude newborns and kittens)
        $tnr_eligible = ($colony['adults'] ?? 0) + ($colony['seniors'] ?? 0);
        $tnr_progress = $tnr_eligible > 0 ? ($colony['tippedEars'] / $tnr_eligible) * 100 : 0;
        
        // Winter Shelters - cats and seniors only (exclude newborns and kittens)  
        $shelter_needed = ($colony['adults'] ?? 0) + ($colony['seniors'] ?? 0);
        $shelter_progress = $shelter_needed > 0 ? ($colony['winterShelters'] / $shelter_needed) * 100 : 0;
        
        $security_scores = array(
            'Insufficient' => 20, 'Dangerous' => 20,
            'Marginal' => 40, 'Unsafe' => 40,
            'Sufficient' => 60, 'Somewhat Safe' => 60,
            'Good' => 80, 'Safe' => 80,
            'Very Good' => 100, 'Very Safe' => 100
        );
        
        $food_score = $security_scores[$colony['foodSecurity']] ?? 0;
        $water_score = $security_scores[$colony['waterSecurity']] ?? 0;
        $safety_score = $security_scores[$colony['safeLocation']] ?? 0;
        
        // Calculate average of available factors
        $total_score = 0;
        $factor_count = 0;
        
        // Add security factors (always counted if set)
        if (!empty($colony['foodSecurity'])) { $total_score += $food_score; $factor_count++; }
        if (!empty($colony['waterSecurity'])) { $total_score += $water_score; $factor_count++; }
        if (!empty($colony['safeLocation'])) { $total_score += $safety_score; $factor_count++; }
        
        // Add TNR and shelter factors only if there are eligible cats
        if ($tnr_eligible > 0) { $total_score += min($tnr_progress, 100); $factor_count++; }
        if ($shelter_needed > 0) { $total_score += min($shelter_progress, 100); $factor_count++; }
        
        return $factor_count > 0 ? round($total_score / $factor_count) : 0;
    }
    
    /**
     * Helper function to get health class for styling
     */
    private function get_health_class($score) {
        if ($score >= 80) return 'good';
        if ($score >= 60) return 'warning';
        if ($score >= 40) return 'poor';
        return 'critical';
    }
    
    
    /**
     * Admin intakes page - user-specific intake records
     */
    public function admin_intakes() {
        $user_id = get_current_user_id();
        $intakes = $this->database->get_user_intakes($user_id);
        
        ?>
        <div class="wrap">
            <h1><?php _e('My Intake Records', 'claws'); ?></h1>
            
            <div class="claws-admin-section">
                <p><?php _e('These are your personal cat intake records. Only you can see and manage these records.', 'claws'); ?></p>
                
                <?php if (!empty($intakes)): ?>
                <table class="wp-list-table widefat fixed striped">
                    <thead>
                        <tr>
                            <th><?php _e('Date', 'claws'); ?></th>
                            <th><?php _e('Cat Name', 'claws'); ?></th>
                            <th><?php _e('Contact Person', 'claws'); ?></th>
                            <th><?php _e('Source', 'claws'); ?></th>
                            <th><?php _e('Medical Condition', 'claws'); ?></th>
                            <th><?php _e('Actions', 'claws'); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($intakes as $intake): ?>
                        <tr>
                            <td><?php echo esc_html($intake['intake_date'] ?? $intake['date'] ?? 'N/A'); ?></td>
                            <td><strong><?php echo esc_html($intake['cat_name'] ?? 'N/A'); ?></strong></td>
                            <td><?php echo esc_html($intake['contact_name'] ?? 'N/A'); ?></td>
                            <td><?php echo esc_html($intake['source'] ?? 'N/A'); ?></td>
                            <td><?php echo esc_html($intake['medical_condition'] ?? 'None noted'); ?></td>
                            <td>
                                <a href="<?php echo admin_url('post.php?post=' . $intake['id'] . '&action=edit'); ?>" class="button button-small">
                                    <?php _e('View/Edit', 'claws'); ?>
                                </a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                <?php else: ?>
                <p><?php _e('No intake records found. Records will appear here after you add them through the CLAWS app.', 'claws'); ?></p>
                <?php endif; ?>
                
                <p style="margin-top: 20px;">
                    <a href="<?php echo home_url('/claws-app/'); ?>" class="button button-primary">
                        <?php _e('Add New Intake Record', 'claws'); ?>
                    </a>
                </p>
            </div>
        </div>
        <?php
    }
    
    /**
     * Admin discharges page - user-specific discharge records
     */
    public function admin_discharges() {
        $user_id = get_current_user_id();
        $discharges = $this->database->get_user_discharges($user_id);
        
        ?>
        <div class="wrap">
            <h1><?php _e('My Discharge Records', 'claws'); ?></h1>
            
            <div class="claws-admin-section">
                <p><?php _e('These are your personal cat discharge/outcome records. Only you can see and manage these records.', 'claws'); ?></p>
                
                <?php if (!empty($discharges)): ?>
                <table class="wp-list-table widefat fixed striped">
                    <thead>
                        <tr>
                            <th><?php _e('Date', 'claws'); ?></th>
                            <th><?php _e('Cat Name', 'claws'); ?></th>
                            <th><?php _e('Outcome', 'claws'); ?></th>
                            <th><?php _e('Notes', 'claws'); ?></th>
                            <th><?php _e('Actions', 'claws'); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($discharges as $discharge): ?>
                        <tr>
                            <td><?php echo esc_html($discharge['discharge_date'] ?? $discharge['date'] ?? 'N/A'); ?></td>
                            <td><strong><?php echo esc_html($discharge['cat_name'] ?? 'N/A'); ?></strong></td>
                            <td><?php echo esc_html($discharge['outcome'] ?? 'N/A'); ?></td>
                            <td><?php echo esc_html(substr($discharge['notes'] ?? '', 0, 50)) . (strlen($discharge['notes'] ?? '') > 50 ? '...' : ''); ?></td>
                            <td>
                                <a href="<?php echo admin_url('post.php?post=' . $discharge['id'] . '&action=edit'); ?>" class="button button-small">
                                    <?php _e('View/Edit', 'claws'); ?>
                                </a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                <?php else: ?>
                <p><?php _e('No discharge records found. Records will appear here after you add them through the CLAWS app.', 'claws'); ?></p>
                <?php endif; ?>
                
                <p style="margin-top: 20px;">
                    <a href="<?php echo home_url('/claws-app/'); ?>" class="button button-primary">
                        <?php _e('Add New Discharge Record', 'claws'); ?>
                    </a>
                </p>
            </div>
        </div>
        <?php
    }
    
    /**
     * Admin feeding records page - user-specific feeding records
     */
    public function admin_feeding() {
        // Handle form actions
        if (isset($_POST['action'])) {
            if ($_POST['action'] === 'update_feeding' && isset($_POST['feeding_nonce']) && wp_verify_nonce($_POST['feeding_nonce'], 'claws_feeding_nonce')) {
                $this->update_feeding_record();
            } elseif ($_POST['action'] === 'delete_feeding' && isset($_POST['feeding_nonce']) && wp_verify_nonce($_POST['feeding_nonce'], 'claws_feeding_nonce')) {
                $this->delete_feeding_record();
            }
        }
        
        // Check if editing a specific record
        if (isset($_GET['edit_feeding']) && is_numeric($_GET['edit_feeding'])) {
            $record = $this->database->get_feeding_record($_GET['edit_feeding']);
            if ($record && $record['user_id'] == get_current_user_id()) {
                $this->show_edit_feeding_form($record);
                return;
            }
        }
        
        $user_id = get_current_user_id();
        $feeding_records = $this->database->get_user_feeding_records($user_id, 50);
        
        ?>
        <div class="wrap">
            <h1><?php _e('My Feeding Records', 'claws'); ?></h1>
            
            <?php if (isset($_GET['updated'])): ?>
                <div class="notice notice-success"><p><?php _e('Feeding record updated successfully!', 'claws'); ?></p></div>
            <?php endif; ?>
            
            <?php if (isset($_GET['deleted'])): ?>
                <div class="notice notice-success"><p><?php _e('Feeding record deleted successfully!', 'claws'); ?></p></div>
            <?php endif; ?>
            
            <div class="claws-admin-section">
                <p><?php _e('These are your personal neonate care feeding records. Only you can see and manage these records.', 'claws'); ?></p>
                
                <?php if (!empty($feeding_records)): ?>
                <table class="wp-list-table widefat fixed striped">
                    <thead>
                        <tr>
                            <th><?php _e('Date', 'claws'); ?></th>
                            <th><?php _e('Time', 'claws'); ?></th>
                            <th><?php _e('Kitten Name', 'claws'); ?></th>
                            <th><?php _e('Pre Weight', 'claws'); ?></th>
                            <th><?php _e('Post Weight', 'claws'); ?></th>
                            <th><?php _e('Weight Gain', 'claws'); ?></th>
                            <th><?php _e('Notes', 'claws'); ?></th>
                            <th><?php _e('Actions', 'claws'); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($feeding_records as $record): ?>
                        <tr>
                            <td><?php echo esc_html($record['feeding_date']); ?></td>
                            <td><?php echo esc_html($record['feeding_time']); ?></td>
                            <td><strong><?php echo esc_html($record['kitten_name']); ?></strong></td>
                            <td><?php echo esc_html($record['pre_weight']); ?>g</td>
                            <td><?php echo esc_html($record['post_weight']); ?>g</td>
                            <td>
                                <?php 
                                $gain = floatval($record['post_weight']) - floatval($record['pre_weight']);
                                $color = $gain > 0 ? 'green' : 'red';
                                echo '<span style="color: ' . $color . ';">' . ($gain > 0 ? '+' : '') . $gain . 'g</span>';
                                ?>
                            </td>
                            <td><?php echo esc_html(substr($record['notes'] ?? '', 0, 50)) . (strlen($record['notes'] ?? '') > 50 ? '...' : ''); ?></td>
                            <td>
                                <a href="<?php echo admin_url('admin.php?page=claws-feeding&edit_feeding=' . $record['id']); ?>" class="button button-small">
                                    <?php _e('Edit', 'claws'); ?>
                                </a>
                                <form method="post" style="display: inline;" onsubmit="return confirm('<?php _e('Are you sure you want to delete this feeding record?', 'claws'); ?>');">
                                    <input type="hidden" name="action" value="delete_feeding" />
                                    <input type="hidden" name="record_id" value="<?php echo esc_attr($record['id']); ?>" />
                                    <input type="hidden" name="feeding_nonce" value="<?php echo wp_create_nonce('claws_feeding_nonce'); ?>" />
                                    <input type="submit" class="button button-small" value="<?php _e('Delete', 'claws'); ?>" />
                                </form>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                <?php else: ?>
                <p><?php _e('No feeding records found. Records will appear here after you add them through the CLAWS app.', 'claws'); ?></p>
                <?php endif; ?>
                
                <p style="margin-top: 20px;">
                    <a href="<?php echo home_url('/claws-app/'); ?>" class="button button-primary">
                        <?php _e('Add New Feeding Record', 'claws'); ?>
                    </a>
                </p>
            </div>
        </div>
        <?php
    }
    
    /**
     * Add custom meta boxes for intake and discharge records
     */
    public function add_custom_meta_boxes() {
        // Intake meta boxes
        add_meta_box(
            'claws_intake_details',
            __('Intake Details', 'claws'),
            array($this, 'intake_details_meta_box'),
            'claws_intake',
            'normal',
            'high'
        );
        
        // Discharge meta boxes
        add_meta_box(
            'claws_discharge_details',
            __('Discharge Details', 'claws'),
            array($this, 'discharge_details_meta_box'),
            'claws_discharge',
            'normal',
            'high'
        );
    }
    
    /**
     * Intake details meta box
     */
    public function intake_details_meta_box($post) {
        // Add nonce field for security
        wp_nonce_field('claws_intake_meta', 'claws_intake_nonce');
        
        // Get saved values
        $meta = get_post_meta($post->ID);
        
        ?>
        <table class="form-table">
            <tr>
                <th><label for="intake_date"><?php _e('Intake Date', 'claws'); ?></label></th>
                <td><input type="date" id="intake_date" name="intake_date" value="<?php echo esc_attr($meta['intake_date'][0] ?? ''); ?>" /></td>
            </tr>
            <tr>
                <th><label for="cat_name"><?php _e('Cat Name', 'claws'); ?></label></th>
                <td><input type="text" id="cat_name" name="cat_name" value="<?php echo esc_attr($meta['cat_name'][0] ?? ''); ?>" class="regular-text" /></td>
            </tr>
            <tr>
                <th><label for="contact_name"><?php _e('Contact Name', 'claws'); ?></label></th>
                <td><input type="text" id="contact_name" name="contact_name" value="<?php echo esc_attr($meta['contact_name'][0] ?? ''); ?>" class="regular-text" /></td>
            </tr>
            <tr>
                <th><label for="contact_phone"><?php _e('Contact Phone', 'claws'); ?></label></th>
                <td><input type="tel" id="contact_phone" name="contact_phone" value="<?php echo esc_attr($meta['contact_phone'][0] ?? ''); ?>" class="regular-text" /></td>
            </tr>
            <tr>
                <th><label for="contact_email"><?php _e('Contact Email', 'claws'); ?></label></th>
                <td><input type="email" id="contact_email" name="contact_email" value="<?php echo esc_attr($meta['contact_email'][0] ?? ''); ?>" class="regular-text" /></td>
            </tr>
            <tr>
                <th><label for="age"><?php _e('Age', 'claws'); ?></label></th>
                <td>
                    <select id="age" name="age">
                        <option value=""><?php _e('Select age...', 'claws'); ?></option>
                        <option value="Newborn (0-8 weeks)" <?php selected($meta['age'][0] ?? '', 'Newborn (0-8 weeks)'); ?>><?php _e('Newborn (0-8 weeks)', 'claws'); ?></option>
                        <option value="Kitten (2-5 months)" <?php selected($meta['age'][0] ?? '', 'Kitten (2-5 months)'); ?>><?php _e('Kitten (2-5 months)', 'claws'); ?></option>
                        <option value="Young Adult (6 months-2 years)" <?php selected($meta['age'][0] ?? '', 'Young Adult (6 months-2 years)'); ?>><?php _e('Young Adult (6 months-2 years)', 'claws'); ?></option>
                        <option value="Adult (2-8 years)" <?php selected($meta['age'][0] ?? '', 'Adult (2-8 years)'); ?>><?php _e('Adult (2-8 years)', 'claws'); ?></option>
                        <option value="Senior (8+ years)" <?php selected($meta['age'][0] ?? '', 'Senior (8+ years)'); ?>><?php _e('Senior (8+ years)', 'claws'); ?></option>
                    </select>
                </td>
            </tr>
            <tr>
                <th><label for="gender"><?php _e('Gender', 'claws'); ?></label></th>
                <td>
                    <select id="gender" name="gender">
                        <option value=""><?php _e('Select gender...', 'claws'); ?></option>
                        <option value="Male" <?php selected($meta['gender'][0] ?? '', 'Male'); ?>><?php _e('Male', 'claws'); ?></option>
                        <option value="Female" <?php selected($meta['gender'][0] ?? '', 'Female'); ?>><?php _e('Female', 'claws'); ?></option>
                        <option value="Unknown" <?php selected($meta['gender'][0] ?? '', 'Unknown'); ?>><?php _e('Unknown', 'claws'); ?></option>
                    </select>
                </td>
            </tr>
            <tr>
                <th><label for="coat"><?php _e('Coat', 'claws'); ?></label></th>
                <td>
                    <select id="coat" name="coat">
                        <option value=""><?php _e('Select coat type...', 'claws'); ?></option>
                        <option value="Short" <?php selected($meta['coat'][0] ?? '', 'Short'); ?>><?php _e('Short', 'claws'); ?></option>
                        <option value="Medium" <?php selected($meta['coat'][0] ?? '', 'Medium'); ?>><?php _e('Medium', 'claws'); ?></option>
                        <option value="Long" <?php selected($meta['coat'][0] ?? '', 'Long'); ?>><?php _e('Long', 'claws'); ?></option>
                        <option value="Hairless" <?php selected($meta['coat'][0] ?? '', 'Hairless'); ?>><?php _e('Hairless', 'claws'); ?></option>
                    </select>
                </td>
            </tr>
            <tr>
                <th><label for="color"><?php _e('Color', 'claws'); ?></label></th>
                <td><input type="text" id="color" name="color" value="<?php echo esc_attr($meta['color'][0] ?? ''); ?>" class="regular-text" placeholder="e.g. Orange tabby, Black" /></td>
            </tr>
            <tr>
                <th><label for="type"><?php _e('Type', 'claws'); ?></label></th>
                <td>
                    <select id="type" name="type">
                        <option value=""><?php _e('Select cat type...', 'claws'); ?></option>
                        <option value="Stray" <?php selected($meta['type'][0] ?? '', 'Stray'); ?>><?php _e('Stray', 'claws'); ?></option>
                        <option value="Feral" <?php selected($meta['type'][0] ?? '', 'Feral'); ?>><?php _e('Feral', 'claws'); ?></option>
                        <option value="Owned" <?php selected($meta['type'][0] ?? '', 'Owned'); ?>><?php _e('Owned', 'claws'); ?></option>
                        <option value="Colony Cat" <?php selected($meta['type'][0] ?? '', 'Colony Cat'); ?>><?php _e('Colony Cat', 'claws'); ?></option>
                    </select>
                </td>
            </tr>
            <tr>
                <th><label for="medical_condition"><?php _e('Medical Condition', 'claws'); ?></label></th>
                <td><input type="text" id="medical_condition" name="medical_condition" value="<?php echo esc_attr($meta['medical_condition'][0] ?? ''); ?>" class="regular-text" /></td>
            </tr>
        </table>
        
        <?php
        // Show attached photo if exists
        $photo_id = get_post_meta($post->ID, 'intake_photo', true);
        if ($photo_id) {
            $photo_url = wp_get_attachment_url($photo_id);
            if ($photo_url) {
                echo '<h4>' . __('Uploaded Photo', 'claws') . '</h4>';
                echo '<img src="' . esc_url($photo_url) . '" style="max-width: 200px; height: auto; border: 1px solid #ddd; padding: 5px;" />';
            }
        }
        ?>
        <?php
    }
    
    /**
     * Save meta box data
     */
    public function save_meta_box_data($post_id) {
        // Check if this is an autosave
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
            return;
        }
        
        // Check user permissions
        if (!current_user_can('edit_post', $post_id)) {
            return;
        }
        
        // Only save for our custom post types
        $post_type = get_post_type($post_id);
        if (!in_array($post_type, ['claws_intake', 'claws_discharge'])) {
            return;
        }
        
        // Verify nonce for intake
        if ($post_type === 'claws_intake') {
            if (!isset($_POST['claws_intake_nonce']) || !wp_verify_nonce($_POST['claws_intake_nonce'], 'claws_intake_meta')) {
                error_log('CLAWS: Nonce verification failed for intake meta save');
                return;
            }
        }
        
        // Save intake fields
        if ($post_type === 'claws_intake') {
            $intake_fields = ['intake_date', 'cat_name', 'contact_name', 'contact_phone', 'contact_email', 'age', 'gender', 'coat', 'color', 'type', 'medical_condition'];
            
            foreach ($intake_fields as $field) {
                if (isset($_POST[$field])) {
                    update_post_meta($post_id, $field, sanitize_text_field($_POST[$field]));
                }
            }
        }
        
        // Save discharge fields
        if ($post_type === 'claws_discharge') {
            $discharge_fields = ['discharge_date', 'cat_name', 'outcome', 'notes'];
            
            foreach ($discharge_fields as $field) {
                if (isset($_POST[$field])) {
                    update_post_meta($post_id, $field, sanitize_text_field($_POST[$field]));
                }
            }
        }
    }
    
    /**
     * Discharge details meta box
     */
    public function discharge_details_meta_box($post) {
        // Get saved values
        $meta = get_post_meta($post->ID);
        
        ?>
        <table class="form-table">
            <tr>
                <th><label for="discharge_date"><?php _e('Discharge Date', 'claws'); ?></label></th>
                <td><input type="date" id="discharge_date" name="discharge_date" value="<?php echo esc_attr($meta['discharge_date'][0] ?? ''); ?>" /></td>
            </tr>
            <tr>
                <th><label for="cat_name"><?php _e('Cat Name', 'claws'); ?></label></th>
                <td><input type="text" id="cat_name" name="cat_name" value="<?php echo esc_attr($meta['cat_name'][0] ?? ''); ?>" class="regular-text" /></td>
            </tr>
            <tr>
                <th><label for="outcome"><?php _e('Outcome', 'claws'); ?></label></th>
                <td>
                    <select id="outcome" name="outcome">
                        <option value=""><?php _e('Select outcome...', 'claws'); ?></option>
                        <option value="Adoption" <?php selected($meta['outcome'][0] ?? '', 'Adoption'); ?>><?php _e('Adoption', 'claws'); ?></option>
                        <option value="Died" <?php selected($meta['outcome'][0] ?? '', 'Died'); ?>><?php _e('Died', 'claws'); ?></option>
                        <option value="Euthanasia" <?php selected($meta['outcome'][0] ?? '', 'Euthanasia'); ?>><?php _e('Euthanasia', 'claws'); ?></option>
                        <option value="Transfer (to no-kill shelter for eventual adoption)" <?php selected($meta['outcome'][0] ?? '', 'Transfer (to no-kill shelter for eventual adoption)'); ?>><?php _e('Transfer (to no-kill shelter for eventual adoption)', 'claws'); ?></option>
                        <option value="TNR (Trap, Neuter, Release)" <?php selected($meta['outcome'][0] ?? '', 'TNR (Trap, Neuter, Release)'); ?>><?php _e('TNR (Trap, Neuter, Release)', 'claws'); ?></option>
                        <option value="Returned to Owner" <?php selected($meta['outcome'][0] ?? '', 'Returned to Owner'); ?>><?php _e('Returned to Owner', 'claws'); ?></option>
                        <option value="Escaped" <?php selected($meta['outcome'][0] ?? '', 'Escaped'); ?>><?php _e('Escaped', 'claws'); ?></option>
                        <option value="Foster to Adopt" <?php selected($meta['outcome'][0] ?? '', 'Foster to Adopt'); ?>><?php _e('Foster to Adopt', 'claws'); ?></option>
                    </select>
                </td>
            </tr>
            <tr>
                <th><label for="notes"><?php _e('Notes', 'claws'); ?></label></th>
                <td><textarea id="notes" name="notes" rows="4" class="large-text"><?php echo esc_textarea($meta['notes'][0] ?? ''); ?></textarea></td>
            </tr>
        </table>
        
        <?php
        // Show attached photo if exists
        $photo_id = get_post_meta($post->ID, 'discharge_photo', true);
        if ($photo_id) {
            $photo_url = wp_get_attachment_url($photo_id);
            if ($photo_url) {
                echo '<h4>' . __('Uploaded Photo', 'claws') . '</h4>';
                echo '<img src="' . esc_url($photo_url) . '" style="max-width: 200px; height: auto; border: 1px solid #ddd; padding: 5px;" />';
            }
        }
        ?>
        <?php
    }
    
    /**
     * Flush rewrite rules if needed (fixes post type edit issues)
     */
    public function maybe_flush_rewrite_rules() {
        if (get_option('claws_flush_rewrite_rules', false)) {
            flush_rewrite_rules();
            delete_option('claws_flush_rewrite_rules');
        }
    }
    
    /**
     * Trigger rewrite rules flush (call this after plugin updates)
     */
    public static function trigger_rewrite_flush() {
        update_option('claws_flush_rewrite_rules', true);
    }
    
    /**
     * Emergency flush rewrite rules (fixes post type edit issues immediately)
     */
    public static function emergency_flush_rewrite_rules() {
        flush_rewrite_rules(true);  // Hard flush
        delete_option('rewrite_rules');  // Clear cached rules
        update_option('claws_emergency_flush_done', time());
    }
    
    /**
     * Display My Colonies admin page
     */
    public function admin_my_colonies() {
        $user_id = get_current_user_id();
        
        // Get colonies created by current user
        $colonies = get_posts(array(
            'post_type' => 'claws_colony',
            'numberposts' => -1,
            'post_status' => 'publish',
            'author' => $user_id,
            'meta_query' => array()
        ));
        
        ?>
        <div class="wrap">
            <h1><?php _e('My Colonies', 'claws'); ?></h1>
            <p><?php _e('View and manage colonies you have created.', 'claws'); ?></p>
            
            <?php if (empty($colonies)): ?>
                <div class="notice notice-info">
                    <p><?php _e('You have not created any colonies yet.', 'claws'); ?></p>
                </div>
            <?php else: ?>
                <table class="wp-list-table widefat fixed striped">
                    <thead>
                        <tr>
                            <th><?php _e('Colony Name', 'claws'); ?></th>
                            <th><?php _e('Location', 'claws'); ?></th>
                            <th><?php _e('Total Cats', 'claws'); ?></th>
                            <th><?php _e('Tipped Ears', 'claws'); ?></th>
                            <th><?php _e('Winter Shelters', 'claws'); ?></th>
                            <th><?php _e('Created', 'claws'); ?></th>
                            <th><?php _e('Actions', 'claws'); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($colonies as $colony): 
                            $meta = get_post_meta($colony->ID);
                            $total_cats = (int)($meta['cats_total'][0] ?? 0);
                            $tipped_ears = (int)($meta['tipped_ears'][0] ?? 0);
                            $winter_shelters = (int)($meta['winter_shelters'][0] ?? 0);
                            
                            $address_parts = array();
                            if (!empty($meta['street'][0])) $address_parts[] = $meta['street'][0];
                            if (!empty($meta['city'][0])) $address_parts[] = $meta['city'][0];
                            if (!empty($meta['state'][0])) $address_parts[] = $meta['state'][0];
                            $location = implode(', ', $address_parts) ?: __('No address', 'claws');
                        ?>
                            <tr>
                                <td><strong><?php echo esc_html($colony->post_title); ?></strong></td>
                                <td><?php echo esc_html($location); ?></td>
                                <td><?php echo $total_cats; ?></td>
                                <td><?php echo $tipped_ears; ?> (<?php echo $total_cats > 0 ? round(($tipped_ears / $total_cats) * 100) : 0; ?>%)</td>
                                <td><?php echo $winter_shelters; ?></td>
                                <td><?php echo date('M j, Y', strtotime($colony->post_date)); ?></td>
                                <td>
                                    <a href="<?php echo get_edit_post_link($colony->ID); ?>" class="button button-small"><?php _e('Edit', 'claws'); ?></a>
                                    <a href="<?php echo admin_url('admin.php?page=claws-colony-history&colony_id=' . $colony->ID); ?>" class="button button-small"><?php _e('History', 'claws'); ?></a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>
        <?php
    }
    
    /**
     * Display All Colonies admin page (authors/admins only)
     */
    public function admin_all_colonies() {
        if (!current_user_can('edit_others_posts')) {
            wp_die(__('You do not have sufficient permissions to access this page.'));
        }
        
        // Get all colonies
        $colonies = get_posts(array(
            'post_type' => 'claws_colony',
            'numberposts' => -1,
            'post_status' => 'publish',
            'meta_query' => array()
        ));
        
        ?>
        <div class="wrap">
            <h1><?php _e('All Colonies', 'claws'); ?></h1>
            <p><?php _e('View and manage all colonies in the system.', 'claws'); ?></p>
            
            <?php if (empty($colonies)): ?>
                <div class="notice notice-info">
                    <p><?php _e('No colonies have been created yet.', 'claws'); ?></p>
                </div>
            <?php else: ?>
                <table class="wp-list-table widefat fixed striped">
                    <thead>
                        <tr>
                            <th><?php _e('Colony Name', 'claws'); ?></th>
                            <th><?php _e('Creator', 'claws'); ?></th>
                            <th><?php _e('Location', 'claws'); ?></th>
                            <th><?php _e('Total Cats', 'claws'); ?></th>
                            <th><?php _e('Health Score', 'claws'); ?></th>
                            <th><?php _e('Created', 'claws'); ?></th>
                            <th><?php _e('Actions', 'claws'); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($colonies as $colony): 
                            $meta = get_post_meta($colony->ID);
                            $author = get_userdata($colony->post_author);
                            $total_cats = (int)($meta['cats_total'][0] ?? 0);
                            $tipped_ears = (int)($meta['tipped_ears'][0] ?? 0);
                            $winter_shelters = (int)($meta['winter_shelters'][0] ?? 0);
                            
                            // Calculate basic health score
                            $health_score = 0;
                            if ($total_cats > 0) {
                                $tnr_percent = ($tipped_ears / $total_cats) * 100;
                                $shelter_percent = ($winter_shelters / $total_cats) * 100;
                                $health_score = round(($tnr_percent + $shelter_percent) / 2);
                            }
                            
                            $address_parts = array();
                            if (!empty($meta['street'][0])) $address_parts[] = $meta['street'][0];
                            if (!empty($meta['city'][0])) $address_parts[] = $meta['city'][0];
                            if (!empty($meta['state'][0])) $address_parts[] = $meta['state'][0];
                            $location = implode(', ', $address_parts) ?: __('No address', 'claws');
                        ?>
                            <tr>
                                <td><strong><?php echo esc_html($colony->post_title); ?></strong></td>
                                <td><?php echo $author ? esc_html($author->display_name) : __('Unknown', 'claws'); ?></td>
                                <td><?php echo esc_html($location); ?></td>
                                <td><?php echo $total_cats; ?></td>
                                <td><?php echo $health_score; ?>%</td>
                                <td><?php echo date('M j, Y', strtotime($colony->post_date)); ?></td>
                                <td>
                                    <a href="<?php echo get_edit_post_link($colony->ID); ?>" class="button button-small"><?php _e('Edit', 'claws'); ?></a>
                                    <a href="<?php echo admin_url('admin.php?page=claws-colony-history&colony_id=' . $colony->ID); ?>" class="button button-small"><?php _e('History', 'claws'); ?></a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>
        <?php
    }
    
    /**
     * Display Historical Colony Data admin page
     */
    public function admin_colony_history() {
        if (!current_user_can('edit_others_posts')) {
            wp_die(__('You do not have sufficient permissions to access this page.'));
        }
        
        // Handle delete action
        if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['history_id'])) {
            $history_id = intval($_GET['history_id']);
            if (wp_verify_nonce($_GET['_wpnonce'], 'delete_history_' . $history_id)) {
                if (wp_delete_post($history_id, true)) {
                    echo '<div class="notice notice-success"><p>' . __('Historical record deleted successfully.', 'claws') . '</p></div>';
                } else {
                    echo '<div class="notice notice-error"><p>' . __('Failed to delete historical record.', 'claws') . '</p></div>';
                }
            }
        }
        
        // Handle edit form submission
        if (isset($_POST['action']) && $_POST['action'] === 'update_history' && isset($_POST['history_id'])) {
            $history_id = intval($_POST['history_id']);
            if (wp_verify_nonce($_POST['_wpnonce'], 'update_history_' . $history_id)) {
                $this->update_historical_record($history_id, $_POST);
            }
        }
        
        // Show edit form if requested
        if (isset($_GET['action']) && $_GET['action'] === 'edit' && isset($_GET['history_id'])) {
            $this->show_edit_history_form(intval($_GET['history_id']));
            return;
        }
        
        // Handle manual creation of initial historical records
        if (isset($_POST['create_initial_records']) && wp_verify_nonce($_POST['_wpnonce'], 'create_initial_records')) {
            $database = CLAWS_Database::getInstance();
            
            // Get colonies count for comparison (admin function sees all colonies)
            $colonies = $this->database->get_colonies();
            $colony_count = count($colonies);
            
            // Use NEW clean implementation
            $created_count = $database->create_initial_colony_history_posts();
            
            echo '<div class="notice notice-success"><p>' . sprintf(__('Found %d colonies. Created initial historical records for %d colonies using custom post type.', 'claws'), $colony_count, $created_count) . '</p></div>';
        }
        
        // Get specific colony if requested
        $colony_id = isset($_GET['colony_id']) ? (int)$_GET['colony_id'] : 0;
        $colony_name = '';
        
        if ($colony_id > 0) {
            $colony = get_post($colony_id);
            if ($colony && $colony->post_type === 'claws_colony') {
                $colony_name = $colony->post_title;
            }
        }
        
        // Get historical records using custom post type (NEW clean approach)
        $database = CLAWS_Database::getInstance();
        $history_records = array();
        
        if ($colony_id > 0) {
            // Get history for specific colony
            $history_records = $database->get_colony_history_posts($colony_id);
        } else {
            // Get all historical records from all colonies
            $args = array(
                'post_type' => 'claws_colony_history',
                'numberposts' => -1,
                'post_status' => 'publish',
                'orderby' => 'post_date',
                'order' => 'DESC'
            );
            
            $history_posts = get_posts($args);
            
            foreach ($history_posts as $post) {
                $colony_id_meta = get_post_meta($post->ID, 'colony_id', true);
                $colony_post = get_post($colony_id_meta);
                $author = get_userdata($post->post_author);
                
                $history_records[] = array(
                    'id' => $post->ID,
                    'colony_id' => $colony_id_meta,
                    'colony_name' => $colony_post ? $colony_post->post_title : 'Unknown',
                    'user_name' => $author ? $author->display_name : 'Unknown',
                    'effective_date' => get_post_meta($post->ID, 'effective_date', true) ?: date('Y-m-d', strtotime($post->post_date)),
                    'cats_total' => get_post_meta($post->ID, 'cats_total', true) ?: 0,
                    'cats_babies' => get_post_meta($post->ID, 'cats_babies', true) ?: 0,
                    'cats_kittens' => get_post_meta($post->ID, 'cats_kittens', true) ?: 0,
                    'cats_adults' => get_post_meta($post->ID, 'cats_adults', true) ?: 0,
                    'cats_seniors' => get_post_meta($post->ID, 'cats_seniors', true) ?: 0,
                    'tipped_ears' => get_post_meta($post->ID, 'tipped_ears', true) ?: 0,
                    'winter_shelters' => get_post_meta($post->ID, 'winter_shelters', true) ?: 0,
                    'food_security' => get_post_meta($post->ID, 'food_security', true) ?: '',
                    'water_security' => get_post_meta($post->ID, 'water_security', true) ?: '',
                    'safe_location' => get_post_meta($post->ID, 'safe_location', true) ?: ''
                );
            }
        }
        
        ?>
        <div class="wrap">
            <h1><?php _e('Historical Colony Data', 'claws'); ?></h1>
            <?php if ($colony_name): ?>
                <p><?php printf(__('Historical data for colony: %s', 'claws'), '<strong>' . esc_html($colony_name) . '</strong>'); ?></p>
                <p><a href="<?php echo admin_url('admin.php?page=claws-colony-history'); ?>" class="button"><?php _e('View All Colonies', 'claws'); ?></a></p>
            <?php else: ?>
                <p><?php _e('Historical tracking data for all colonies (using WordPress custom post types).', 'claws'); ?></p>
                
                <?php if (empty($history_records)): ?>
                    <div style="margin: 20px 0; padding: 15px; background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 4px;">
                        <h3><?php _e('No Historical Data Found', 'claws'); ?></h3>
                        <p><?php _e('No historical records exist yet. You can create initial historical records for all existing colonies using the button below.', 'claws'); ?></p>
                        
                        <form method="post" style="margin-top: 10px;">
                            <?php wp_nonce_field('create_initial_records'); ?>
                            <input type="submit" name="create_initial_records" value="<?php _e('Create Initial Historical Records', 'claws'); ?>" class="button button-primary" onclick="return confirm('<?php _e('This will create initial historical records for all colonies that do not have any. Continue?', 'claws'); ?>');">
                        </form>
                    </div>
                <?php endif; ?>
            <?php endif; ?>
            
            <?php if (empty($history_records)): ?>
                <div class="notice notice-info">
                    <p><?php _e('No historical data found.', 'claws'); ?></p>
                </div>
            <?php else: ?>
                <table class="wp-list-table widefat fixed striped">
                    <thead>
                        <tr>
                            <th><?php _e('Colony', 'claws'); ?></th>
                            <th><?php _e('Date', 'claws'); ?></th>
                            <th><?php _e('Total Cats', 'claws'); ?></th>
                            <th><?php _e('Newborn', 'claws'); ?></th>
                            <th><?php _e('Kitten', 'claws'); ?></th>
                            <th><?php _e('Cat', 'claws'); ?></th>
                            <th><?php _e('Senior', 'claws'); ?></th>
                            <th><?php _e('Tipped Ears', 'claws'); ?></th>
                            <th><?php _e('Shelters', 'claws'); ?></th>
                            <th><?php _e('Food Security', 'claws'); ?></th>
                            <th><?php _e('Water Security', 'claws'); ?></th>
                            <th><?php _e('Location Security', 'claws'); ?></th>
                            <th><?php _e('Recorded By', 'claws'); ?></th>
                            <th><?php _e('Actions', 'claws'); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($history_records as $record): 
                            // Handle both array and object formats for compatibility
                            $colony_name = is_array($record) ? $record['colony_name'] : $record->colony_name;
                            $effective_date = is_array($record) ? $record['effective_date'] : $record->effective_date;
                            $cats_total = is_array($record) ? $record['cats_total'] : $record->cats_total;
                            $cats_babies = is_array($record) ? $record['cats_babies'] : $record->cats_babies;
                            $cats_kittens = is_array($record) ? $record['cats_kittens'] : $record->cats_kittens;
                            $cats_adults = is_array($record) ? $record['cats_adults'] : $record->cats_adults;
                            $cats_seniors = is_array($record) ? $record['cats_seniors'] : $record->cats_seniors;
                            $tipped_ears = is_array($record) ? $record['tipped_ears'] : $record->tipped_ears;
                            $winter_shelters = is_array($record) ? $record['winter_shelters'] : $record->winter_shelters;
                            $food_security = is_array($record) ? $record['food_security'] : $record->food_security;
                            $water_security = is_array($record) ? $record['water_security'] : $record->water_security;
                            $safe_location = is_array($record) ? $record['safe_location'] : $record->safe_location;
                            $user_name = is_array($record) ? $record['user_name'] : $record->user_name;
                            $record_colony_id = is_array($record) ? $record['colony_id'] : $record->colony_id;
                        ?>
                            <tr>
                                <td>
                                    <strong><?php echo esc_html($colony_name ?: __('Unknown', 'claws')); ?></strong>
                                    <?php if (!$colony_id): ?>
                                        <br><a href="<?php echo admin_url('admin.php?page=claws-colony-history&colony_id=' . $record_colony_id); ?>" class="button button-small"><?php _e('View History', 'claws'); ?></a>
                                    <?php endif; ?>
                                </td>
                                <td><?php echo date('M j, Y', strtotime($effective_date)); ?></td>
                                <td><?php echo (int)$cats_total; ?></td>
                                <td><?php echo (int)$cats_babies; ?></td>
                                <td><?php echo (int)$cats_kittens; ?></td>
                                <td><?php echo (int)$cats_adults; ?></td>
                                <td><?php echo (int)$cats_seniors; ?></td>
                                <td><?php echo (int)$tipped_ears; ?></td>
                                <td><?php echo (int)$winter_shelters; ?></td>
                                <td><?php echo esc_html($food_security); ?></td>
                                <td><?php echo esc_html($water_security); ?></td>
                                <td><?php echo esc_html($safe_location); ?></td>
                                <td><?php echo esc_html($user_name ?: __('Unknown', 'claws')); ?></td>
                                <td>
                                    <?php 
                                    $history_id = is_array($record) ? $record['id'] : $record->id;
                                    ?>
                                    <a href="<?php echo admin_url('admin.php?page=claws-colony-history&action=edit&history_id=' . $history_id); ?>" class="button button-small"><?php _e('Edit', 'claws'); ?></a>
                                    <a href="<?php echo wp_nonce_url(admin_url('admin.php?page=claws-colony-history&action=delete&history_id=' . $history_id), 'delete_history_' . $history_id); ?>" class="button button-small button-link-delete" onclick="return confirm('<?php _e('Are you sure you want to delete this historical record?', 'claws'); ?>')"><?php _e('Delete', 'claws'); ?></a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>
        <?php
    }

    private function show_edit_history_form($record) {
        ?>
        <h3>Edit Historical Record</h3>
        <form method="post" action="">
            <input type="hidden" name="action" value="update_history" />
            <input type="hidden" name="record_id" value="<?php echo esc_attr($record->ID); ?>" />
            <input type="hidden" name="admin_nonce" value="<?php echo wp_create_nonce('claws_admin_nonce'); ?>" />
            
            <table class="form-table">
                <tr>
                    <th><label for="edit_colony_name">Colony Name</label></th>
                    <td><input type="text" id="edit_colony_name" name="colony_name" value="<?php echo esc_attr(get_post_meta($record->ID, '_colony_name', true)); ?>" class="regular-text" required /></td>
                </tr>
                <tr>
                    <th><label for="edit_street_address">Street Address</label></th>
                    <td><input type="text" id="edit_street_address" name="street_address" value="<?php echo esc_attr(get_post_meta($record->ID, '_street_address', true)); ?>" class="regular-text" /></td>
                </tr>
                <tr>
                    <th><label for="edit_city">City</label></th>
                    <td><input type="text" id="edit_city" name="city" value="<?php echo esc_attr(get_post_meta($record->ID, '_city', true)); ?>" class="regular-text" /></td>
                </tr>
                <tr>
                    <th><label for="edit_state">State</label></th>
                    <td><input type="text" id="edit_state" name="state" value="<?php echo esc_attr(get_post_meta($record->ID, '_state', true)); ?>" class="regular-text" /></td>
                </tr>
                <tr>
                    <th><label for="edit_zip">ZIP Code</label></th>
                    <td><input type="text" id="edit_zip" name="zip" value="<?php echo esc_attr(get_post_meta($record->ID, '_zip', true)); ?>" class="regular-text" /></td>
                </tr>
                <tr>
                    <th><label for="edit_babies">Babies</label></th>
                    <td><input type="number" id="edit_babies" name="babies" value="<?php echo esc_attr(get_post_meta($record->ID, '_babies', true)); ?>" min="0" /></td>
                </tr>
                <tr>
                    <th><label for="edit_kittens">Kittens</label></th>
                    <td><input type="number" id="edit_kittens" name="kittens" value="<?php echo esc_attr(get_post_meta($record->ID, '_kittens', true)); ?>" min="0" /></td>
                </tr>
                <tr>
                    <th><label for="edit_adults">Adults</label></th>
                    <td><input type="number" id="edit_adults" name="adults" value="<?php echo esc_attr(get_post_meta($record->ID, '_adults', true)); ?>" min="0" /></td>
                </tr>
                <tr>
                    <th><label for="edit_seniors">Seniors</label></th>
                    <td><input type="number" id="edit_seniors" name="seniors" value="<?php echo esc_attr(get_post_meta($record->ID, '_seniors', true)); ?>" min="0" /></td>
                </tr>
                <tr>
                    <th><label for="edit_feeding_security">Feeding Security</label></th>
                    <td>
                        <select id="edit_feeding_security" name="feeding_security">
                            <option value="High" <?php selected(get_post_meta($record->ID, '_feeding_security', true), 'High'); ?>>High</option>
                            <option value="Medium" <?php selected(get_post_meta($record->ID, '_feeding_security', true), 'Medium'); ?>>Medium</option>
                            <option value="Low" <?php selected(get_post_meta($record->ID, '_feeding_security', true), 'Low'); ?>>Low</option>
                        </select>
                    </td>
                </tr>
                <tr>
                    <th><label for="edit_water_security">Water Security</label></th>
                    <td>
                        <select id="edit_water_security" name="water_security">
                            <option value="High" <?php selected(get_post_meta($record->ID, '_water_security', true), 'High'); ?>>High</option>
                            <option value="Medium" <?php selected(get_post_meta($record->ID, '_water_security', true), 'Medium'); ?>>Medium</option>
                            <option value="Low" <?php selected(get_post_meta($record->ID, '_water_security', true), 'Low'); ?>>Low</option>
                        </select>
                    </td>
                </tr>
                <tr>
                    <th><label for="edit_shelter_security">Shelter Security</label></th>
                    <td>
                        <select id="edit_shelter_security" name="shelter_security">
                            <option value="High" <?php selected(get_post_meta($record->ID, '_shelter_security', true), 'High'); ?>>High</option>
                            <option value="Medium" <?php selected(get_post_meta($record->ID, '_shelter_security', true), 'Medium'); ?>>Medium</option>
                            <option value="Low" <?php selected(get_post_meta($record->ID, '_shelter_security', true), 'Low'); ?>>Low</option>
                        </select>
                    </td>
                </tr>
                <tr>
                    <th><label for="edit_safe_location">Safe Location</label></th>
                    <td>
                        <select id="edit_safe_location" name="safe_location">
                            <option value="Yes" <?php selected(get_post_meta($record->ID, '_safe_location', true), 'Yes'); ?>>Yes</option>
                            <option value="No" <?php selected(get_post_meta($record->ID, '_safe_location', true), 'No'); ?>>No</option>
                        </select>
                    </td>
                </tr>
                <tr>
                    <th><label for="edit_tipped_ears">Tipped Ears</label></th>
                    <td>
                        <select id="edit_tipped_ears" name="tipped_ears">
                            <option value="All" <?php selected(get_post_meta($record->ID, '_tipped_ears', true), 'All'); ?>>All</option>
                            <option value="Some" <?php selected(get_post_meta($record->ID, '_tipped_ears', true), 'Some'); ?>>Some</option>
                            <option value="None" <?php selected(get_post_meta($record->ID, '_tipped_ears', true), 'None'); ?>>None</option>
                        </select>
                    </td>
                </tr>
                <tr>
                    <th><label for="edit_winter_shelters">Winter Shelters</label></th>
                    <td>
                        <select id="edit_winter_shelters" name="winter_shelters">
                            <option value="Adequate" <?php selected(get_post_meta($record->ID, '_winter_shelters', true), 'Adequate'); ?>>Adequate</option>
                            <option value="Some" <?php selected(get_post_meta($record->ID, '_winter_shelters', true), 'Some'); ?>>Some</option>
                            <option value="None" <?php selected(get_post_meta($record->ID, '_winter_shelters', true), 'None'); ?>>None</option>
                        </select>
                    </td>
                </tr>
                <tr>
                    <th><label for="edit_notes">Notes</label></th>
                    <td><textarea id="edit_notes" name="notes" rows="4" cols="50"><?php echo esc_textarea(get_post_meta($record->ID, '_notes', true)); ?></textarea></td>
                </tr>
            </table>
            
            <p class="submit">
                <input type="submit" class="button-primary" value="Update Record" />
                <a href="<?php echo admin_url('admin.php?page=claws-colony-history'); ?>" class="button">Cancel</a>
            </p>
        </form>
        <?php
    }

    private function update_historical_record() {
        if (!isset($_POST['admin_nonce']) || !wp_verify_nonce($_POST['admin_nonce'], 'claws_admin_nonce')) {
            wp_die('Security check failed.');
        }

        $record_id = intval($_POST['record_id']);
        
        // Update all the meta fields
        $fields = array(
            '_colony_name' => sanitize_text_field($_POST['colony_name']),
            '_street_address' => sanitize_text_field($_POST['street_address']),
            '_city' => sanitize_text_field($_POST['city']),
            '_state' => sanitize_text_field($_POST['state']),
            '_zip' => sanitize_text_field($_POST['zip']),
            '_babies' => intval($_POST['babies']),
            '_kittens' => intval($_POST['kittens']),
            '_adults' => intval($_POST['adults']),
            '_seniors' => intval($_POST['seniors']),
            '_feeding_security' => sanitize_text_field($_POST['feeding_security']),
            '_water_security' => sanitize_text_field($_POST['water_security']),
            '_shelter_security' => sanitize_text_field($_POST['shelter_security']),
            '_safe_location' => sanitize_text_field($_POST['safe_location']),
            '_tipped_ears' => sanitize_text_field($_POST['tipped_ears']),
            '_winter_shelters' => sanitize_text_field($_POST['winter_shelters']),
            '_notes' => sanitize_textarea_field($_POST['notes'])
        );

        foreach ($fields as $key => $value) {
            update_post_meta($record_id, $key, $value);
        }

        // Also update the total cats meta field
        $total_cats = intval($_POST['babies']) + intval($_POST['kittens']) + intval($_POST['adults']) + intval($_POST['seniors']);
        update_post_meta($record_id, '_total_cats', $total_cats);

        // Redirect back to the main page with success message
        wp_redirect(admin_url('admin.php?page=claws-colony-history&updated=1'));
        exit;
    }

    private function show_edit_feeding_form($record) {
        ?>
        <h3>Edit Feeding Record</h3>
        <form method="post" action="">
            <input type="hidden" name="action" value="update_feeding" />
            <input type="hidden" name="record_id" value="<?php echo esc_attr($record['id']); ?>" />
            <input type="hidden" name="feeding_nonce" value="<?php echo wp_create_nonce('claws_feeding_nonce'); ?>" />
            
            <table class="form-table">
                <tr>
                    <th><label for="edit_kitten_name">Kitten Name</label></th>
                    <td><input type="text" id="edit_kitten_name" name="kitten_name" value="<?php echo esc_attr($record['kitten_name']); ?>" class="regular-text" required /></td>
                </tr>
                <tr>
                    <th><label for="edit_feeding_date">Feeding Date</label></th>
                    <td><input type="date" id="edit_feeding_date" name="feeding_date" value="<?php echo esc_attr($record['feeding_date']); ?>" required /></td>
                </tr>
                <tr>
                    <th><label for="edit_feeding_time">Feeding Time</label></th>
                    <td><input type="time" id="edit_feeding_time" name="feeding_time" value="<?php echo esc_attr($record['feeding_time']); ?>" required /></td>
                </tr>
                <tr>
                    <th><label for="edit_pre_weight">Pre Weight (g)</label></th>
                    <td><input type="number" id="edit_pre_weight" name="pre_weight" value="<?php echo esc_attr($record['pre_weight']); ?>" min="0" step="0.1" required /></td>
                </tr>
                <tr>
                    <th><label for="edit_post_weight">Post Weight (g)</label></th>
                    <td><input type="number" id="edit_post_weight" name="post_weight" value="<?php echo esc_attr($record['post_weight']); ?>" min="0" step="0.1" required /></td>
                </tr>
                <tr>
                    <th><label for="edit_notes">Notes</label></th>
                    <td><textarea id="edit_notes" name="notes" rows="4" cols="50"><?php echo esc_textarea($record['notes'] ?? ''); ?></textarea></td>
                </tr>
            </table>
            
            <p class="submit">
                <input type="submit" class="button-primary" value="Update Record" />
                <a href="<?php echo admin_url('admin.php?page=claws-feeding'); ?>" class="button">Cancel</a>
            </p>
        </form>
        <?php
    }

    private function update_feeding_record() {
        if (!isset($_POST['feeding_nonce']) || !wp_verify_nonce($_POST['feeding_nonce'], 'claws_feeding_nonce')) {
            wp_die('Security check failed.');
        }

        $record_id = intval($_POST['record_id']);
        $user_id = get_current_user_id();
        
        // Verify ownership
        $existing_record = $this->database->get_feeding_record($record_id);
        if (!$existing_record || $existing_record['user_id'] != $user_id) {
            wp_die('Access denied.');
        }

        // Update the feeding record
        $updated = $this->database->update_feeding_record($record_id, array(
            'kitten_name' => sanitize_text_field($_POST['kitten_name']),
            'date' => sanitize_text_field($_POST['feeding_date']),
            'time' => sanitize_text_field($_POST['feeding_time']),
            'pre_weight' => floatval($_POST['pre_weight']),
            'post_weight' => floatval($_POST['post_weight']),
            'notes' => sanitize_textarea_field($_POST['notes'])
        ), $user_id);

        if ($updated && !is_wp_error($updated)) {
            wp_redirect(admin_url('admin.php?page=claws-feeding&updated=1'));
        } else {
            wp_die('Failed to update feeding record.');
        }
        exit;
    }

    private function delete_feeding_record() {
        if (!isset($_POST['feeding_nonce']) || !wp_verify_nonce($_POST['feeding_nonce'], 'claws_feeding_nonce')) {
            wp_die('Security check failed.');
        }

        $record_id = intval($_POST['record_id']);
        $user_id = get_current_user_id();
        
        // Verify ownership
        $existing_record = $this->database->get_feeding_record($record_id);
        if (!$existing_record || $existing_record['user_id'] != $user_id) {
            wp_die('Access denied.');
        }

        // Delete the feeding record
        $deleted = $this->database->delete_feeding_record($record_id, $user_id);

        if ($deleted) {
            wp_redirect(admin_url('admin.php?page=claws-feeding&deleted=1'));
        } else {
            wp_die('Failed to delete feeding record.');
        }
        exit;
    }
}
?>