<?php
namespace ZS_SEO\AuditOptimization\Core;

defined( 'ABSPATH' ) || exit;

class Installer {

    public static function activate(): void {
        // Create default options
        $defaults = [
            'zs_seo_auto_meta'        => true,
            'zs_seo_schema_enabled'   => true,
            'zs_seo_geo_enabled'      => true,
            'zs_seo_sitemap_enabled'  => true,
            'zs_seo_version'          => ZS_SEO_VERSION,
        ];
        foreach ( $defaults as $key => $value ) {
            if ( false === get_option( $key ) ) {
                add_option( $key, $value );
            }
        }

        // Create DB table for redirects
        self::create_redirects_table();

        flush_rewrite_rules();
    }

    public static function deactivate(): void {
        flush_rewrite_rules();
    }

    private static function create_redirects_table(): void {
        global $wpdb;
        $table   = $wpdb->prefix . 'zs_seo_redirects';
        $charset = $wpdb->get_charset_collate();

        $sql = "CREATE TABLE IF NOT EXISTS {$table} (
            id          BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
            source_url  VARCHAR(500)    NOT NULL,
            target_url  VARCHAR(500)    NOT NULL,
            type        SMALLINT        NOT NULL DEFAULT 301,
            hits        BIGINT UNSIGNED NOT NULL DEFAULT 0,
            created_at  DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            UNIQUE KEY source_url (source_url(255))
        ) {$charset};";

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