<?php
/**
 * ارتقای v4 — تست مزاج · هزینه‌های ERP · معرفی دوستان · اشتراک
 * php run-arag-upgrade-v4.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    = [];

$wpdb->query( "CREATE TABLE IF NOT EXISTS {$pre}arag_mizaj_sessions (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    session_key VARCHAR(64) NOT NULL,
    phone VARCHAR(20) NOT NULL DEFAULT '',
    answers_json LONGTEXT NOT NULL,
    scores_json LONGTEXT NOT NULL,
    result_type VARCHAR(32) NOT NULL DEFAULT '',
    result_label VARCHAR(80) NOT NULL DEFAULT '',
    coupon_code VARCHAR(40) NOT NULL DEFAULT '',
    shared TINYINT(1) NOT NULL DEFAULT 0,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    UNIQUE KEY session_key (session_key),
    KEY result_type (result_type),
    KEY created_at (created_at)
) {$charset}" );
$done[] = 'arag_mizaj_sessions';

$wpdb->query( "CREATE TABLE IF NOT EXISTS {$pre}arag_erp_expenses (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    category VARCHAR(40) NOT NULL DEFAULT 'other',
    title VARCHAR(200) NOT NULL,
    amount DECIMAL(15,0) NOT NULL DEFAULT 0,
    expense_date DATE NOT NULL,
    notes TEXT NULL,
    created_by BIGINT UNSIGNED NOT NULL DEFAULT 0,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    KEY category (category),
    KEY expense_date (expense_date)
) {$charset}" );
$done[] = 'arag_erp_expenses';

$wpdb->query( "CREATE TABLE IF NOT EXISTS {$pre}arag_referrals (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    user_id BIGINT UNSIGNED NOT NULL DEFAULT 0,
    phone VARCHAR(20) NOT NULL DEFAULT '',
    code VARCHAR(20) NOT NULL,
    uses_count INT UNSIGNED NOT NULL DEFAULT 0,
    reward_total DECIMAL(14,0) NOT NULL DEFAULT 0,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    UNIQUE KEY code (code),
    KEY user_id (user_id),
    KEY phone (phone)
) {$charset}" );
$done[] = 'arag_referrals';

$wpdb->query( "CREATE TABLE IF NOT EXISTS {$pre}arag_referral_uses (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    referral_id BIGINT UNSIGNED NOT NULL,
    order_id BIGINT UNSIGNED NOT NULL DEFAULT 0,
    buyer_phone VARCHAR(20) NOT NULL DEFAULT '',
    discount_amount DECIMAL(14,0) NOT NULL DEFAULT 0,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    KEY referral_id (referral_id),
    KEY order_id (order_id)
) {$charset}" );
$done[] = 'arag_referral_uses';

$wpdb->query( "CREATE TABLE IF NOT EXISTS {$pre}arag_subscriptions (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    phone VARCHAR(20) NOT NULL,
    name VARCHAR(120) NOT NULL DEFAULT '',
    plan_key VARCHAR(40) NOT NULL DEFAULT 'monthly_classic',
    status VARCHAR(20) NOT NULL DEFAULT 'pending',
    mizaj_type VARCHAR(32) NOT NULL DEFAULT '',
    notes TEXT NULL,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    KEY phone (phone),
    KEY status (status)
) {$charset}" );
$done[] = 'arag_subscriptions';

$coupons = [
    [ 'code' => 'MAZAJ15', 'discount_pct' => 15, 'min_order' => 300000 ],
    [ 'code' => 'REF10',   'discount_pct' => 10, 'min_order' => 0 ],
];
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'];
    }
}

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