<?php
/**
 * Plugin Name: Purralytics - Where Data Meets Compassion
 * Plugin URI: https://clawsva.org
 * Description: Advanced cat colony management and analytics system with user authentication, colony tracking, and geocoding.
 * Version: 2.2.39-SCROLL-FIX
 * Author: CLAWS Organization
 * License: GPL v2 or later
 * Text Domain: claws
 * Requires at least: 5.0
 * Tested up to: 6.4
 */
 
// Freemius SDK Integration
if ( ! function_exists( 'pur_fs' ) ) {
    // Create a helper function for easy SDK access.
    function pur_fs() {
        global $pur_fs;

        if ( ! isset( $pur_fs ) ) {
            // Include Freemius SDK.
            require_once dirname( __FILE__ ) . '/vendor/freemius/start.php';

            $pur_fs = fs_dynamic_init( array(
                'id'                  => '22129',
                'slug'                => 'purralytics',
                'premium_slug'        => 'purralytics',
                'type'                => 'plugin',
                'public_key'          => 'pk_5253d27bd0cee3c2a271f0ff1c1b6',
                'is_premium'          => true,
                'is_premium_only'     => true,   // TRUE = paid-only, no free version
                'has_addons'          => false,
                'has_paid_plans'      => true,
                'is_org_compliant'    => false,
                'menu'                => array(
                    'slug'           => 'purralytics',
                    'support'        => false,
                ),
            ) );
            
            // CRITICAL: Disable ALL Freemius redirects
            $pur_fs->add_filter('redirect_on_activation', '__return_false');
            
            // Block after-license-activation redirect
            $pur_fs->add_filter('after_license_activation_url', function($url) {
                error_log('PURRALYTICS: Freemius wants to redirect to: ' . $url);
                error_log('PURRALYTICS: BLOCKING redirect, returning plugins.php instead');
                return admin_url('plugins.php');
            });
            
            // Block connect redirect
            $pur_fs->add_filter('connect_url', function($url) {
                error_log('PURRALYTICS: Connect redirect blocked: ' . $url);
                return admin_url('plugins.php');
            });
            
            // Block after connect redirect  
            $pur_fs->add_filter('after_connect_url', function($url) {
                error_log('PURRALYTICS: After connect redirect blocked: ' . $url);
                return admin_url('plugins.php');
            });
            
            // Hide "custom implementation" banner on pricing page
            $pur_fs->add_filter('show_customizer_upsell', '__return_false');
            
            // Hide "Need more sites" message
            $pur_fs->add_filter('show_more_sites_link', '__return_false');
        }

        return $pur_fs;
    }

    // Init Freemius.
    pur_fs();
    // Signal that SDK was initiated.
    do_action( 'pur_fs_loaded' );
}

/**
 * Helper function to check if user has a valid paid license
 * Returns true only if user has purchased and activated a plan
 */
if ( ! function_exists( 'pur_has_access' ) ) {
    function pur_has_access() {
        if ( ! function_exists( 'pur_fs' ) ) {
            return false; // No Freemius = no access
        }
        
        // Check if user has an active, paid license
        if ( pur_fs()->can_use_premium_code() ) {
            return true;
        }
        
        return false; // No paid license = no access
    }
}

/**
 * NUCLEAR OPTION: Intercept ALL redirects to Purralytics admin page
 * If someone tries to redirect to page=purralytics, force them to plugins.php instead
 */
add_filter('wp_redirect', function($location, $status) {
    // Check if redirect is to Purralytics admin page
    if (strpos($location, 'page=purralytics') !== false || strpos($location, 'page=claws-admin') !== false) {
        error_log('PURRALYTICS: BLOCKED redirect to: ' . $location);
        error_log('PURRALYTICS: Forcing redirect to plugins.php instead');
        return admin_url('plugins.php');
    }
    return $location;
}, 999, 2); // Priority 999 = run very late, after everything else

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

