<?php
/**
 * v7 — import 1011 پهنه + مالی ستاد + SMS OTP production
 * C:\xampp\php\php.exe run-election-v7-install.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;

require_once ACC_PATH . 'includes/helpers/election-havadaran.php';

$pre = $wpdb->prefix;
$log = [];

$seg_t = Election_Havadaran::segments_table();
$cols = $wpdb->get_col( "SHOW COLUMNS FROM {$seg_t}", 0 );
$add_cols = [
    'gis_neighborhood_id'  => 'BIGINT UNSIGNED NULL',
    'gis_block_code'       => 'VARCHAR(40) NULL',
    'election_district_id' => 'BIGINT UNSIGNED NULL',
    'import_source'        => "VARCHAR(20) NULL DEFAULT 'seed'",
];
foreach ( $add_cols as $col => $def ) {
    if ( ! in_array( $col, $cols, true ) ) {
        $wpdb->query( "ALTER TABLE {$seg_t} ADD COLUMN {$col} {$def}" );
        $log[] = "segments_{$col}";
    }
}

$bt = Election_Havadaran::budget_table();
$wpdb->query( "CREATE TABLE IF NOT EXISTS {$bt} (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    category VARCHAR(40) NOT NULL DEFAULT 'other',
    label VARCHAR(200) NOT NULL,
    planned_amount DECIMAL(18,2) NOT NULL DEFAULT 0,
    phase VARCHAR(30) NOT NULL DEFAULT 'campaign',
    dept_slug VARCHAR(40) NOT NULL DEFAULT 'financial',
    notes TEXT NULL,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    KEY idx_cat (category),
    KEY idx_phase (phase)
) DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci" );
$log[] = 'budget_table';

$tt = Election_Havadaran::transactions_table();
$wpdb->query( "CREATE TABLE IF NOT EXISTS {$tt} (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    direction ENUM('in','out') NOT NULL DEFAULT 'out',
    category VARCHAR(40) NOT NULL DEFAULT 'other',
    amount DECIMAL(18,2) NOT NULL DEFAULT 0,
    description VARCHAR(500) NULL,
    dept_slug VARCHAR(40) NOT NULL DEFAULT 'financial',
    phase VARCHAR(30) NOT NULL DEFAULT 'campaign',
    ref_type VARCHAR(40) NULL,
    ref_id BIGINT UNSIGNED NULL,
    entry_date DATE NOT NULL,
    created_by BIGINT UNSIGNED NULL,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    KEY idx_dir (direction),
    KEY idx_date (entry_date),
    KEY idx_cat (category)
) DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci" );
$log[] = 'transactions_table';

$at = Election_Havadaran::fin_audit_table();
$wpdb->query( "CREATE TABLE IF NOT EXISTS {$at} (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    user_id BIGINT UNSIGNED NULL,
    action VARCHAR(40) NOT NULL,
    detail TEXT NULL,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    KEY idx_action (action)
) DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci" );
$log[] = 'fin_audit_table';

if ( get_option( 'acc_election_otp_demo', false ) === false ) {
    update_option( 'acc_election_otp_demo', '1' );
    $log[] = 'otp_demo_default';
}

$seeded = Election_Havadaran::seed_budget_lines();
if ( $seeded ) {
    $log[] = "budget_seed_{$seeded}";
}

$import = Election_Havadaran::import_segments_from_gis( false );
$log[] = 'segment_import:' . wp_json_encode( [
    'imported' => $import['imported'] ?? 0,
    'total'    => $import['total'] ?? 0,
    'source'   => $import['source'] ?? '',
] );

$sample_tx = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$tt}" );
if ( $sample_tx === 0 ) {
    $admin = (int) $wpdb->get_var(
        "SELECT ID FROM {$wpdb->users} WHERE user_login='election_admin' LIMIT 1"
    );
    $uid = $admin ?: 1;
    $samples = [
        [ 'in',  'other',        15000000000, 'تخصیص اولیه ستاد انتخابات' ],
        [ 'out', 'media',        1200000000,  'پیش‌پرداخت آگهی شهری' ],
        [ 'out', 'goods',        850000000,   'خرید پرچم و بنر' ],
        [ 'out', 'distribution', 620000000,   'چاپ بروشور منطقه ۱' ],
        [ 'out', 'field',        400000000,   'هزینه عملیات میدانی هفته اول' ],
    ];
    foreach ( $samples as [ $dir, $cat, $amt, $desc ] ) {
        $wpdb->insert( $tt, [
            'direction'   => $dir,
            'category'    => $cat,
            'amount'      => $amt,
            'description' => $desc,
            'dept_slug'   => 'financial',
            'phase'       => 'campaign',
            'entry_date'  => current_time( 'Y-m-d' ),
            'created_by'  => $uid,
            'created_at'  => current_time( 'mysql' ),
        ] );
    }
    $log[] = 'sample_transactions';
}

echo json_encode( [
    'ok'      => true,
    'message' => 'v7 — 1011 پهنه + مالی + SMS OTP',
    'log'     => $log,
    'segments'=> Election_Havadaran::segment_stats(),
    'finance' => Election_Havadaran::financial_dashboard()['summary'] ?? [],
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT );
