<?php

if (!defined('ABSPATH')) {
    exit;
}

if (!function_exists('aieo_create_core_brand_vitals_table')) {
    function aieo_create_core_brand_vitals_table() {
        global $wpdb;

        $table           = $wpdb->prefix . 'aieo_core_brand_vitals';
        $charset_collate = function_exists('aieo_get_charset_collate')
            ? aieo_get_charset_collate()
            : $wpdb->get_charset_collate();

        $sql = "CREATE TABLE IF NOT EXISTS {$table} (
            `brand_id` bigint unsigned NOT NULL,
            `brand_name` varchar(255) NOT NULL DEFAULT '',
            `brand_slug` varchar(255) NOT NULL DEFAULT '',
            `taxonomy` varchar(64) NOT NULL DEFAULT 'product_brand',
            `letter` char(1) NOT NULL DEFAULT '#',
            `product_count` int unsigned NOT NULL DEFAULT 0,
            `in_stock_count` int unsigned NOT NULL DEFAULT 0,
            `total_sales` int unsigned NOT NULL DEFAULT 0,
            `total_turnover` decimal(12,2) NOT NULL DEFAULT 0.00,
            `brand_created_at` datetime NULL,
            `newest_product_at` datetime NULL,
            `hero_image_id` bigint unsigned NOT NULL DEFAULT 0,
            `logo_image_id` bigint unsigned NOT NULL DEFAULT 0,
            `rating_avg` decimal(3,2) NULL,
            `rating_count` int unsigned NOT NULL DEFAULT 0,
            `promo` tinyint NOT NULL DEFAULT 0,
            `priority` int NOT NULL DEFAULT 0,
            `last_computed` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (`brand_id`),
            KEY `aieo_cbv_idx_letter` (`letter`, `product_count`),
            KEY `aieo_cbv_idx_top_sales` (`total_sales`),
            KEY `aieo_cbv_idx_brand_new` (`brand_created_at`),
            KEY `aieo_cbv_idx_product_new` (`newest_product_at`),
            KEY `aieo_cbv_idx_recompute` (`last_computed`),
            KEY `aieo_cbv_idx_promo` (`promo`, `priority`)
        ) {$charset_collate};";

        $wpdb->query($sql);

        if (!empty($wpdb->last_error)) {
            if (function_exists('aieo_debug_log')) {
                aieo_debug_log('AIEO: Error creating core_brand_vitals table: ' . $wpdb->last_error);
            }
            return;
        }
        if (function_exists('aieo_debug_log')) {
            aieo_debug_log('AIEO: Successfully created/verified core_brand_vitals table');
        }
    }
}
