<?php
/**
 * Plugin Activator
 *
 * @package AIContentGenerator
 */

namespace AICG;

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

/**
 * Fired during plugin activation
 */
class Activator
{

    /**
     * Activation routine
     */
    public static function activate()
    {
        self::create_tables();
        self::set_default_options();

        // Clear any existing cron schedules
        wp_clear_scheduled_hook('roidaico_scheduled_publish');
        wp_clear_scheduled_hook('roidaico_keyword_check');

        // Flush rewrite rules
        flush_rewrite_rules();
    }

    /**
     * Create database tables
     */
    private static function create_tables()
    {
        global $wpdb;

        $charset_collate = $wpdb->get_charset_collate();

        // Keywords queue table
        $keywords_table = $wpdb->prefix . 'roidaico_keywords';
        $keywords_sql = "CREATE TABLE $keywords_table (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            keyword varchar(255) NOT NULL,
            category_id bigint(20) NOT NULL DEFAULT 0,
            status varchar(20) NOT NULL DEFAULT 'pending',
            post_id bigint(20) DEFAULT NULL,
            retries int(11) NOT NULL DEFAULT 0,
            error_message text DEFAULT NULL,
            language varchar(10) NOT NULL DEFAULT 'en',
            translation_of bigint(20) DEFAULT NULL,
            created_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
            processed_at datetime DEFAULT NULL,
            PRIMARY KEY (id),
            KEY category_id (category_id),
            KEY status (status),
            KEY keyword (keyword(191)),
            KEY translation_of (translation_of)
        ) $charset_collate;";

        // Schedules table
        $schedules_table = $wpdb->prefix . 'roidaico_schedules';
        $schedules_sql = "CREATE TABLE $schedules_table (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            name varchar(255) NOT NULL,
            category_id bigint(20) NOT NULL DEFAULT 0,
            days varchar(50) NOT NULL,
            times text NOT NULL,
            post_type varchar(50) NOT NULL DEFAULT 'post',
            author_id bigint(20) NOT NULL DEFAULT 0,
            options text DEFAULT NULL,
            enabled tinyint(1) NOT NULL DEFAULT 1,
            last_run datetime DEFAULT NULL,
            created_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            KEY category_id (category_id),
            KEY enabled (enabled)
        ) $charset_collate;";

        // Used images table (for duplicate prevention)
        $images_table = $wpdb->prefix . 'roidaico_used_images';
        $images_sql = "CREATE TABLE $images_table (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            pexels_id varchar(100) NOT NULL,
            image_hash varchar(64) NOT NULL,
            attachment_id bigint(20) DEFAULT NULL,
            used_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            UNIQUE KEY pexels_id (pexels_id),
            KEY image_hash (image_hash)
        ) $charset_collate;";

        // Generated posts log
        $posts_log_table = $wpdb->prefix . 'roidaico_posts_log';
        $posts_log_sql = "CREATE TABLE $posts_log_table (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            post_id bigint(20) NOT NULL,
            keyword_id bigint(20) NOT NULL,
            schedule_id bigint(20) DEFAULT NULL,
            generated_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            KEY post_id (post_id),
            KEY keyword_id (keyword_id)
        ) $charset_collate;";

        // Action logs
        $logs_table = $wpdb->prefix . 'roidaico_logs';
        $logs_sql = "CREATE TABLE $logs_table (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            action varchar(100) NOT NULL,
            message text NOT NULL,
            status varchar(20) NOT NULL DEFAULT 'info',
            schedule_id bigint(20) DEFAULT NULL,
            created_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            KEY action (action),
            KEY status (status),
            KEY schedule_id (schedule_id)
        ) $charset_collate;";

        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        dbDelta($keywords_sql);
        dbDelta($schedules_sql);
        dbDelta($images_sql);
        dbDelta($posts_log_sql);
        dbDelta($logs_sql);

        // Store database version
        update_option('roidaico_db_version', ROIDAICO_VERSION);
    }

    /**
     * Set default plugin options
     */
    private static function set_default_options()
    {
        $defaults = array(
            'ai_provider' => 'openrouter',
            'openrouter_api_key' => '',
            'openrouter_model' => 'openai/gpt-4o-mini',
            'pexels_api_key' => '',
            'default_tone' => 'professional',
            'default_length' => 'medium',
            'default_language' => 'en',
            'max_ready_articles' => 5,
            'min_interval_minutes' => 15,
            'auto_generate_keywords' => false,
            'auto_generate_instructions' => '',
            'enable_internal_links' => true,
            'max_internal_links' => 3,
            'seo_plugin' => 'auto', // auto, yoast, rankmath, none
            'image_source' => 'pexels',
            'ai_image_model' => 'black-forest-labs/flux-1-schnell',
        );

        foreach ($defaults as $key => $value) {
            if (get_option('roidaico_' . $key) === false) {
                update_option('roidaico_' . $key, $value);
            }
        }
    }
}
