<?php

namespace MediaTrim\Activator;

use MediaTrim\Traits\Singleton;

defined('ABSPATH') || exit;

/**
 * Class Activator
 *
 * Handles plugin activation, deactivation, and version management.
 *
 * @package MediaTrim\Activator
 */
class Activator
{

    use Singleton;

    /**
     * Plugin version
     *
     * @var string
     */
    const VERSION = '1.0.0';

    /**
     * Plugin slug
     *
     * @var string
     */
    const SLUG = 'media-trim';

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->init_hooks();
    }

    /**
     * Initialize hooks
     */
    public function init_hooks()
    {
        add_action('plugins_loaded', [$this, 'mtrim_set_initial_version']);
        add_action('upgrader_process_complete', [$this, 'mtrim_on_update'], 10, 2);
    }

    /**
     * Handle plugin activation
     */
    public function on_activate()
    {
        // Update version
        update_option('mtrim_version', self::VERSION);

        // Create database tables
        $this->create_cleaner_table();
        $this->create_trash_table();
        $this->create_scan_history_table();
        $this->create_scan_state_table();
        $this->create_orphaned_files_table();
    }

    /**
     * Create cleaner database table
     * This will store scan results
     */
    public function create_cleaner_table()
    {
        global $wpdb;
        $table_name = $wpdb->prefix . 'mtrim_scan_results';
        $charset_collate = $wpdb->get_charset_collate();

        $sql = "CREATE TABLE IF NOT EXISTS $table_name (
            id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
            attachment_id BIGINT(20) UNSIGNED NOT NULL,
            file_hash VARCHAR(32) NOT NULL,
            status VARCHAR(20) DEFAULT 'unused',
            file_path TEXT NOT NULL,
            file_size BIGINT(20) UNSIGNED DEFAULT 0,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            UNIQUE KEY attachment_id (attachment_id),
            KEY status (status)
        ) $charset_collate;";

        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);
    }

    /**
     * Create trash items database table
     */
    public function create_trash_table()
    {
        global $wpdb;
        $table_name = $wpdb->prefix . 'mtrim_trash_items';
        $charset_collate = $wpdb->get_charset_collate();

        $sql = "CREATE TABLE IF NOT EXISTS $table_name (
            id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
            original_attachment_id BIGINT(20) UNSIGNED NOT NULL,
            original_path TEXT NOT NULL,
            trash_path TEXT NOT NULL,
            file_name VARCHAR(255) NOT NULL,
            file_size BIGINT(20) UNSIGNED DEFAULT 0,
            mime_type VARCHAR(100) DEFAULT '',
            trashed_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            KEY original_attachment_id (original_attachment_id)
        ) $charset_collate;";

        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);
    }

    /**
     * Create scan history database table
     */
    public function create_scan_history_table()
    {
        global $wpdb;
        $table_name = $wpdb->prefix . 'mtrim_scan_history';
        $charset_collate = $wpdb->get_charset_collate();

        $sql = "CREATE TABLE IF NOT EXISTS $table_name (
            id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
            scan_type VARCHAR(50) NOT NULL DEFAULT 'full',
            items_scanned INT(11) UNSIGNED DEFAULT 0,
            unused_found INT(11) UNSIGNED DEFAULT 0,
            duplicates_found INT(11) UNSIGNED DEFAULT 0,
            space_reclaimable BIGINT(20) UNSIGNED DEFAULT 0,
            duration INT(11) UNSIGNED DEFAULT 0,
            completed_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id)
        ) $charset_collate;";

        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);
    }

    /**
     * Create scan state database table for pause/resume
     */
    public function create_scan_state_table()
    {
        global $wpdb;
        $table_name = $wpdb->prefix . 'mtrim_scan_state';
        $charset_collate = $wpdb->get_charset_collate();

        $sql = "CREATE TABLE IF NOT EXISTS $table_name (
            id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
            scan_type VARCHAR(50) NOT NULL DEFAULT 'media',
            current_offset INT(11) UNSIGNED DEFAULT 0,
            total_items INT(11) UNSIGNED DEFAULT 0,
            status VARCHAR(20) DEFAULT 'idle',
            started_at DATETIME DEFAULT NULL,
            paused_at DATETIME DEFAULT NULL,
            PRIMARY KEY (id),
            KEY scan_type (scan_type)
        ) $charset_collate;";

        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);
    }

    /**
     * Create orphaned files database table
     */
    public function create_orphaned_files_table()
    {
        global $wpdb;
        $table_name = $wpdb->prefix . 'mtrim_orphaned_files';
        $charset_collate = $wpdb->get_charset_collate();

        $sql = "CREATE TABLE IF NOT EXISTS $table_name (
            id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
            file_path TEXT NOT NULL,
            file_name VARCHAR(255) NOT NULL,
            file_size BIGINT(20) UNSIGNED DEFAULT 0,
            mime_type VARCHAR(100) DEFAULT '',
            found_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id)
        ) $charset_collate;";

        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);
    }

    /**
     * Set the version if it was never saved before
     */
    public function mtrim_set_initial_version()
    {
        if (get_option('mtrim_version') === false) {
            update_option('mtrim_version', self::VERSION);
        }
    }

    /**
     * Handle plugin update via WordPress plugin updater
     *
     * @param object $upgrader_object The upgrader object.
     * @param array  $options         Options array.
     */
    public function mtrim_on_update($upgrader_object, $options)
    {
        if (
            isset($options['type']) && $options['type'] === 'plugin' &&
            in_array($options['action'], ['update', 'install'], true)
        ) {
            $plugin_slug = defined('MTRIM_PLUGIN_BASENAME') ? MTRIM_PLUGIN_BASENAME : 'media-trim/media-trim.php';

            $is_target_plugin = false;

            if (!empty($options['plugins']) && is_array($options['plugins'])) {
                $is_target_plugin = in_array($plugin_slug, $options['plugins'], true);
            }

            if (!$is_target_plugin && !empty($options['plugin'])) {
                $is_target_plugin = $options['plugin'] === $plugin_slug;
            }

            if ($is_target_plugin) {
                update_option('mtrim_version', self::VERSION);
                $this->create_cleaner_table();
                $this->create_trash_table();
                $this->create_scan_history_table();
                $this->create_scan_state_table();
            }
        }
    }
}
