<?php
defined( 'ABSPATH' ) || exit;

class Jalpi_Activator {

    public static function activate() {
        global $wpdb;
        $charset = $wpdb->get_charset_collate();

        $sql = "CREATE TABLE IF NOT EXISTS {$wpdb->prefix}jalpi_pages (
            id          BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
            post_id     BIGINT UNSIGNED NOT NULL,
            page_data   LONGTEXT        NOT NULL,
            version     INT UNSIGNED    NOT NULL DEFAULT 1,
            created_at  DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP,
            updated_at  DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            UNIQUE KEY post_id (post_id),
            KEY updated_at (updated_at)
        ) $charset;";

        $classes_sql = "CREATE TABLE IF NOT EXISTS {$wpdb->prefix}jalpi_classes (
            id          BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
            class_key   VARCHAR(64)     NOT NULL,
            name        VARCHAR(191)    NOT NULL,
            styles      LONGTEXT        NOT NULL,
            favorite    TINYINT(1)      NOT NULL DEFAULT 0,
            sort_order  INT UNSIGNED    NOT NULL DEFAULT 0,
            created_by  BIGINT UNSIGNED NOT NULL DEFAULT 0,
            created_at  DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP,
            updated_at  DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            UNIQUE KEY class_key (class_key),
            KEY sort_order (sort_order)
        ) $charset;";

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

        add_option( 'jalpi_version', JALPI_VERSION );
        add_option( 'jalpi_classes_version', 1 );
        add_option( 'jalpi_classes_table_ready', '1' );
        add_option( 'jalpi_enabled_post_types', [ 'page', 'post' ] );

        // Settings page defaults — add_option() is a no-op when the key already exists,
        // so this is safe to call on both fresh installs and plugin updates.
        $defaults = Jalpi_Settings::defaults();
        add_option( Jalpi_Settings::OPT_GENERAL,     $defaults['general']     );
        add_option( Jalpi_Settings::OPT_LAYOUT,      $defaults['layout']      );
        add_option( Jalpi_Settings::OPT_DESIGN,      $defaults['design']      );
        add_option( Jalpi_Settings::OPT_PERFORMANCE, $defaults['performance'] );
        add_option( Jalpi_Settings::OPT_BREAKPOINTS,  $defaults['breakpoints'] );

        self::seed_design_system();

        Jalpi_Revisions::create_table();
    }

    public static function deactivate() {
        // Intentionally keep data on deactivation.
    }

    /**
     * Version-guarded upgrade entry point. activate() only fires on fresh
     * plugin activation (register_activation_hook) — a plugin file update via
     * wp-admin does NOT re-trigger it — so this is the mechanism for one-time
     * upgrade steps that must also run against already-installed sites.
     * Called from jalpi_init() on every request; the get_option() check below
     * makes every call after the first a cheap no-op.
     */
    public static function maybe_upgrade(): void {
        // Runs on every load, but self-gates on its own flag: menus imported
        // before kit tagging existed carry no _jalpi_kit, so the Menu widget's
        // strict filter would hide every one of them.
        self::backfill_menu_kits();

        if ( get_option( 'jalpi_version', '' ) === JALPI_VERSION ) {
            return;
        }
        self::seed_design_system();
        update_option( 'jalpi_version', JALPI_VERSION );
    }

    /**
     * One-time: tag pre-existing kit menus with the kit that created them.
     *
     * Kit importers name their menu "<Kit Name> Menu", which WordPress slugs as
     * "<kit-id>-menu". That prefix is the only evidence available after the
     * fact, so it is used to recover ownership — but only for menus that match
     * a website kit actually shipped with the plugin. Anything else (a menu the
     * user made by hand) is deliberately left untagged and stays hidden.
     */
    private static function backfill_menu_kits(): void {
        if ( get_option( 'jalpi_menu_kits_backfilled', false ) ) {
            return;
        }

        $menus = wp_get_nav_menus();
        if ( ! is_array( $menus ) ) {
            return;
        }

        // Kit ids are the filenames in websites/, e.g. hoops.json → "hoops".
        $kit_ids = [];
        foreach ( (array) glob( JALPI_DIR . 'websites/*.json' ) as $file ) {
            $kit_ids[] = sanitize_key( basename( $file, '.json' ) );
        }

        foreach ( $menus as $menu ) {
            if ( '' !== (string) get_term_meta( $menu->term_id, '_jalpi_kit', true ) ) {
                continue; // Already tagged.
            }

            foreach ( $kit_ids as $kit_id ) {
                if ( $menu->slug === $kit_id . '-menu' || 0 === strpos( $menu->slug, $kit_id . '-' ) ) {
                    update_term_meta( $menu->term_id, '_jalpi_kit', $kit_id );
                    break;
                }
            }
        }

        update_option( 'jalpi_menu_kits_backfilled', 1 );
    }

    /**
     * One-time seed of the site-wide Design System option. Never overwrites an
     * existing OPT_DESIGN_SYSTEM value. Pulls forward any values already
     * configured on the (previously orphaned) Settings → Global Design tab so
     * sites that already set a primary/secondary color or body/heading font
     * don't lose that configuration when the Design System takes over as the
     * source of truth for those same concepts.
     */
    private static function seed_design_system(): void {
        if ( false !== get_option( Jalpi_Settings::OPT_DESIGN_SYSTEM, false ) ) {
            return; // Already seeded (or user has already configured it) — never clobber.
        }

        $legacy = get_option( Jalpi_Settings::OPT_DESIGN, [] );
        $seed   = Jalpi_Settings::defaults()['design_system'];

        if ( ! empty( $legacy['primary_color'] ) ) {
            $seed['colors'][0]['value'] = $legacy['primary_color'];
        }
        if ( ! empty( $legacy['secondary_color'] ) ) {
            $seed['colors'][1]['value'] = $legacy['secondary_color'];
        }
        if ( ! empty( $legacy['body_font'] ) ) {
            $seed['fontFamilies'][] = [ 'id' => 'body', 'name' => 'Body', 'value' => $legacy['body_font'] ];
        }
        if ( ! empty( $legacy['heading_font'] ) ) {
            $seed['fontFamilies'][] = [ 'id' => 'heading', 'name' => 'Heading', 'value' => $legacy['heading_font'] ];
        }
        if ( ! empty( $legacy['base_font_size'] ) ) {
            $seed['fontSizes'][] = [ 'id' => 'base-legacy', 'name' => 'Base (legacy)', 'value' => $legacy['base_font_size'] . 'px' ];
        }

        add_option( Jalpi_Settings::OPT_DESIGN_SYSTEM, Jalpi_Sanitizer::sanitize_design_system( $seed ), '', true );
    }
}
