<?php
/**
 * Plugin Name: Plugin Compass Community suggestions
 * Plugin URI: https://plugincompass.com/plugins/pc-community-suggestions-7d3f
 * Description: A community suggestions system where logged-in users can create and upvote improvement suggestions.
 * Version: 1.0.0
 * Author: Plugin Compass
 * Author URI: https://plugincompass.com
 * Text Domain: pc-community-suggestions-7d3f
 * Domain Path: /languages
 * Update URI: https://plugincompass.com/plugins/pc-community-suggestions-7d3f
 */

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

// Define plugin constants
define('PC_COMMUNITY_SUGGESTIONS_VERSION', '1.0.0');
define('PC_COMMUNITY_SUGGESTIONS_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('PC_COMMUNITY_SUGGESTIONS_PLUGIN_URL', plugin_dir_url(__FILE__));
define('PC_COMMUNITY_SUGGESTIONS_PLUGIN_BASENAME', plugin_basename(__FILE__));

// Prevent WordPress.org update checks
add_filter('site_transient_update_plugins', function($value) {
    $plugin_file = PC_COMMUNITY_SUGGESTIONS_PLUGIN_BASENAME;
    if (isset($value->response[$plugin_file])) {
        unset($value->response[$plugin_file]);
    }
    return $value;
});

// Activation hook
register_activation_hook(__FILE__, 'pc_community_suggestions_activate');
function pc_community_suggestions_activate() {
    require_once PC_COMMUNITY_SUGGESTIONS_PLUGIN_DIR . 'includes/class-database.php';
    PC_Community_Suggestions_Database::create_tables();
    
    // Set default options
    add_option('pc_community_suggestions_default_sort', 'popular');
    add_option('pc_community_suggestions_page_id', '0');
    add_option('pc_community_suggestions_page_created', false);
    
    // Create default page immediately
    pc_community_suggestions_create_default_page();
    
    // Flush rewrite rules to ensure URL routing works
    flush_rewrite_rules();
}

// Deactivation hook
register_deactivation_hook(__FILE__, 'pc_community_suggestions_deactivate');
function pc_community_suggestions_deactivate() {
    // Cleanup on deactivation if needed
}

// Create default suggestions page
function pc_community_suggestions_create_default_page() {
    // Check if page already exists
    $existing_page = get_page_by_path('suggestions');
    
    if ($existing_page) {
        update_option('pc_community_suggestions_page_id', $existing_page->ID);
        return;
    }
    
    $page_content = '<!-- wp:shortcode -->[community_suggestions]<!-- /wp:shortcode -->';
    
    $page_data = array(
        'post_title'    => __('Community Suggestions', 'pc-community-suggestions-7d3f'),
        'post_content'  => $page_content,
        'post_status'   => 'publish',
        'post_type'     => 'page',
        'post_name'     => 'suggestions',
        'post_author'   => 1 // Set to admin user
    );
    
    $page_id = wp_insert_post($page_data);
    
    if ($page_id && !is_wp_error($page_id)) {
        update_option('pc_community_suggestions_page_id', $page_id);
        
        // Flush rewrite rules to ensure the URL works immediately
        flush_rewrite_rules();
        
        // Also set this page as the option for our plugin
        update_option('pc_community_suggestions_page_created', true);
    }
}

// Add rewrite rule for /suggestions URL
function pc_community_suggestions_add_rewrite_rule() {
    add_rewrite_rule(
        '^suggestions/?$',
        'index.php?pagename=suggestions',
        'top'
    );
}
add_action('init', 'pc_community_suggestions_add_rewrite_rule');

// Handle template redirect for suggestions page
function pc_community_suggestions_template_include($template) {
    if (get_query_var('pagename') === 'suggestions') {
        // Check if the page exists, if not create it
        $page_id = get_option('pc_community_suggestions_page_id');
        if (!$page_id || !get_post($page_id)) {
            pc_community_suggestions_create_default_page();
        }
        
        // Use the page template if it exists
        $page_template = locate_template(array('page-suggestions.php', 'page.php', 'singular.php'));
        if ($page_template) {
            return $page_template;
        }
    }
    return $template;
}
add_filter('template_include', 'pc_community_suggestions_template_include');

// Query var for suggestions page
function pc_community_suggestions_query_vars($query_vars) {
    $query_vars[] = 'pagename';
    return $query_vars;
}
add_filter('query_vars', 'pc_community_suggestions_query_vars');

// Handle 404 for suggestions page and create it if needed
function pc_community_suggestions_handle_404() {
    if (is_404()) {
        $requested_url = $_SERVER['REQUEST_URI'];
        
        // Check if this is a request for /suggestions/
        if (preg_match('/^\/suggestions\/?$/', $requested_url) || strpos($requested_url, '/suggestions') !== false) {
            // Check if page exists
            $page_id = get_option('pc_community_suggestions_page_id');
            if (!$page_id || !get_post($page_id)) {
                // Create the page
                pc_community_suggestions_create_default_page();
                
                // Redirect to the newly created page
                $suggestions_url = home_url('/suggestions/');
                wp_redirect($suggestions_url);
                exit;
            }
        }
    }
}
add_action('template_redirect', 'pc_community_suggestions_handle_404', 1);

// Fallback handler - if no page is found for /suggestions, render our content
function pc_community_suggestions_fallback_handler() {
    if (is_404()) {
        $requested_path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
        
        if ($requested_path === '/suggestions/' || $requested_path === '/suggestions') {
            status_header(200);
            
            // Render the suggestions content directly
            $shortcode = new PC_Community_Suggestions_Shortcodes();
            echo $shortcode->render_suggestions_page();
            exit;
        }
    }
}
add_action('template_redirect', 'pc_community_suggestions_fallback_handler', 999);

// Load plugin classes
function pc_community_suggestions_init() {
    // Include required files
    require_once PC_COMMUNITY_SUGGESTIONS_PLUGIN_DIR . 'includes/class-database.php';
    require_once PC_COMMUNITY_SUGGESTIONS_PLUGIN_DIR . 'includes/class-shortcodes.php';
    require_once PC_COMMUNITY_SUGGESTIONS_PLUGIN_DIR . 'includes/class-rest-api.php';
    
    // Initialize REST API early to ensure AJAX handlers are registered
    $rest_api = new PC_Community_Suggestions_REST_API();
    
    // Initialize shortcodes
    new PC_Community_Suggestions_Shortcodes();
    
    if (is_admin()) {
        require_once PC_COMMUNITY_SUGGESTIONS_PLUGIN_DIR . 'admin/class-admin.php';
        new PC_Community_Suggestions_Admin();
    }
    
    // Ensure suggestions page exists on every load (safety check)
    $page_id = get_option('pc_community_suggestions_page_id');
    if (!$page_id || !get_post($page_id)) {
        pc_community_suggestions_create_default_page();
    }
}
add_action('plugins_loaded', 'pc_community_suggestions_init', 5);

// Enqueue scripts and styles
function pc_community_suggestions_enqueue_scripts() {
    // Frontend styles
    wp_enqueue_style(
        'pc-community-suggestions-frontend',
        PC_COMMUNITY_SUGGESTIONS_PLUGIN_URL . 'public/css/public-style.css',
        array(),
        PC_COMMUNITY_SUGGESTIONS_VERSION
    );
    
    // Frontend scripts
    wp_enqueue_script(
        'pc-community-suggestions-frontend',
        PC_COMMUNITY_SUGGESTIONS_PLUGIN_URL . 'public/js/public-script.js',
        array('jquery'),
        PC_COMMUNITY_SUGGESTIONS_VERSION,
        true
    );
    
    // Localize script for AJAX
    wp_localize_script('pc-community-suggestions-frontend', 'pcCommunitySuggestions', array(
        'ajax_url' => admin_url('admin-ajax.php'),
        'nonce' => wp_create_nonce('pc_community_suggestions_nonce'),
        'is_user_logged_in' => is_user_logged_in(),
        'i18n' => array(
            'fill_all_fields' => __('Please fill in all required fields.', 'pc-community-suggestions-7d3f'),
            'title_too_long' => __('Title must be less than 255 characters.', 'pc-community-suggestions-7d3f'),
            'login_to_vote' => __('You must be logged in to vote.', 'pc-community-suggestions-7d3f'),
            'login_to_submit' => __('You must be logged in to submit suggestions.', 'pc-community-suggestions-7d3f'),
            'ajax_error' => __('An error occurred. Please try again.', 'pc-community-suggestions-7d3f')
        )
    ));
}
add_action('wp_enqueue_scripts', 'pc_community_suggestions_enqueue_scripts');

// Admin enqueue
function pc_community_suggestions_admin_enqueue_scripts($hook) {
    if (strpos($hook, 'pc_community_suggestions') !== false) {
        wp_enqueue_style(
            'pc-community-suggestions-admin',
            PC_COMMUNITY_SUGGESTIONS_PLUGIN_URL . 'admin/css/admin-style.css',
            array(),
            PC_COMMUNITY_SUGGESTIONS_VERSION
        );
        
        wp_enqueue_script(
            'pc-community-suggestions-admin',
            PC_COMMUNITY_SUGGESTIONS_PLUGIN_URL . 'admin/js/admin-script.js',
            array('jquery'),
            PC_COMMUNITY_SUGGESTIONS_VERSION,
            true
        );
        
        // Localize admin script
        wp_localize_script('pc-community-suggestions-admin', 'pcCommunitySuggestionsAdmin', array(
            'nonce' => wp_create_nonce('pc_admin_nonce'),
            'ajax_url' => admin_url('admin-ajax.php'),
            'i18n' => array(
                'confirm_bulk_action' => __('Are you sure you want to perform this action on the selected suggestions?', 'pc-community-suggestions-7d3f'),
                'no_items_selected' => __('Please select at least one suggestion.', 'pc-community-suggestions-7d3f'),
                'action_failed' => __('The action failed. Please try again.', 'pc-community-suggestions-7d3f'),
                'loading' => __('Loading...', 'pc-community-suggestions-7d3f'),
                'processing' => __('Processing...', 'pc-community-suggestions-7d3f')
            )
        ));
    }
}
add_action('admin_enqueue_scripts', 'pc_community_suggestions_admin_enqueue_scripts');

// Add plugin action links
function pc_community_suggestions_action_links($links) {
    $settings_link = '<a href="' . admin_url('admin.php?page=pc_community_suggestions_settings') . '">' . __('Settings', 'pc-community-suggestions-7d3f') . '</a>';
    array_unshift($links, $settings_link);
    return $links;
}
add_filter('plugin_action_links_' . PC_COMMUNITY_SUGGESTIONS_PLUGIN_BASENAME, 'pc_community_suggestions_action_links');

// Load textdomain
function pc_community_suggestions_load_textdomain() {
    load_plugin_textdomain('pc-community-suggestions-7d3f', false, dirname(PC_COMMUNITY_SUGGESTIONS_PLUGIN_BASENAME) . '/languages');
}
add_action('plugins_loaded', 'pc_community_suggestions_load_textdomain');

// Manual page creation trigger (for debugging)
function pc_community_suggestions_manual_create_page() {
    if (isset($_GET['pc_create_suggestions_page']) && current_user_can('manage_options')) {
        check_admin_referer('pc_create_page_nonce');
        
        pc_community_suggestions_create_default_page();
        flush_rewrite_rules();
        
        $page_id = get_option('pc_community_suggestions_page_id');
        $page_url = get_permalink($page_id);
        
        wp_redirect(admin_url('admin.php?page=pc_community_suggestions_settings&created=1&url=' . urlencode($page_url)));
        exit;
    }
}
add_action('admin_init', 'pc_community_suggestions_manual_create_page');

// Note: Do not require the uninstall file here. WordPress will include `uninstall.php` when the plugin is uninstalled.
// The uninstall logic is self-contained in `uninstall.php` and should not run during normal plugin load.