<?php
/**
 * Author: Rymera Web Co
 *
 * @package SAAI\Actions
 */

namespace SAAI\Actions;

use SAAI\Abstracts\Abstract_Class;
use SAAI\Post_Types\Product_Question_Post_Type;
use SAAI\Updates\Version_1_0_6;
use SAAI\Updates\Skip_Onboarding_For_Updates;
use SAAI\Updates\Version_1_1_2;

/**
 * Activation class.
 *
 * @since 1.0.0
 */
class Activation extends Abstract_Class {

    const PLUGIN_INSTALLED_TIMESTAMP = 'saai_plugin_installed_timestamp';

    /**
     * Holds boolean value whether the plugin is being activated network wide.
     *
     * @var bool
     */
    protected $network_wide;

    /**
     * Constructor.
     *
     * @param bool $network_wide Whether the plugin is being activated network wide.
     */
    public function __construct( $network_wide = false ) {

        $this->network_wide         = $network_wide;
        $plugin_installed_timestamp = get_option( self::PLUGIN_INSTALLED_TIMESTAMP );

        // If the plugin is being activated for the first time, set the installed timestamp.
        if ( empty( $plugin_installed_timestamp ) ) {
            update_option( self::PLUGIN_INSTALLED_TIMESTAMP, time() );
        }
    }

    /**
     * Run plugin activation actions.
     */
    public function run() {
        // Setup.
        Product_Question_Post_Type::instance()->register_post_type();
        $this->create_database_tables();
        $this->schedule_initial_tasks();

        // Upgrade scripts.
        ( new Version_1_0_6() )->run();
        ( new Skip_Onboarding_For_Updates() )->run();
        ( new Version_1_1_2() )->run(); // @since 1.1.2
    }

    /**
     * Schedule initial recurring tasks for the plugin.
     *
     * @return void
     */
    public function schedule_initial_tasks() {
        // Clean up old weekly update schedules (migration from weekly to daily).
        $this->cleanup_old_weekly_schedules();
        // Schedule subscription plan fetching.
        $plan_manager = \SAAI\Classes\Plan_Manager::instance();
        if ( $plan_manager ) {
            $plan_manager->schedule_daily_fetch();
        }

        // Schedule the short description check.
        $product_description_automations = \SAAI\Automations\Product_Description_Automations::instance();
        $product_description_ai          = \SAAI\AI_Agents\Product_Description_AI::instance();
        if ( $product_description_automations && $product_description_ai ) {
            $product_description_automations->schedule_main_description_length_check( $product_description_ai->get_settings() );
        }

        // Schedule the missing short description check if the feature is enabled.
        $product_summaries_automations = \SAAI\Automations\Product_Summaries_Automations::instance();
        $product_summaries_ai          = \SAAI\AI_Agents\Product_Summaries_AI::instance();

        if ( $product_summaries_automations && $product_summaries_ai && $product_summaries_ai->is_enabled() ) {
            // Use the automations class to schedule the check.
            $product_summaries_automations->schedule_missing_short_description_check( $product_summaries_ai->get_settings() );
        }

        // Schedule the review request notification.
        $review_request = \SAAI\Classes\Review_Request::instance();
        if ( $review_request ) {
            $review_request->schedule_review_request();
        }
    }

    /**
     * Create database tables for the plugin.
     *
     * @return void
     */
    public function create_database_tables() {
        global $wpdb;

        // Include WordPress database upgrade functionality.
        require_once ABSPATH . 'wp-admin/includes/upgrade.php';

        $charset_collate = $wpdb->get_charset_collate();
        $table_name      = $wpdb->prefix . 'storeagent_notifications';

        // SQL statement to create the notifications table if it doesn't exist.
        // Note: dbDelta() requires a semicolon at the end of each SQL statement.
        $sql = "CREATE TABLE IF NOT EXISTS $table_name (
            id BIGINT(20) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
            type VARCHAR(50) NOT NULL,
            title TEXT NOT NULL,
            message LONGTEXT NOT NULL,
            agent VARCHAR(255) NOT NULL,
            product_id BIGINT(20) NULL,
            extra LONGTEXT NULL,
            actions LONGTEXT NOT NULL,
            archived TINYINT(1) DEFAULT 0,
            hide_archive TINYINT(1) DEFAULT 0,
            status VARCHAR(50) DEFAULT 'pending',
            is_read TINYINT(1) DEFAULT 0,
            created_at DATETIME NOT NULL,
            updated_at DATETIME NOT NULL,
            KEY agent_idx (agent),
            KEY product_id_idx (product_id),
            KEY archived_idx (archived, created_at),
            KEY status_idx (status)
        ) $charset_collate;";

        // Create or update the table.
        // dbDelta() is preferred for WordPress plugins as it handles upgrades gracefully.
        dbDelta( $sql );
    }

    /**
     * Clean up old scheduled update actions (migration from weekly/daily to unified).
     * This ensures old scheduled actions are removed when the plugin is updated.
     *
     * @return void
     */
    protected function cleanup_old_weekly_schedules() {
        // Only proceed if Action Scheduler functions are available.
        if ( ! function_exists( 'as_unschedule_all_actions' ) ) {
            return;
        }

        // Unschedule all old weekly update actions.
        as_unschedule_all_actions( 'saai_weekly_product_update' );

        // Remove old schedule time options.
        delete_option( 'saai_weekly_update_schedule_time' );
    }
}
