<?php
/**
 * Plugin Name: EveAI Sync
 * Plugin URI: https://askeveai.com/
 * Description: Synchronizes WordPress content with EveAI API.
 * Version: 2.0.3
 * Author: Josako, Pieter Laroy
 * Author URI: https://askeveai.com/about/
 * License: GPL v2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain: eveai-sync
 * Domain Path: /languages
 */

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

// Define plugin constants
define('EVEAI_SYNC_VERSION', '2.0.3');
define('EVEAI_SYNC_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('EVEAI_SYNC_PLUGIN_URL', plugin_dir_url(__FILE__));

// Include the main plugin class
require_once EVEAI_SYNC_PLUGIN_DIR . 'includes/class-eveai-sync.php';

// Initialize the plugin
function eveai_sync_init() {
    $plugin = new EveAI_Sync();
    $plugin->init();
}
add_action('plugins_loaded', 'eveai_sync_init');

// Set up activation and deactivation hooks
register_activation_hook(__FILE__, 'eveai_sync_activation');
register_deactivation_hook(__FILE__, 'eveai_sync_deactivation');

function eveai_sync_activation() {
    // Other activation tasks...
}

function eveai_sync_deactivation() {
    // Other deactivation tasks...
}

// Clean up meta when a post is permanently deleted
function eveai_delete_post_meta($post_id) {
    delete_post_meta($post_id, '_eveai_document_id');
    delete_post_meta($post_id, '_eveai_document_version_id');
}
add_action('before_delete_post', 'eveai_delete_post_meta');

// Clean metadata from Wordpress site
function eveai_reinitialize_site() {
    check_ajax_referer('eveai_reinitialize_site', 'nonce');

    if (!current_user_can('manage_options')) {
        wp_send_json_error('You do not have permission to perform this action.');
        return;
    }

    global $wpdb;

    // Remove all EveAI-related post meta
    $wpdb->query("DELETE FROM $wpdb->postmeta WHERE meta_key LIKE '_eveai_%'");

    // Remove all EveAI-related options
    delete_option('eveai_last_sync_time');
    delete_option('eveai_sync_status');

    // Optionally, you might want to clear any custom tables if you have any

    wp_send_json_success('Site reinitialized. All EveAI metadata has been removed.');
}
add_action('wp_ajax_eveai_reinitialize_site', 'eveai_reinitialize_site');

// Display sync info in post
function eveai_display_sync_info($post) {
    $document_id = get_post_meta($post->ID, '_eveai_document_id', true);
    $document_version_id = get_post_meta($post->ID, '_eveai_document_version_id', true);

    echo '<div class="misc-pub-section">';
    echo '<h4>EveAI Sync Info:</h4>';
    echo 'Document ID: ' . ($document_id ? esc_html($document_id) : 'Not set') . '<br>';
    echo 'Document Version ID: ' . ($document_version_id ? esc_html($document_version_id) : 'Not set');
    echo '</div>';
}
add_action('post_submitbox_misc_actions', 'eveai_display_sync_info');
