<?php
/**
 * ارتقای فروشگاه عرقیات v2 — کوپن DB، سبد سروری، تخفیف سفارش، اعلان‌ها
 * php run-arag-upgrade-v2.php
 */
declare(strict_types=1);

define( 'ACC_BASE_PATH', __DIR__ );
require_once __DIR__ . '/standalone/bootstrap.php';

header( 'Content-Type: application/json; charset=utf-8' );
global $wpdb;
$pre     = $wpdb->prefix;
$charset = 'DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci';
$done    = [];

function arag2_col_exists( $wpdb, string $table, string $col ): bool {
    $row = $wpdb->get_row( "SHOW COLUMNS FROM `{$table}` LIKE '{$col}'" );
    return (bool) $row;
}

function arag2_add_col( $wpdb, string $table, string $col, string $ddl, array &$done ): void {
    if ( ! arag2_col_exists( $wpdb, $table, $col ) ) {
        $wpdb->query( "ALTER TABLE `{$table}` ADD COLUMN {$ddl}" );
        $done[] = "add {$table}.{$col}";
    }
}

// ── orders: coupon + total ──
$ot = $pre . 'arag_orders';
arag2_add_col( $wpdb, $ot, 'coupon_code', "coupon_code VARCHAR(40) NOT NULL DEFAULT '' AFTER subtotal", $done );
arag2_add_col( $wpdb, $ot, 'discount_amount', "discount_amount DECIMAL(14,0) NOT NULL DEFAULT 0 AFTER coupon_code", $done );
arag2_add_col( $wpdb, $ot, 'total', "total DECIMAL(14,0) NOT NULL DEFAULT 0 AFTER discount_amount", $done );

// backfill total from subtotal
$wpdb->query( "UPDATE {$ot} SET total = subtotal WHERE total = 0 AND subtotal > 0" );

// ── shop settings: announcements + review moderation ──
$st = $pre . 'arag_shop_settings';
arag2_add_col( $wpdb, $st, 'announcements_json', "announcements_json JSON NULL AFTER brand_story", $done );
arag2_add_col( $wpdb, $st, 'auto_approve_reviews', "auto_approve_reviews TINYINT(1) NOT NULL DEFAULT 1 AFTER announcements_json", $done );

// ── coupons ──
$wpdb->query( "CREATE TABLE IF NOT EXISTS {$pre}arag_coupons (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    code VARCHAR(40) NOT NULL,
    discount_pct TINYINT UNSIGNED NOT NULL DEFAULT 0,
    discount_fixed DECIMAL(14,0) NOT NULL DEFAULT 0,
    min_order DECIMAL(14,0) NOT NULL DEFAULT 0,
    max_uses INT UNSIGNED NOT NULL DEFAULT 0,
    used_count INT UNSIGNED NOT NULL DEFAULT 0,
    expires_at DATETIME NULL,
    is_active TINYINT(1) NOT NULL DEFAULT 1,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    UNIQUE KEY code (code)
) {$charset}" );
$done[] = 'arag_coupons';

// ── server cart ──
$wpdb->query( "CREATE TABLE IF NOT EXISTS {$pre}arag_cart (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    session_key VARCHAR(64) NOT NULL,
    user_id BIGINT UNSIGNED NOT NULL DEFAULT 0,
    items_json LONGTEXT NOT NULL,
    updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    UNIQUE KEY session_key (session_key),
    KEY user_id (user_id)
) {$charset}" );
$done[] = 'arag_cart';

// seed default coupons
$coupons = [
    [ 'code' => 'ARAG10',    'discount_pct' => 10, 'min_order' => 0 ],
    [ 'code' => 'ARAG15',    'discount_pct' => 15, 'min_order' => 500000 ],
    [ 'code' => 'WELCOME20', 'discount_pct' => 20, 'min_order' => 1000000 ],
];
foreach ( $coupons as $c ) {
    $exists = (int) $wpdb->get_var( $wpdb->prepare(
        "SELECT id FROM {$pre}arag_coupons WHERE code = %s", $c['code']
    ) );
    if ( ! $exists ) {
        $wpdb->insert( "{$pre}arag_coupons", [
            'code'         => $c['code'],
            'discount_pct' => $c['discount_pct'],
            'min_order'    => $c['min_order'],
            'is_active'    => 1,
        ] );
        $done[] = 'coupon ' . $c['code'];
    }
}

// default announcements
$ann = wp_json_encode( [
    '🚚 ارسال رایگان برای خرید بالای ۵۰۰ هزار تومان',
    '🌿 محصولات ۱۰۰٪ طبیعی · بدون افزودنی مصنوعی',
    '⭐ بیش از ۱۲۰۰ مشتری راضی در سراسر کشور',
], JSON_UNESCAPED_UNICODE );
$wpdb->query( $wpdb->prepare(
    "UPDATE {$st} SET announcements_json = %s WHERE id = 1 AND (announcements_json IS NULL OR announcements_json = 'null' OR announcements_json = '[]')",
    $ann
) );

echo json_encode( [
    'success' => true,
    'changes' => $done,
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT );
