<?php

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

function aieo_dmm_shipping_rates_install_schema() {
    aieo_dmm_create_shipping_rates_table();
}

function aieo_dmm_create_shipping_rates_table() {
    global $wpdb;

    $table = $wpdb->prefix . 'aieo_dmm_shipping_rates';
    $charset_collate = aieo_get_charset_collate();

    $sql = "CREATE TABLE IF NOT EXISTS {$table} (
        `id`                          bigint unsigned NOT NULL AUTO_INCREMENT,
        `shipping_method_id`          bigint unsigned NOT NULL,
        `legacy_rate_id`              bigint unsigned DEFAULT NULL,
        `rate_class`                  varchar(40)     NOT NULL DEFAULT '',
        `rate_condition`              varchar(40)     NOT NULL DEFAULT '',
        `rate_min`                    decimal(14,4)   DEFAULT NULL,
        `rate_max`                    decimal(14,4)   DEFAULT NULL,
        `rate_cost`                   decimal(14,4)   NOT NULL DEFAULT 0,
        `rate_cost_per_item`          decimal(14,4)   NOT NULL DEFAULT 0,
        `rate_cost_per_weight_unit`   decimal(14,4)   NOT NULL DEFAULT 0,
        `rate_cost_percent`           decimal(8,4)    NOT NULL DEFAULT 0,
        `rate_label`                  varchar(255)    NOT NULL DEFAULT '',
        `rate_priority`               tinyint         NOT NULL DEFAULT 0,
        `rate_order`                  int             NOT NULL DEFAULT 0,
        `rate_abort`                  tinyint         NOT NULL DEFAULT 0,
        `rate_abort_reason`           varchar(255)    NOT NULL DEFAULT '',
        `enabled`                     tinyint         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`),
        KEY `method`                  (`shipping_method_id`),
        KEY `method_class`            (`shipping_method_id`, `rate_class`),
        KEY `method_class_condition`  (`shipping_method_id`, `rate_class`, `rate_condition`),
        KEY `enabled_order`           (`shipping_method_id`, `enabled`, `rate_order`),
        KEY `legacy_rate_id`          (`legacy_rate_id`)
    ) {$charset_collate};";

    $wpdb->query($sql);
}
