<?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.0.53
 * Author: CLAWS Organization
 * License: GPL v2 or later
 * Text Domain: claws
 * Requires at least: 5.0
 * Tested up to: 6.4
 */
 
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,
                'has_addons'          => false,
                'has_paid_plans'      => true,
                'is_org_compliant'    => false,
                'trial'               => array(
                    'days'               => 7,
                    'is_require_payment' => true,
                ),
                'menu'                => array(
                    'slug'           => 'purralytics',
                    'support'        => false,
                ),
            ) );
        }

        return $pur_fs;
    }

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

/**
 * Helper function to check if user can access volunteer features
 * Deluxe plan only, or during trial period
 */
if ( ! function_exists( 'pur_can_use_volunteer_features' ) ) {
    function pur_can_use_volunteer_features() {
        // During trial, allow everything
        if ( pur_fs()->is_trial() ) {
            return true;
        }
        
        // Check if user has premium and is on deluxe plan
        if ( pur_fs()->can_use_premium_code__premium_only() ) {
            // If they're on deluxe plan (or higher), allow
            if ( pur_fs()->is_plan( 'deluxe', true ) ) {
                return true;
            }
        }
        
        return false;
    }
}


// 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.0.53');

/**
 * 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'));
        
        // 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);
        
        // 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();
        
        // 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();
        }
    }
    
    /**
     * 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 {
            // 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' => 'post',
                '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', 'editor', 'custom-fields', 'author', 'thumbnail'),
                'capability_type' => 'post',
                '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' => true,
                'supports' => array('title', 'editor', 'custom-fields', 'author', 'thumbnail'),
                'capability_type' => 'post',
                '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' => 'post',
                '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' => 'post',
                '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' => 'post',
                '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' => 'post',
                'has_archive' => false,
                'rewrite' => false
            );
            
            register_post_type('claws_volunteer_time', $volunteer_time_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'));
        }
    }
    
    /**
     * 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;
        }
    }
    
    /**
     * 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();
}
?>