<?php
/**
 * ارتقای هسته حسابداری v19 — snapshot, reversal, schema
 * php run-accounting-core-upgrade.php
 */
declare(strict_types=1);

if ( ! defined( 'ACC_BASE_PATH' ) ) {
    define( 'ACC_BASE_PATH', __DIR__ );
    require __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';

require_once ACC_PATH . 'includes/helpers/acc-schema.php';
Acc_Schema::ensure_core_tables();

$alters = [
    "ALTER TABLE {$pre}ai_acc_events ADD COLUMN posted_mapping_json JSON NULL COMMENT 'snapshot mapping at post time'",
    "ALTER TABLE {$pre}ai_acc_events ADD COLUMN reverses_event_id BIGINT UNSIGNED NULL",
    "ALTER TABLE {$pre}ai_acc_events ADD COLUMN reversed_by_event_id BIGINT UNSIGNED NULL",
    "ALTER TABLE {$pre}ai_acc_events ADD COLUMN source_module VARCHAR(40) NULL",
];

foreach ( $alters as $sql ) {
    preg_match( '/ADD COLUMN (\w+)/', $sql, $m );
    $col = $m[1] ?? '';
    if ( ! $col ) continue;
    $exists = $wpdb->get_var( $wpdb->prepare(
        'SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = %s AND COLUMN_NAME = %s',
        $pre . 'ai_acc_events', $col
    ) );
    if ( $exists ) continue;
    $wpdb->query( $sql );
}

// Template برگشت
if ( ! $wpdb->get_var( $wpdb->prepare(
    "SELECT id FROM {$pre}ai_acc_event_templates WHERE event_type=%s AND version=1", 'REVERSAL'
) ) ) {
    $wpdb->insert( "{$pre}ai_acc_event_templates", [
        'event_type'    => 'REVERSAL',
        'version'       => 1,
        'template_name' => 'سند برگشتی',
        'mapping_logic' => wp_json_encode( [ 'pairs' => [] ] ),
        'description'   => 'از manual_entries در payload استفاده می‌شود',
        'is_active'     => 1,
    ] );
}

update_option( 'acc_engine_db_version', '19.0' );

echo wp_json_encode( [
    'success'    => true,
    'db_version' => '19.0',
    'features'   => [
        'unified_post_engine' => 'Acc_Event_Engine::post_event',
        'idempotency'         => true,
        'template_snapshot'   => 'posted_mapping_json',
        'multi_dimensions'    => 'tag_json.dimension_values',
        'balance_validation'  => true,
        'reversal'            => 'REVERSAL event type',
        'rules_fallback'      => 'ai_acc_rules → pairs',
        'smartflow_wired'     => true,
    ],
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT );
