<?php

namespace AIProductContentImageGenerator;

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

use AIProductContentImageGenerator\Core\Container;
use AIProductContentImageGenerator\Core\Router;
use AIProductContentImageGenerator\Admin\AdminManager;
use AIProductContentImageGenerator\Services\AIProviderManager;
use AIProductContentImageGenerator\Services\ContentGenerator;
use AIProductContentImageGenerator\Services\ImageGenerator;

class Plugin {
    private static $instance = null;
    private $container;
    private $router;
    private $version;

    private function __construct() {
        $this->version = APCIG_VERSION;
        $this->container = new Container();
        $this->router = new Router();
    }

    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new self();
            self::$instance->init();
        }
        return self::$instance;
    }

    public function init() {
        $this->registerServices();
        $this->initHooks();
        $this->initRouter();
    }

    private function registerServices() {
        $this->container->register('database', function() {
            $database = new \AIProductContentImageGenerator\Core\Database();
            $database->init();
            return $database;
        });

        $this->container->register('background_processor', function() {
            $processor = new \AIProductContentImageGenerator\Core\BackgroundProcessor($this->container);
            $processor->init();
            return $processor;
        });

        $this->container->register('ai_provider_manager', function() {
            return new AIProviderManager();
        });

        $this->container->register('content_generator', function() {
            return new ContentGenerator($this->container->get('ai_provider_manager'));
        });

        $this->container->register('image_generator', function() {
            return new ImageGenerator($this->container->get('ai_provider_manager'));
        });

        $this->container->register('admin_manager', function() {
            return new AdminManager($this->container, $this->router);
        });

        $this->container->register('ajax_handler', function() {
            $handler = new \AIProductContentImageGenerator\Admin\AjaxHandler($this->container);
            $handler->init();
            return $handler;
        });
        
        $this->container->get('database');
        $this->container->get('background_processor');
        $this->container->get('ajax_handler');
    }

    private function initHooks() {
        if (is_admin()) {
            $this->container->get('admin_manager')->init();
        }

        add_action('wp_enqueue_scripts', [$this, 'enqueueFrontendAssets']);
        add_action('wp_footer', [$this, 'addFrontendScripts']);

        add_action('woocommerce_single_product_summary', [$this, 'addProductButtons'], 25);
        add_action('woocommerce_product_meta_end', [$this, 'addProductMetaButtons']);
        add_action('woocommerce_after_shop_loop_item', [$this, 'addShopButtons'], 15);
        add_action('woocommerce_after_single_product_summary', [$this, 'addProductTabs'], 25);

        add_action('apcig_process_bulk_queue', [$this, 'processBulkQueue']);
        add_action('apcig_cleanup_old_files', [$this, 'cleanupOldFiles']);
        add_action('apcig_reset_daily_stats', [$this, 'resetDailyStats']);

        if (!wp_next_scheduled('apcig_cleanup_old_files')) {
            wp_schedule_event(time(), 'daily', 'apcig_cleanup_old_files');
        }
    }

    private function initRouter() {
        $this->router->init();
    }

    public function enqueueFrontendAssets() {
        if (is_product() || 
            is_shop() || 
            is_product_category()) {
            
            wp_enqueue_style(
                'apcig-frontend',
                APCIG_PLUGIN_URL . 'assets/css/frontend.css',
                [],
                APCIG_VERSION
            );
        }
    }



    public function addProductButtons() {
        $button_html = '<button type="button" class="apcig-generate-btn" data-product-id="' . get_the_ID() . '">' . 
                      esc_html(__('🤖 Generate', 'contengen-ai-product-content-image-generator')) . '</button>';
        
        do_action('apcig_before_product_buttons', get_the_ID());
        echo wp_kses_post($button_html);
        do_action('apcig_after_product_buttons', get_the_ID());
    }

    public function addProductMetaButtons() {
        do_action('apcig_before_product_meta_buttons', get_the_ID());
        echo '<div class="apcig-meta-buttons"></div>';
        do_action('apcig_after_product_meta_buttons', get_the_ID());
    }

    public function addShopButtons() {
        do_action('apcig_before_shop_buttons');
        echo '<div class="apcig-shop-buttons"></div>';
    }

    public function addProductTabs() {
    }

    public function addFrontendScripts() {
    }

    public function processBulkQueue() {
        $this->container->get('background_processor')->process_queue();
    }

    public function cleanupOldFiles() {
        $upload_dir = wp_upload_dir();
        $plugin_dir = $upload_dir['basedir'] . '/apcig/';
        
        if (is_dir($plugin_dir)) {
            $files = glob($plugin_dir . '*');
            $cutoff_time = time() - (30 * DAY_IN_SECONDS);
            
            foreach ($files as $file) {
                if (is_file($file) && filemtime($file) < $cutoff_time) {
                    wp_delete_file($file);
                }
            }
        }
    }

    public function resetDailyStats() {
        // Reset daily counters at midnight
        update_option('apcig_content_generated_today', 0);
        update_option('apcig_images_generated_today', 0);
        update_option('apcig_last_daily_reset', current_time('Y-m-d'));
    }

    public function getContainer(): Container {
        return $this->container;
    }

    public function getRouter(): Router {
        return $this->router;
    }

    public function getVersion(): string {
        return $this->version;
    }
}