<?php

namespace classes;

/**
 * Ensures additive V2 history tables exist.
 *
 * This project has no centralized migration runner, so we keep bootstrap
 * idempotent and safe to call from runtime flows.
 */
class economic_v2_schema_bootstrap
{
    private static bool $initialized = false;

    public static function ensureTables(): void
    {
        if (self::$initialized) {
            return;
        }

        global $db;

        $queries = [
            "CREATE TABLE IF NOT EXISTS customer_fixed_pricing_versions (
                id INT AUTO_INCREMENT PRIMARY KEY,
                customer_number INT NOT NULL,
                price INT NOT NULL,
                description VARCHAR(255) NULL,
                effective_from DATETIME NOT NULL,
                effective_to DATETIME NULL,
                source VARCHAR(64) NOT NULL DEFAULT 'live',
                confidence DECIMAL(6,5) NOT NULL DEFAULT 1.00000,
                inferred TINYINT(1) NOT NULL DEFAULT 0,
                metadata_json TEXT NULL,
                created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                INDEX idx_customer_fixed_versions_lookup (customer_number, effective_from, effective_to),
                INDEX idx_customer_fixed_versions_source (source)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci",

            "CREATE TABLE IF NOT EXISTS customer_vehicle_subscription_versions (
                id INT AUTO_INCREMENT PRIMARY KEY,
                vehicle_id INT NULL,
                customer_number INT NOT NULL,
                reg VARCHAR(64) NOT NULL,
                vehicle_type INT NOT NULL,
                wash_subscription TINYINT(1) NOT NULL,
                effective_from DATETIME NOT NULL,
                effective_to DATETIME NULL,
                source VARCHAR(64) NOT NULL DEFAULT 'live',
                confidence DECIMAL(6,5) NOT NULL DEFAULT 1.00000,
                inferred TINYINT(1) NOT NULL DEFAULT 0,
                metadata_json TEXT NULL,
                created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                INDEX idx_vehicle_subscription_versions_lookup (customer_number, reg, effective_from, effective_to),
                INDEX idx_vehicle_subscription_versions_vehicle (vehicle_id),
                INDEX idx_vehicle_subscription_versions_source (source)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci",

            "CREATE TABLE IF NOT EXISTS customer_discount_override_versions (
                id INT AUTO_INCREMENT PRIMARY KEY,
                department_id INT NULL DEFAULT NULL,
                user_id INT NOT NULL,
                customer_number INT NOT NULL,
                is_category TINYINT(1) NOT NULL,
                object_id VARCHAR(64) NOT NULL,
                discount INT NOT NULL,
                fixed_price INT NULL DEFAULT NULL,
                effective_from DATETIME NOT NULL,
                effective_to DATETIME NULL,
                source VARCHAR(64) NOT NULL DEFAULT 'live',
                confidence DECIMAL(6,5) NOT NULL DEFAULT 1.00000,
                inferred TINYINT(1) NOT NULL DEFAULT 0,
                metadata_json TEXT NULL,
                created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                INDEX idx_discount_override_versions_lookup (customer_number, is_category, object_id, effective_from, effective_to),
                INDEX idx_discount_override_versions_department_lookup (department_id, customer_number, is_category, object_id, effective_from, effective_to),
                INDEX idx_discount_override_versions_user (user_id),
                INDEX idx_discount_override_versions_source (source)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci",
        ];

        foreach ($queries as $sql) {
            $db->query($sql);
        }

        if (!self::tableHasColumn('customer_discount_override_versions', 'fixed_price')) {
            $db->query(
                "ALTER TABLE customer_discount_override_versions
                    ADD COLUMN fixed_price INT NULL DEFAULT NULL
                    AFTER discount"
            );
        }

        if (!self::tableHasColumn('customer_discount_override_versions', 'department_id')) {
            $db->query(
                "ALTER TABLE customer_discount_override_versions
                    ADD COLUMN department_id INT NULL DEFAULT NULL
                    AFTER id"
            );
        }

        self::$initialized = true;
    }

    public static function tableHasColumn(string $table, string $column): bool
    {
        global $db;
        $table = $db->escape_string($table);
        $column = $db->escape_string($column);
        $database = $db->escape_string($db->getDatabase());

        $sql = "SELECT COUNT(*) AS c
                FROM information_schema.COLUMNS
                WHERE TABLE_SCHEMA = '$database'
                  AND TABLE_NAME = '$table'
                  AND COLUMN_NAME = '$column'";
        $result = $db->query($sql);
        if (!$result) {
            return false;
        }
        $row = $result->fetch_assoc();
        return ((int)($row['c'] ?? 0)) > 0;
    }
}