// Define plugin constants
define('CLAWS_PLUGIN_URL', plugin_dir_url(__FILE__));
define('CLAWS_PLUGIN_PATH', plugin_dir_path(__FILE__));
define('CLAWS_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('CLAWS_VERSION', '2.2.39-SCROLL-FIX');

/**
 * Main CLAWS Plugin Class
 */
class CLAWSPlugin {
    
    private $error_log = array();
    private $admin;
    private $api;
    private $database;
    private $shortcodes;
    private $zapier;
    private $ai;
    
    public function __construct() {
        // Hook into WordPress
        add_action('init', array($this, 'init'));
        add_action('wp_enqueue_scripts', array($this, 'enqueue_scripts'));

        // Force classic editor for CLAWS record types so meta boxes render normally
        add_filter('use_block_editor_for_post_type', array($this, 'disable_block_editor'), 10, 2);
        
        // Track user activity for online status
        add_action('init', array($this, 'track_user_activity'));
        
        // Custom columns for admin lists
        add_filter('manage_claws_volunteer_time_posts_columns', array($this, 'task_columns'));
        add_action('manage_claws_volunteer_time_posts_custom_column', array($this, 'task_column_content'), 10, 2);
        add_filter('manage_claws_event_posts_columns', array($this, 'event_columns'));
        add_action('manage_claws_event_posts_custom_column', array($this, 'event_column_content'), 10, 2);
        
        // Intake edit meta boxes
        add_action('add_meta_boxes', array($this, 'add_intake_meta_boxes'));
        add_action('save_post_claws_intake', array($this, 'save_intake_meta'), 10, 1);
        
        // Plugin lifecycle
        register_activation_hook(__FILE__, array($this, 'activate'));
        register_deactivation_hook(__FILE__, array($this, 'deactivate'));
        
        // Error logging
        add_action('wp_footer', array($this, 'log_errors'));
    }
    
    public function init() {
        // Load required files
        $this->load_dependencies();
        
        // Initialize components
        $this->database = CLAWS_Database::getInstance();
        $this->admin = CLAWS_Admin::getInstance();
        $this->api = CLAWS_API::getInstance();
        $this->shortcodes = CLAWS_Shortcodes::getInstance();
        $this->zapier = CLAWS_Zapier::getInstance();
        $this->ai = CLAWS_AI::getInstance();
        
        // Run one-time message migration if needed
        $this->migrate_chat_messages();
        
        // Load text domain
        load_plugin_textdomain('claws', false, dirname(plugin_basename(__FILE__)) . '/languages/');
        
        // Only create post types if not in maintenance mode
        if (!defined('WP_INSTALLING') && !wp_installing()) {
            $this->create_post_types();
            $this->setup_capabilities();
        }
    }
    
    /**
     * Disable block editor for CLAWS record types so meta boxes render normally.
     *
     * @param bool   $use_block_editor Whether the block editor would be used.
     * @param string $post_type        Post type being checked.
     * @return bool
     */
    public function disable_block_editor($use_block_editor, $post_type) {
        if (in_array($post_type, array('claws_intake', 'claws_discharge'), true)) {
            return false;
        }
        return $use_block_editor;
    }


    /**
     * Track user activity for online status
     * Uses transient to track last activity (expires after 5 minutes)
     */
    public function track_user_activity() {
        if (is_user_logged_in()) {
            $user_id = get_current_user_id();
            // Set transient that expires in 5 minutes
            set_transient('claws_user_online_' . $user_id, true, 5 * MINUTE_IN_SECONDS);
        }
    }
    
    /**
     * Load required files
     */
    private function load_dependencies() {
        require_once CLAWS_PLUGIN_PATH . 'includes/class-database.php';
        require_once CLAWS_PLUGIN_PATH . 'includes/class-admin.php';
        require_once CLAWS_PLUGIN_PATH . 'includes/class-api.php';
        require_once CLAWS_PLUGIN_PATH . 'includes/class-shortcodes.php';
        require_once CLAWS_PLUGIN_PATH . 'includes/class-zapier.php';
        require_once CLAWS_PLUGIN_PATH . 'includes/class-ai.php';
    }
    
    /**
     * Create custom post types - with better error handling
     */
    public function create_post_types() {
        try {
            // Helper function to create proper custom capabilities
            $get_custom_caps = function($singular, $plural) {
                return array(
                    'edit_post' => "edit_{$singular}",
                    'read_post' => "read_{$singular}",
                    'delete_post' => "delete_{$singular}",
                    'edit_posts' => "edit_{$plural}",
                    'edit_others_posts' => "edit_others_{$plural}",
                    'publish_posts' => "publish_{$plural}",
                    'read_private_posts' => "read_private_{$plural}",
                    'delete_posts' => "delete_{$plural}",
                    'delete_private_posts' => "delete_private_{$plural}",
                    'delete_published_posts' => "delete_published_{$plural}",
                    'delete_others_posts' => "delete_others_{$plural}",
                    'edit_private_posts' => "edit_private_{$plural}",
                    'edit_published_posts' => "edit_published_{$plural}",
                    'create_posts' => "edit_{$plural}"
                );
            };
            
            // Colonies - role-based visibility
            $colony_args = array(
                'labels' => array(
                    'name' => __('Colonies', 'claws'),
                    'singular_name' => __('Colony', 'claws'),
                    'menu_name' => __('Cat Colonies', 'claws'),
                    'add_new' => __('Add New Colony', 'claws'),
                    'edit_item' => __('Edit Colony', 'claws'),
                    'view_item' => __('View Colony', 'claws'),
                ),
                'public' => false,
                'show_ui' => true,
                'show_in_menu' => 'claws-admin',
                'show_in_rest' => true,
                'supports' => array('title', 'custom-fields', 'author'),
                'capability_type' => 'claws_colony',
                'map_meta_cap' => true,
                'capabilities' => $get_custom_caps('claws_colony', 'claws_colonies'),
                'menu_icon' => 'dashicons-location-alt',
                'has_archive' => false,
                'rewrite' => false
            );
            
            register_post_type('claws_colony', $colony_args);
            
            // Intakes - private to each user
            $intake_args = array(
                'labels' => array(
                    'name' => __('Intakes', 'claws'),
                    'singular_name' => __('Intake', 'claws'),
                    'menu_name' => __('Cat Intakes', 'claws'),
                    'add_new' => __('Add New Intake', 'claws'),
                    'add_new_item' => __('Add New Intake', 'claws'),
                    'edit_item' => __('Edit Intake', 'claws'),
                    'new_item' => __('New Intake', 'claws'),
                    'view_item' => __('View Intake', 'claws'),
                    'view_items' => __('View Intakes', 'claws'),
                    'search_items' => __('Search Intakes', 'claws'),
                    'not_found' => __('No intakes found.', 'claws'),
                    'not_found_in_trash' => __('No intakes found in Trash.', 'claws'),
                    'all_items' => __('All Intakes', 'claws'),
                ),
                'public' => false,
                'show_ui' => true,
                'show_in_menu' => 'claws-admin',
                'show_in_rest' => true,
                'supports' => array('title', 'custom-fields', 'author'),
                'capability_type' => 'claws_intake',
                'map_meta_cap' => true,
                'capabilities' => $get_custom_caps('claws_intake', 'claws_intakes'),
                'has_archive' => false,
                'rewrite' => false
            );
            
            register_post_type('claws_intake', $intake_args);
            
            // Discharges - private to each user
            $discharge_args = array(
                'labels' => array(
                    'name' => __('Discharges', 'claws'),
                    'singular_name' => __('Discharge', 'claws'),
                    'menu_name' => __('Cat Discharges', 'claws'),
                    'add_new' => __('Add New Discharge', 'claws'),
                    'add_new_item' => __('Add New Discharge', 'claws'),
                    'edit_item' => __('Edit Discharge', 'claws'),
                    'new_item' => __('New Discharge', 'claws'),
                    'view_item' => __('View Discharge', 'claws'),
                    'view_items' => __('View Discharges', 'claws'),
                    'search_items' => __('Search Discharges', 'claws'),
                    'not_found' => __('No discharges found.', 'claws'),
                    'not_found_in_trash' => __('No discharges found in Trash.', 'claws'),
                    'all_items' => __('All Discharges', 'claws'),
                ),
                'public' => false,
                'show_ui' => true,
                'show_in_menu' => 'claws-admin',
                'show_in_rest' => false,
                'supports' => array('title', 'custom-fields', 'author'),
                'capability_type' => 'claws_discharge',
                'map_meta_cap' => true,
                'capabilities' => $get_custom_caps('claws_discharge', 'claws_discharges'),
                'has_archive' => false,
                'rewrite' => false
            );
            
            register_post_type('claws_discharge', $discharge_args);
            
            // Colony History - for tracking changes over time (like feeding records)
            $history_args = array(
                'labels' => array(
                    'name' => __('Colony History', 'claws'),
                    'singular_name' => __('Colony History Record', 'claws'),
                    'menu_name' => __('Colony History', 'claws'),
                ),
                'public' => false,
                'show_ui' => false, // Hidden from admin UI - managed programmatically
                'show_in_rest' => false,
                'supports' => array('title', 'custom-fields', 'author'),
                'capability_type' => 'claws_discharge',
                'map_meta_cap' => true,
                'capabilities' => $get_custom_caps('claws_discharge', 'claws_discharges'),
                'has_archive' => false,
                'rewrite' => false
            );
            
            register_post_type('claws_colony_history', $history_args);
            
            // Event post type (includes both events and projects)
            $event_args = array(
                'labels' => array(
                    'name' => __('Events & Projects', 'claws'),
                    'singular_name' => __('Event/Project', 'claws'),
                    'add_new' => 'Add Event/Project',
                    'add_new_item' => 'Add New Event/Project',
                    'edit_item' => 'Edit Event/Project',
                    'view_item' => 'View Event/Project',
                    'search_items' => 'Search Events/Projects',
                    'not_found' => 'No events/projects found'
                ),
                'public' => false,
                'show_ui' => true,
                'show_in_menu' => false, // We'll add it manually via add_admin_menus
                'supports' => array('title', 'custom-fields', 'author'),
                'capability_type' => 'claws_discharge',
                'map_meta_cap' => true,
                'capabilities' => $get_custom_caps('claws_discharge', 'claws_discharges'),
                'has_archive' => false,
                'rewrite' => false
            );
            
            register_post_type('claws_event', $event_args);
            
            // Chat messages post type
            $message_args = array(
                'label' => 'Chat Messages',
                'public' => false,
                'show_ui' => false,
                'show_in_menu' => false,
                'supports' => array('title', 'editor', 'author', 'custom-fields'),
                'capability_type' => 'claws_discharge',
                'map_meta_cap' => true,
                'capabilities' => $get_custom_caps('claws_discharge', 'claws_discharges'),
                'has_archive' => false,
                'rewrite' => false
            );
            
            register_post_type('claws_message', $message_args);
            
            // Volunteer time tracking post type
            $volunteer_time_args = array(
                'label' => 'Volunteer Time',
                'labels' => array(
                    'name' => 'Volunteer Tasks',
                    'singular_name' => 'Task',
                    'add_new' => 'Add Task',
                    'add_new_item' => 'Add New Task',
                    'edit_item' => 'Edit Task',
                    'view_item' => 'View Task',
                    'search_items' => 'Search Tasks',
                    'not_found' => 'No tasks found'
                ),
                'public' => false,
                'show_ui' => true,
                'show_in_menu' => false, // We'll add it manually via add_admin_menus
                'supports' => array('title', 'author', 'custom-fields'),
                'capability_type' => 'claws_discharge',
                'map_meta_cap' => true,
                'capabilities' => $get_custom_caps('claws_discharge', 'claws_discharges'),
                'has_archive' => false,
                'rewrite' => false
            );
            
            register_post_type('claws_volunteer_time', $volunteer_time_args);
            
            // Donor post type
            $donor_args = array(
                'public' => false,
                'show_ui' => true,
                'show_in_menu' => false, // We're adding it to our custom menu
                'show_in_rest' => false,
                'supports' => array('title'),
                'capability_type' => 'claws_discharge',
                'map_meta_cap' => true,
                'capabilities' => $get_custom_caps('claws_discharge', 'claws_discharges'),
                'map_meta_cap' => true,
                'labels' => array(
                    'name' => 'Donors',
                    'singular_name' => 'Donor',
                    'add_new' => 'Add New',
                    'add_new_item' => 'Add New Donor',
                    'edit_item' => 'Edit Donor',
                    'new_item' => 'New Donor',
                    'view_item' => 'View Donor',
                    'search_items' => 'Search Donors',
                    'not_found' => 'No donors found',
                    'not_found_in_trash' => 'No donors found in trash'
                )
            );
            register_post_type('claws_donor', $donor_args);
            
            // Sponsor post type
            $sponsor_args = array(
                'public' => false,
                'show_ui' => true,
                'show_in_menu' => false, // We're adding it to our custom menu
                'show_in_rest' => false,
                'supports' => array('title'),
                'capability_type' => 'claws_discharge',
                'map_meta_cap' => true,
                'capabilities' => $get_custom_caps('claws_discharge', 'claws_discharges'),
                'map_meta_cap' => true,
                'labels' => array(
                    'name' => 'Sponsors',
                    'singular_name' => 'Sponsor',
                    'add_new' => 'Add New',
                    'add_new_item' => 'Add New Sponsor',
                    'edit_item' => 'Edit Sponsor',
                    'new_item' => 'New Sponsor',
                    'view_item' => 'View Sponsor',
                    'search_items' => 'Search Sponsors',
                    'not_found' => 'No sponsors found',
                    'not_found_in_trash' => 'No sponsors found in trash'
                )
            );
            register_post_type('claws_sponsor', $sponsor_args);
            
            // Volunteer Application post type
            $volunteer_app_args = array(
                'public' => false,
                'show_ui' => true,
                'show_in_menu' => false, // We're adding it to our custom menu
                'show_in_rest' => false,
                'supports' => array('title'),
                'capability_type' => 'claws_discharge',
                'map_meta_cap' => true,
                'capabilities' => $get_custom_caps('claws_discharge', 'claws_discharges'),
                'map_meta_cap' => true,
                'labels' => array(
                    'name' => 'Volunteers',
                    'singular_name' => 'Volunteer',
                    'add_new' => 'Add New',
                    'add_new_item' => 'Add New Volunteer',
                    'edit_item' => 'Edit Volunteer',
                    'new_item' => 'New Volunteer',
                    'view_item' => 'View Volunteer',
                    'search_items' => 'Search Volunteers',
                    'not_found' => 'No volunteers found',
                    'not_found_in_trash' => 'No volunteers found in trash'
                )
            );
            register_post_type('claws_volunteer_app', $volunteer_app_args);
            
            // Contact post type
            $contact_args = array(
                'public' => false,
                'show_ui' => true,
                'show_in_menu' => false, // We're adding it to our custom menu
                'show_in_rest' => false,
                'supports' => array('title'),
                'capability_type' => 'claws_contact',  // FIXED: was claws_discharge
                'map_meta_cap' => true,
                'capabilities' => $get_custom_caps('claws_contact', 'claws_contacts'),  // FIXED
                'labels' => array(
                    'name' => 'Contacts',
                    'singular_name' => 'Contact',
                    'add_new' => 'Add New',
                    'add_new_item' => 'Add New Contact',
                    'edit_item' => 'Edit Contact',
                    'new_item' => 'New Contact',
                    'view_item' => 'View Contact',
                    'search_items' => 'Search Contacts',
                    'not_found' => 'No contacts found',
                    'not_found_in_trash' => 'No contacts found in trash'
                )
            );
            register_post_type('claws_contact', $contact_args);
            
        } catch (Exception $e) {
            $this->error_log[] = 'Failed to create post types: ' . $e->getMessage();
            claws_log('CLAWS Plugin Error: ' . $e->getMessage(), 'error');
        }
    }
    
    /**
     * Setup user capabilities for three-role system: Contributor, Author, Admin
     */
    public function setup_capabilities() {
        try {
            // Contributors have edit_posts by default but need publish_posts and upload_files
            $contributor_role = get_role('contributor');
            if ($contributor_role) {
                $contributor_role->add_cap('publish_posts');
                $contributor_role->add_cap('upload_files');
            }
            
            // Authors already have all needed capabilities by default
            $author_role = get_role('author');
            if ($author_role) {
                // Authors already have edit_posts, publish_posts, upload_files
            }
            
            // Admins: Can see everything
            $admin_role = get_role('administrator');
            if ($admin_role) {
                $admin_role->add_cap('manage_claws');
                // Admins already have all capabilities
            }
            
            claws_log('CLAWS three-role capability system initialized: Contributor, Author, Admin');
        } catch (Exception $e) {
            $this->error_log[] = 'Failed to setup capabilities: ' . $e->getMessage();
        }
    }
    
    /**
     * Enqueue scripts safely
     */
    public function enqueue_scripts() {
        global $post;
        if (is_a($post, 'WP_Post') && has_shortcode($post->post_content, 'claws_app')) {
            wp_enqueue_script('wp-api');
            
            wp_localize_script('wp-api', 'wpApiSettings', array(
                'root' => esc_url_raw(rest_url()),
                'nonce' => wp_create_nonce('wp_rest'),
                'currentUserId' => get_current_user_id(),
                'userId' => get_current_user_id(), // Alias for consistency
                'userCan' => array(
                    'manage_options' => current_user_can('manage_options'),
                    'edit_others_posts' => current_user_can('edit_others_posts')
                )
            ));
        }
    }
    
    /**
     * Plugin activation
     */
    public function activate() {
        try {
            $this->load_dependencies();
            
            // Create database tables
            CLAWS_Database::create_tables();
            
            // Migrate database tables to remove unused columns
            CLAWS_Database::migrate_feeding_records_table();
            
            // Create initial historical records for existing colonies
            $database = CLAWS_Database::getInstance();
            $database->create_initial_colony_history_posts();
            
            $this->create_post_types();
            flush_rewrite_rules();
            
            // Trigger additional flush for post type fixes
            CLAWS_Admin::trigger_rewrite_flush();
            CLAWS_Admin::emergency_flush_rewrite_rules();
            
            // Ensure admin capabilities
            $admin_role = get_role('administrator');
            if ($admin_role) {
                $admin_role->add_cap('manage_claws');
            }
            
            claws_log('CLAWS Plugin activated successfully');
            
        } catch (Exception $e) {
            claws_log('CLAWS Activation Error: ' . $e->getMessage(), 'error');
            wp_die(__('CLAWS Plugin could not be activated safely. Please check your error logs.', 'claws'));
        }
    }
    
    /**
     * Migrate old chat messages to include recipient_id
     * One-time migration for existing messages
     */
    public function migrate_chat_messages() {
        // Check if migration already done
        $migration_done = get_option('claws_chat_messages_migrated', false);
        if ($migration_done) {
            return;
        }
        
        claws_log('Starting chat message migration...', 'info');
        
        // Get all individual chat messages without recipient_id
        $messages = get_posts(array(
            'post_type' => 'claws_message',
            'post_status' => 'publish',
            'posts_per_page' => -1,
            'meta_query' => array(
                array(
                    'key' => 'chat_type',
                    'value' => 'individual',
                    'compare' => '='
                )
            )
        ));
        
        $updated = 0;
        foreach ($messages as $message) {
            $recipient_id = get_post_meta($message->ID, 'recipient_id', true);
            
            // If recipient_id doesn't exist, add it from chat_id
            if (empty($recipient_id)) {
                $chat_id = get_post_meta($message->ID, 'chat_id', true);
                if ($chat_id) {
                    update_post_meta($message->ID, 'recipient_id', $chat_id);
                    update_post_meta($message->ID, 'is_read', '1'); // Mark old messages as read
                    $updated++;
                }
            }
        }
        
        // Mark migration as complete
        update_option('claws_chat_messages_migrated', true);
        claws_log("Chat message migration complete. Updated $updated messages.", 'info');
    }
    
    /**
     * Plugin deactivation
     */
    public function deactivate() {
        flush_rewrite_rules();
        claws_log('CLAWS Plugin deactivated');
    }
    
    /**
     * Define custom columns for volunteer tasks admin list
     */
    public function task_columns($columns) {
        $new_columns = array(
            'cb' => $columns['cb'],
            'title' => 'Task',
            'volunteer' => 'Volunteer',
            'task_type' => 'Type',
            'date' => 'Date',
            'hours' => 'Hours',
            'status' => 'Status',
            'coordinator' => 'Coordinator'
        );
        return $new_columns;
    }
    
    /**
     * Display custom column content for volunteer tasks
     */
    public function task_column_content($column, $post_id) {
        switch ($column) {
            case 'volunteer':
                $volunteer_id = get_post_meta($post_id, 'volunteer_id', true);
                $volunteer = get_user_by('ID', $volunteer_id);
                echo $volunteer ? esc_html($volunteer->display_name) : 'Unknown';
                break;
                
            case 'task_type':
                echo esc_html(get_post_meta($post_id, 'task_type', true));
                break;
                
            case 'date':
                echo esc_html(get_post_meta($post_id, 'date', true));
                break;
                
            case 'hours':
                echo esc_html(get_post_meta($post_id, 'hours', true));
                break;
                
            case 'status':
                $status = get_post_meta($post_id, 'approval_status', true);
                $colors = array(
                    'pending' => '#f59e0b',
                    'approved' => '#10b981',
                    'rejected' => '#ef4444'
                );
                $color = $colors[$status] ?? '#6b7280';
                echo '<span style="padding: 4px 8px; background: ' . $color . '; color: white; border-radius: 4px; font-size: 11px; font-weight: 600; text-transform: uppercase;">' . esc_html($status ?: 'unknown') . '</span>';
                break;
                
            case 'coordinator':
                $coord_id = get_post_meta($post_id, 'coordinator_id', true);
                $coord = get_user_by('ID', $coord_id);
                echo $coord ? esc_html($coord->display_name) : 'Unknown';
                break;
        }
    }
    
    /**
     * Define custom columns for events/projects admin list
     */
    public function event_columns($columns) {
        $new_columns = array(
            'cb' => $columns['cb'],
            'title' => 'Name',
            'type' => 'Type',
            'lead' => 'Lead',
            'date' => 'Date',
            'spots' => 'Volunteer Spots',
            'category' => 'Category'
        );
        return $new_columns;
    }
    
    /**
     * Display custom column content for events/projects
     */
    public function event_column_content($column, $post_id) {
        switch ($column) {
            case 'type':
                $date = get_post_meta($post_id, 'event_date', true);
                $start_time = get_post_meta($post_id, 'start_time', true);
                if ($date && $start_time) {
                    echo '<span style="padding: 4px 8px; background: #3b82f6; color: white; border-radius: 4px; font-size: 11px; font-weight: 600;">EVENT</span>';
                } else {
                    echo '<span style="padding: 4px 8px; background: #8b5cf6; color: white; border-radius: 4px; font-size: 11px; font-weight: 600;">PROJECT</span>';
                }
                break;
                
            case 'lead':
                $lead_id = get_post_meta($post_id, 'lead_id', true);
                $lead = get_user_by('ID', $lead_id);
                echo $lead ? esc_html($lead->display_name) : 'Not assigned';
                break;
                
            case 'date':
                $date = get_post_meta($post_id, 'event_date', true);
                if ($date) {
                    echo esc_html(date('M j, Y', strtotime($date)));
                } else {
                    echo '<em style="color: #6b7280;">Ongoing</em>';
                }
                break;
                
            case 'spots':
                $num_volunteers = get_post_meta($post_id, 'num_volunteers', true);
                $spots = get_post_meta($post_id, 'volunteer_spots', true);
                $filled = is_array($spots) ? count(array_filter($spots, function($s) { return !empty($s['reserved']); })) : 0;
                echo esc_html($filled . ' / ' . $num_volunteers);
                break;
                
            case 'category':
                echo esc_html(get_post_meta($post_id, 'category', true));
                break;
        }
    }
    
    /**
     * Register meta boxes for intake edit screen
     */
    public function add_intake_meta_boxes() {
        add_meta_box(
            'claws_intake_details',
            'Intake Details',
            array($this, 'render_intake_meta_box'),
            'claws_intake',
            'normal',
            'high'
        );
    }
    
    /**
     * Render the intake meta box
     */
    public function render_intake_meta_box($post) {
        // Add nonce for security
        wp_nonce_field('claws_save_intake_meta', 'claws_intake_nonce');
        
        // Get current values
        $cat_name = get_post_meta($post->ID, 'cat_name', true);
        $age = get_post_meta($post->ID, 'age', true);
        $gender = get_post_meta($post->ID, 'gender', true);
        $coat = get_post_meta($post->ID, 'coat', true);
        $color = get_post_meta($post->ID, 'color', true);
        $type = get_post_meta($post->ID, 'type', true);
        $fiv = get_post_meta($post->ID, 'fiv', true);
        $special_needs = get_post_meta($post->ID, 'special_needs', true);
        $notes = get_post_meta($post->ID, 'notes', true);
        $intake_date = get_post_meta($post->ID, 'intake_date', true);
        $contact_first_name = get_post_meta($post->ID, 'contact_first_name', true);
        $contact_last_name = get_post_meta($post->ID, 'contact_last_name', true);
        $contact_phone = get_post_meta($post->ID, 'contact_phone', true);
        $contact_email = get_post_meta($post->ID, 'contact_email', true);
        
        ?>
        <style>
            .claws-meta-field { margin-bottom: 15px; }
            .claws-meta-field label { display: block; font-weight: 600; margin-bottom: 5px; }
            .claws-meta-field input[type="text"],
            .claws-meta-field input[type="date"],
            .claws-meta-field input[type="email"],
            .claws-meta-field input[type="tel"],
            .claws-meta-field select,
            .claws-meta-field textarea { width: 100%; padding: 6px 8px; }
            .claws-meta-field textarea { min-height: 80px; }
            .claws-checkbox-field { display: flex; align-items: center; gap: 8px; margin-bottom: 10px; }
            .claws-checkbox-field input[type="checkbox"] { width: auto; }
            .claws-two-col { display: grid; grid-template-columns: 1fr 1fr; gap: 15px; }
        </style>
        
        <div class="claws-meta-field">
            <label>Intake Date *</label>
            <input type="date" name="claws_intake_date" value="<?php echo esc_attr($intake_date); ?>" required>
        </div>
        
        <h3>Cat Information</h3>
        <div class="claws-meta-field">
            <label>Cat Name *</label>
            <input type="text" name="claws_cat_name" value="<?php echo esc_attr($cat_name); ?>" required>
        </div>
        
        <div class="claws-two-col">
            <div class="claws-meta-field">
                <label>Age *</label>
                <select name="claws_age" required>
                    <option value="">Select age category</option>
                    <option value="Newborn (0-8 weeks)" <?php selected($age, 'Newborn (0-8 weeks)'); ?>>Newborn (0-8 weeks)</option>
                    <option value="Kitten (2-5 months)" <?php selected($age, 'Kitten (2-5 months)'); ?>>Kitten (2-5 months)</option>
                    <option value="Cat (6 months to 8 years)" <?php selected($age, 'Cat (6 months to 8 years)'); ?>>Cat (6 months to 8 years)</option>
                    <option value="Senior (Older than 8 years)" <?php selected($age, 'Senior (Older than 8 years)'); ?>>Senior (Older than 8 years)</option>
                </select>
            </div>
            
            <div class="claws-meta-field">
                <label>Gender *</label>
                <select name="claws_gender" required>
                    <option value="">Select gender</option>
                    <option value="Male" <?php selected($gender, 'Male'); ?>>Male</option>
                    <option value="Female" <?php selected($gender, 'Female'); ?>>Female</option>
                    <option value="Unknown" <?php selected($gender, 'Unknown'); ?>>Unknown</option>
                </select>
            </div>
        </div>
        
        <div class="claws-two-col">
            <div class="claws-meta-field">
                <label>Coat</label>
                <select name="claws_coat">
                    <option value="">Select coat type</option>
                    <option value="Short" <?php selected($coat, 'Short'); ?>>Short</option>
                    <option value="Medium" <?php selected($coat, 'Medium'); ?>>Medium</option>
                    <option value="Long" <?php selected($coat, 'Long'); ?>>Long</option>
                    <option value="Hairless" <?php selected($coat, 'Hairless'); ?>>Hairless</option>
                </select>
            </div>
            
            <div class="claws-meta-field">
                <label>Color</label>
                <input type="text" name="claws_color" value="<?php echo esc_attr($color); ?>" placeholder="e.g., Orange tabby, Black">
            </div>
        </div>
        
        <div class="claws-meta-field">
            <label>Type</label>
            <select name="claws_type">
                <option value="">Select cat type</option>
                <option value="Stray" <?php selected($type, 'Stray'); ?>>Stray</option>
                <option value="Feral" <?php selected($type, 'Feral'); ?>>Feral</option>
                <option value="Friendly/Socialized" <?php selected($type, 'Friendly/Socialized'); ?>>Friendly/Socialized</option>
                <option value="Semi-feral" <?php selected($type, 'Semi-feral'); ?>>Semi-feral</option>
                <option value="Colony Cat" <?php selected($type, 'Colony Cat'); ?>>Colony Cat</option>
            </select>
        </div>
        
        <div class="claws-checkbox-field">
            <input type="checkbox" name="claws_fiv" id="claws_fiv" value="1" <?php checked($fiv, '1'); ?>>
            <label for="claws_fiv" style="margin: 0; font-weight: 600;">FIV?</label>
        </div>
        
        <div class="claws-checkbox-field">
            <input type="checkbox" name="claws_special_needs" id="claws_special_needs" value="1" <?php checked($special_needs, '1'); ?>>
            <label for="claws_special_needs" style="margin: 0; font-weight: 600;">Special Needs</label>
        </div>
        
        <div class="claws-meta-field">
            <label>Notes</label>
            <textarea name="claws_notes"><?php echo esc_textarea($notes); ?></textarea>
        </div>
        
        <h3>Contact Information</h3>
        <div class="claws-two-col">
            <div class="claws-meta-field">
                <label>First Name</label>
                <input type="text" name="claws_contact_first_name" value="<?php echo esc_attr($contact_first_name); ?>">
            </div>
            
            <div class="claws-meta-field">
                <label>Last Name</label>
                <input type="text" name="claws_contact_last_name" value="<?php echo esc_attr($contact_last_name); ?>">
            </div>
        </div>
        
        <div class="claws-two-col">
            <div class="claws-meta-field">
                <label>Phone</label>
                <input type="tel" name="claws_contact_phone" value="<?php echo esc_attr($contact_phone); ?>">
            </div>
            
            <div class="claws-meta-field">
                <label>Email</label>
                <input type="email" name="claws_contact_email" value="<?php echo esc_attr($contact_email); ?>">
            </div>
        </div>
        <?php
    }
    
    /**
     * Save intake meta box data
     */
    public function save_intake_meta($post_id) {
        // Check nonce
        if (!isset($_POST['claws_intake_nonce']) || !wp_verify_nonce($_POST['claws_intake_nonce'], 'claws_save_intake_meta')) {
            return;
        }
        
        // Check autosave
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
            return;
        }
        
        // Check permissions
        if (!current_user_can('edit_post', $post_id)) {
            return;
        }
        
        // Save all fields
        $fields = array(
            'claws_intake_date' => 'intake_date',
            'claws_cat_name' => 'cat_name',
            'claws_age' => 'age',
            'claws_gender' => 'gender',
            'claws_coat' => 'coat',
            'claws_color' => 'color',
            'claws_type' => 'type',
            'claws_notes' => 'notes',
            'claws_contact_first_name' => 'contact_first_name',
            'claws_contact_last_name' => 'contact_last_name',
            'claws_contact_phone' => 'contact_phone',
            'claws_contact_email' => 'contact_email'
        );
        
        foreach ($fields as $form_field => $meta_key) {
            if (isset($_POST[$form_field])) {
                update_post_meta($post_id, $meta_key, sanitize_text_field($_POST[$form_field]));
            }
        }
        
        // Save checkboxes (they won't be in POST if unchecked)
        update_post_meta($post_id, 'fiv', isset($_POST['claws_fiv']) ? '1' : '0');
        update_post_meta($post_id, 'special_needs', isset($_POST['claws_special_needs']) ? '1' : '0');
        
        // Also save as 'date' for compatibility
        if (isset($_POST['claws_intake_date'])) {
            update_post_meta($post_id, 'date', sanitize_text_field($_POST['claws_intake_date']));
        }
        
        // Update post title
        if (isset($_POST['claws_cat_name']) && isset($_POST['claws_intake_date'])) {
            $new_title = sanitize_text_field($_POST['claws_cat_name']) . ' - ' . sanitize_text_field($_POST['claws_intake_date']);
            wp_update_post(array(
                'ID' => $post_id,
                'post_title' => $new_title
            ));
        }
    }
    
    /**
     * Log errors for debugging
     */
    public function log_errors() {
        if (!empty($this->error_log) && current_user_can('manage_options')) {
            echo '<!-- CLAWS Plugin Errors: ' . esc_html(implode(', ', $this->error_log)) . ' -->';
        }
    }
}

/**
 * Utility function for logging
 */
if (!function_exists('claws_log')) {
    function claws_log($message, $level = 'info') {
        if (defined('WP_DEBUG') && WP_DEBUG) {
            error_log('CLAWS [' . strtoupper($level) . ']: ' . $message);
        }
    }
}

// Initialize the plugin safely
if (class_exists('CLAWSPlugin')) {
    new CLAWSPlugin();
}
?>