<?php

namespace WPJoli\SAFI;

use WPJoli\SAFI\JoliApplication;
use WPJoli\SAFI\Activator;
use WPJoli\SAFI\Hooks;

class Application extends JoliApplication
{
    const VERSION = '1.5.1';
    const VERSION_OPTION  = 'smart-auto-featured-image_version';
    const NAME = 'Smart Auto Featured Image';
    const SLUG = 'smart-auto-featured-image';
    const WP_ORG_SLUG = 'smart-auto-featured-image';
    const SETTINGS_SLUG = 'smart-auto-featured-image_settings';
    const TEMPLATES_OPT = 'smart-auto-featured-image_templates';
    const SCREENSHOT_TEMPLATES_OPT = 'smart-auto-featured-image_templates_screenshots';
    const DOMAIN = 'smart-auto-featured-image';
    const ID = 'safi';
    const PREFIX = "safi_"; //db prefix
    const POST_TYPE_TEMPLATE = 'safi_template';
    const TAXONOMY_TEMPLATE = 'safi_template_category';
    const TAXONOMY_TEMPLATE_TAG = 'safi_template_tag';
    const USE_MINIFIED_ASSETS = true;

    protected $log;
    protected $hooks;

    public $options;

    public function __construct()
    {
        // static::$instance = $this;
        parent::__construct();

        //get the wp upload dir
        $upload_dir = wp_upload_dir();

        $dir = $upload_dir['basedir'] . "/safi-thumbnails/";
        $url = $upload_dir['baseurl'] . "/safi-thumbnails/";

        //Templaate thumbnail directory
        define('SAFI_TEMPLATE_THUMB_DIR', $dir);
        define('SAFI_TEMPLATE_THUMB_URL', $url);

        add_action(
            'init',
            function () {
                load_plugin_textdomain(
                    'wpjoli-safi',
                    false,
                    trailingslashit(plugin_basename($this->path()) . '/languages')
                );
            }
        );
        $this->log = new Log($this);
    }

    public function run()
    {
        add_action('init', [$this, 'maybeRunMigrations']);
        $this->hooks = new Hooks($this);
        $this->hooks->run();
    }


    public function activate()
    {
        $activator = new Activator();
        $activator->activate();
    }

    public function deactivate() {}
    protected function detectOldData()
    {
        global $wpdb;

        // Example: check if any legacy template options exist
        $option_exists = get_option(Application::TEMPLATES_OPT);
        if (!empty($option_exists)) {
            return true;
        }
        
        return false;
    }

    public function detectPostTypeTemplates()
    {
        global $wpdb;
        
        // Or check if old custom post type data exists
        $count = $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_type = 'safi_template'");
        return $count > 0;
    }

    public function maybeRunMigrations()
    {
        $has_pt_templates = $this->detectPostTypeTemplates();

        if ($has_pt_templates) {
            update_option(self::VERSION_OPTION, self::VERSION);
            return;
        }

        $stored_version = get_option(self::VERSION_OPTION);

        // Detect if plugin was already used (e.g. data from <1.5.0 exists)
        $has_old_data = $this->detectOldData();

        // First install (no old data at all)
        if (!$stored_version && !$has_old_data) {
            update_option(self::VERSION_OPTION, self::VERSION);
            return;
        }

        // First upgrade from a pre-version-tracking release
        if (!$stored_version && $has_old_data) {
            $from_version = '1.1.0'; // or whatever the last version before migrations
            $this->runMigrations($from_version);
            update_option(self::VERSION_OPTION, self::VERSION);
            return;
        }

        // Normal upgrade (option already exists)
        if (version_compare($stored_version, self::VERSION, '<')) {
            $this->runMigrations($stored_version);
            update_option(self::VERSION_OPTION, self::VERSION);
        }
    }


    protected function runMigrations($from_version)
    {
        // Example: only run this migration for upgrades from <1.5.0
        if (version_compare($from_version, '1.5.0', '<')) {
            $controller = $this::instance()->requestService(\WPJoli\SAFI\Controllers\TemplatesControllerV2::class);
            $result = $controller->migrateTemplates();

            if (!empty($result['migrated'])) {
                error_log('[SAFI Migration] Migrated templates: ' . implode(', ', $result['migrated']));
            }

            if (!empty($result['errors'])) {
                error_log('[SAFI Migration] Migration errors: ' . implode(', ', $result['errors']));
            }
        }
    }


    public function getPlans()
    {
        return [
            '16821' => [
                'plan' => 'Pro',

                'segments' => [
                    // pricing_id
                    '0' => [
                        'name' => 'Trial',
                        'credits' => 10,
                    ],
                    '18866' => [
                        'name' => '1 site',
                        'credits' => 20,
                    ],
                    // '26206' => [
                    //     'name' => '2 sites',
                    //     'credits' => 65,
                    // ],
                    // '26207' => [
                    //     'name' => '3 sites',
                    //     'credits' => 100,
                    // ],
                    '26208' => [
                        'name' => '5 sites',
                        'credits' => 100,
                    ],
                    '26209' => [
                        'name' => '10 sites',
                        'credits' => 300,
                    ],
                    '26211' => [
                        'name' => '25 sites',
                        'credits' => 1000,
                    ],
                ],
            ],
        ];
    }
}
