<?php
/**
 * ارتقاء v2 — ستاد شخصی + missions + sync GIS
 * C:\xampp\php\php.exe run-election-v2-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;
$charset = 'DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci';
$log     = [];

$wpdb->query( "CREATE TABLE IF NOT EXISTS {$pre}election_hqs (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    user_id BIGINT UNSIGNED NOT NULL,
    hq_code VARCHAR(20) NOT NULL,
    title VARCHAR(200) NOT NULL,
    role_type VARCHAR(20) NOT NULL DEFAULT 'personal',
    category VARCHAR(40) NULL,
    zone_label VARCHAR(255) NULL,
    neighborhood_name VARCHAR(120) NULL,
    district_name VARCHAR(120) NULL,
    gis_neighborhood_id BIGINT UNSIGNED NULL,
    block_codes_json JSON NULL,
    parcel_count INT UNSIGNED NOT NULL DEFAULT 0,
    household_estimate INT UNSIGNED NOT NULL DEFAULT 0,
    voter_estimate INT UNSIGNED NOT NULL DEFAULT 0,
    mission_brief TEXT NULL,
    gis_intel_json JSON NULL,
    parent_hq_id BIGINT UNSIGNED NULL,
    performance_score INT UNSIGNED NOT NULL DEFAULT 0,
    tasks_done INT UNSIGNED NOT NULL DEFAULT 0,
    missions_done INT UNSIGNED NOT NULL DEFAULT 0,
    phone VARCHAR(30) NULL,
    is_active TINYINT(1) 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),
    UNIQUE KEY idx_user (user_id),
    UNIQUE KEY idx_code (hq_code),
    KEY idx_role (role_type)
) {$charset}" );

$wpdb->query( "CREATE TABLE IF NOT EXISTS {$pre}election_missions (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    hq_id BIGINT UNSIGNED NOT NULL,
    title VARCHAR(200) NOT NULL,
    body TEXT NOT NULL,
    mission_type VARCHAR(40) NOT NULL DEFAULT 'general',
    target_count INT UNSIGNED NOT NULL DEFAULT 1,
    progress_count INT UNSIGNED NOT NULL DEFAULT 0,
    status VARCHAR(30) NOT NULL DEFAULT 'pending',
    due_date DATE NULL,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    KEY idx_hq (hq_id),
    KEY idx_status (status)
) {$charset}" );

$log[] = 'tables_v2_ok';

function elv2_upsert_hq( int $uid, array $d ): int {
    global $wpdb, $log;
    $t = Election_Havadaran::hqs_table();
    $exists = (int) $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$t} WHERE user_id = %d", $uid ) );
    $row = array_merge( [
        'user_id' => $uid, 'is_active' => 1,
        'created_at' => current_time( 'mysql' ),
        'updated_at' => current_time( 'mysql' ),
    ], $d );
    if ( $exists ) {
        unset( $row['created_at'] );
        $wpdb->update( $t, $row, [ 'id' => $exists ] );
        return $exists;
    }
    $wpdb->insert( $t, $row );
    $log[] = 'hq:' . $d['hq_code'];
    return (int) $wpdb->insert_id;
}

$user_map = [
    'election_admin'          => [ 'HQ-ADM', 'مرکز intel — مدیر سامانه', 'coordinator', 'personnel', null ],
    'election_branch_waste'   => [ 'HQ-WST', 'ستاد شخصی — پسماند', 'coordinator', 'waste', null ],
    'election_branch_green'   => [ 'HQ-GRN', 'ستاد شخصی — فضای سبز', 'coordinator', 'green_space', null ],
    'election_branch_dense'   => [ 'HQ-DNS', 'ستاد شخصی — ساختمان پرتراکم', 'coordinator', 'dense_buildings', null ],
    'election_supporter_01'   => [ 'HQ-P01', 'ستاد رضا نوروزی', 'personal', 'waste', 'election_branch_waste' ],
    'election_supporter_02'   => [ 'HQ-P02', 'ستاد مریم صادقی', 'personal', 'green_space', 'election_branch_green' ],
    'election_supporter_03'   => [ 'HQ-P03', 'ستاد علی حیدری', 'personal', 'dense_buildings', 'election_branch_dense' ],
];

$parent_ids = [];
foreach ( $user_map as $login => [ $code, $title, $role, $cat, $parent_login ] ) {
    $uid = (int) $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM {$wpdb->users} WHERE user_login = %s", $login ) );
    if ( ! $uid ) continue;

    $parent_id = null;
    if ( $parent_login && isset( $parent_ids[ $parent_login ] ) ) {
        $parent_id = $parent_ids[ $parent_login ];
    }

    $hid = elv2_upsert_hq( $uid, [
        'hq_code'   => $code,
        'title'     => $title,
        'role_type' => $role,
        'category'  => $cat,
        'parent_hq_id' => $parent_id,
        'phone'     => '0917' . rand( 1000000, 9999999 ),
        'performance_score' => rand( 5, 25 ),
        'tasks_done' => rand( 3, 15 ),
    ] );
    $parent_ids[ $login ] = $hid;
}

$gis = Election_Havadaran::admin_gis_intel();
if ( ! empty( $gis['available'] ) && ! empty( $gis['neighborhoods'] ) ) {
    $hqs = Election_Havadaran::list_hqs( true );
    $nb_list = $gis['neighborhoods'];
    $blocks  = $gis['blocks'];
    foreach ( $hqs as $i => $hq ) {
        if ( $hq['hq_code'] === 'HQ-ADM' ) continue;
        $nb = $nb_list[ $i % count( $nb_list ) ];
        $nb_blocks = array_values( array_filter( $blocks, fn( $b ) => (int) ( $b['neighborhood_id'] ?? 0 ) === (int) $nb['id'] ) );
        $bc = array_slice( array_column( $nb_blocks, 'block_code' ), 0, 2 );
        Election_Havadaran::assign_zone_to_hq( (int) $hq['id'], [
            'neighborhood_id' => (int) $nb['id'],
            'block_codes'     => $bc,
        ] );
        $log[] = 'zone:' . $hq['hq_code'];
    }
}

echo json_encode( [
    'ok'      => true,
    'message' => 'ارتقاء v2 — ستاد شخصی + GIS intel',
    'gis'     => [
        'available' => $gis['available'] ?? false,
        'neighborhoods' => count( $gis['neighborhoods'] ?? [] ),
        'blocks' => count( $gis['blocks'] ?? [] ),
    ],
    'hqs'     => count( Election_Havadaran::list_hqs() ),
    'log'     => $log,
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT );
