<?php


class AIPostActivator {


    public static function activate() {


        global $wpdb;


        $table_name = $wpdb->prefix . 'ai_post_rewrite_logs';


        $charset_collate = $wpdb->get_charset_collate();




        $sql = "CREATE TABLE $table_name (


            id mediumint(9) NOT NULL AUTO_INCREMENT,


            post_id bigint(20) NOT NULL,


            original_title text NOT NULL,


            new_title text NOT NULL,


            created_at datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,


            rewrite_time datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,


            PRIMARY KEY  (id)


        ) $charset_collate;";




        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');


        dbDelta($sql);

        // Create uploads/aipost-fonts directory for Title Image (Method-2) font mounting
        try {
            if (!function_exists('wp_upload_dir')) {
                require_once ABSPATH . 'wp-includes/functions.php';
            }
            if (!function_exists('wp_mkdir_p')) {
                require_once ABSPATH . 'wp-admin/includes/file.php';
            }
            $uploads = wp_upload_dir();
            if (isset($uploads['basedir']) && $uploads['basedir']) {
                $fontBase = rtrim($uploads['basedir'], '/\\') . DIRECTORY_SEPARATOR . 'aipost-fonts';
                if (!is_dir($fontBase)) {
                    @wp_mkdir_p($fontBase);
                }
                // Write a README to guide users
                $readme = $fontBase . DIRECTORY_SEPARATOR . 'README.txt';
                if (!file_exists($readme)) {
                    @file_put_contents($readme, "This directory is used by ai-post (Title Image - Method 2) to load font files.\r\n"
                        . "Place your preferred fonts here, e.g. NotoSansSC-Regular.ttf or WeiRuanYaHei.ttf.\r\n"
                        . "If a default font URL is configured, the plugin will try to download it on activation.\r\n");
                }
                // Try to download default font WeiRuanYaHei.ttf using fastest URL among candidates
                $target = $fontBase . DIRECTORY_SEPARATOR . 'WeiRuanYaHei.ttf';
                if (!file_exists($target)) {
                    // Gather candidates: filter list + single option/filter fallback
                    $candidates = apply_filters('aipost_font_candidates_wei_ruan_ya_hei', []);
                    $single = apply_filters('aipost_default_font_url', get_option('aipost_default_font_url'));
                    if (is_string($single) && !empty($single)) { $candidates[] = $single; }
                    $candidates = array_values(array_unique(array_filter(array_map('trim', $candidates))));

                    if (!empty($candidates)) {
                        // choose fastest by HEAD
                        $fastest = '';
                        $best = PHP_INT_MAX;
                        foreach ($candidates as $u) {
                            $t0 = microtime(true);
                            $resp = wp_remote_head($u, ['timeout' => 5]);
                            if (is_wp_error($resp)) { continue; }
                            $code = wp_remote_retrieve_response_code($resp);
                            if ($code >= 200 && $code < 400) {
                                $dt = (int) round((microtime(true) - $t0) * 1000);
                                if ($dt < $best) { $best = $dt; $fastest = $u; }
                            }
                        }

                        if (!empty($fastest)) {
                            if (!function_exists('download_url')) {
                                require_once ABSPATH . 'wp-admin/includes/file.php';
                            }
                            $tmp = download_url($fastest, 30);
                            if (!is_wp_error($tmp) && file_exists($tmp)) {
                                @rename($tmp, $target);
                                @chmod($target, 0644);
                                error_log('[AI-Post][Activator] Default font downloaded (fastest) to: ' . $target);
                            } else {
                                error_log('[AI-Post][Activator] Default font download failed (fastest): ' . (is_wp_error($tmp) ? $tmp->get_error_message() : 'unknown'));
                                if (is_string($tmp) && file_exists($tmp)) { @unlink($tmp); }
                            }
                        } else {
                            error_log('[AI-Post][Activator] No reachable font candidates (HEAD).');
                        }
                    } else {
                        error_log('[AI-Post][Activator] No default font candidates configured.');
                    }
                }
            }
        } catch (\Throwable $e) {
            error_log('[AI-Post][Activator] Font directory prepare error: ' . $e->getMessage());
        }

    }


} 