<?php
namespace ShopyPress;

if ( ! defined( 'ABSPATH' ) ) exit;

use ShopyPress\Hooks\HooksFactory;
use ShopyPress\Jobs\Cron;
use ShopyPress\Models\ShopyPressProduct;
use ShopyPress\Utils\OptionUtils;
use ShopyPress\Config\SyncConfig;
use ShopyPress\Helpers\ShopifyAuth;

class App {
    static function init(mixed $file): void {
        register_activation_hook(
            $file,
            [self::class, 'onActivate']
        );
        
        register_uninstall_hook(
            $file,
            [self::class, 'onUninstall']
        );
    }
    static function run(): void {
        HooksFactory::registerHooks();
    }

    static function onActivate() {
        Cron::addCronJobs();
    }

    static function onUninstall() {
        // Delete all plugin data (posts, terms, options, transients)
        self::deleteAllPluginData();

        // Remove cron jobs
        Cron::removeCronJobs();

        // Clean up lock file if exists
        $lockFile = get_temp_dir() . 'shopypress_sync_products.lock';
        if (file_exists($lockFile)) {
            wp_delete_file($lockFile);
        }
    }

    /**
     * Delete transient cached data
     *
     * @return void
     */
    private static function deleteTransients(): void {
        delete_transient(ShopifyAuth::ACCESS_TOKEN_OPTION_KEY);
    }

    /**
     * Delete all product posts and their associated metadata
     *
     * @return void
     */
    private static function deleteProducts(): void {
        $product_ids = get_posts([
            'post_type' => ShopyPressProduct::PRODUCT_SLUG,
            'posts_per_page' => -1,
            'fields' => 'ids',
            'post_status' => 'any' // Include all statuses: publish, draft, trash, etc.
        ]);

        foreach ($product_ids as $post_id) {
            wp_delete_post($post_id, true); // true = force delete, bypass trash
        }
    }

    /**
     * Delete all collection taxonomy terms and their associated metadata
     *
     * @return void
     */
    private static function deleteCollections(): void {
        $terms = get_terms([
            'taxonomy' => ShopyPressProduct::COLLECTION_TAXONOMY,
            'hide_empty' => false,
            'fields' => 'ids'
        ]);

        if (!is_wp_error($terms) && !empty($terms)) {
            foreach ($terms as $term_id) {
                wp_delete_term($term_id, ShopyPressProduct::COLLECTION_TAXONOMY);
            }
        }
    }

    /**
     * Delete all plugin options from wp_options table
     *
     * @return void
     */
    private static function deleteOptions(): void {
        delete_option(OptionUtils::OPTION_GROUP_SLUG);
        delete_option(SyncConfig::SYNC_STATE_OPTION_KEY);
        delete_option(SyncConfig::SYNC_LAST_STATE_OPTION_KEY);
    }

    /**
     * Delete ALL plugin data including posts, terms, options, and transients
     *
     * @return void
     */
    private static function deleteAllPluginData(): void {
        try {
            // 1. Delete transients
            self::deleteTransients();

            // 2. Delete custom post type posts (and their meta)
            self::deleteProducts();

            // 3. Delete taxonomy terms (and their meta)
            self::deleteCollections();

            // 4. Delete WordPress options
            self::deleteOptions();

            // 5. Clear object cache
            wp_cache_flush();

            // 6. Flush rewrite rules
            flush_rewrite_rules();

        } catch (\Throwable $e) {
            // Log error for debugging
            error_log('ShopyPress cleanup error: ' . $e->getMessage());
        }
    }
}