<?php
/**
 * run-election-install.php — سامانه هوادران انتخابات
 * C:\xampp\php\php.exe run-election-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';
require_once ACC_PATH . 'includes/helpers/acl-functions.php';

$pre     = $wpdb->prefix;
$charset = 'DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci';
$pass    = 'Election1234';
$log     = [];

$ddl = [
    "CREATE TABLE IF NOT EXISTS {$pre}election_stations (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        code VARCHAR(20) NOT NULL,
        name VARCHAR(200) NOT NULL,
        address TEXT NULL,
        neighborhood VARCHAR(120) NULL,
        lat DECIMAL(10,7) NULL,
        lng DECIMAL(10,7) NULL,
        PRIMARY KEY (id),
        UNIQUE KEY idx_code (code)
    ) {$charset}",

    "CREATE TABLE IF NOT EXISTS {$pre}election_segments (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        code VARCHAR(30) NOT NULL,
        neighborhood VARCHAR(120) NOT NULL,
        part_no TINYINT UNSIGNED NOT NULL DEFAULT 1,
        station_id BIGINT UNSIGNED NULL,
        voter_count INT UNSIGNED NOT NULL DEFAULT 0,
        age_profile_json JSON NULL,
        lat DECIMAL(10,7) NULL,
        lng DECIMAL(10,7) NULL,
        notes TEXT NULL,
        PRIMARY KEY (id),
        UNIQUE KEY idx_code (code),
        KEY idx_nb (neighborhood),
        KEY idx_station (station_id)
    ) {$charset}",

    "CREATE TABLE IF NOT EXISTS {$pre}election_branches (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        user_id BIGINT UNSIGNED NOT NULL,
        title VARCHAR(200) NOT NULL,
        category VARCHAR(40) NOT NULL DEFAULT 'personnel',
        zone_json JSON NULL,
        phone VARCHAR(30) NULL,
        is_active TINYINT(1) NOT NULL DEFAULT 1,
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (id),
        KEY idx_user (user_id),
        KEY idx_cat (category)
    ) {$charset}",

    "CREATE TABLE IF NOT EXISTS {$pre}election_supporters (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        user_id BIGINT UNSIGNED NOT NULL,
        branch_id BIGINT UNSIGNED NOT NULL,
        display_name VARCHAR(120) NULL,
        phone VARCHAR(30) NULL,
        segment_ids_json JSON NULL,
        performance_score INT UNSIGNED NOT NULL DEFAULT 0,
        tasks_done INT UNSIGNED NOT NULL DEFAULT 0,
        is_active TINYINT(1) NOT NULL DEFAULT 1,
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (id),
        KEY idx_user (user_id),
        KEY idx_branch (branch_id)
    ) {$charset}",

    "CREATE TABLE IF NOT EXISTS {$pre}election_content (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        title VARCHAR(200) NOT NULL,
        body TEXT NOT NULL,
        content_type VARCHAR(30) NOT NULL DEFAULT 'training',
        audience VARCHAR(30) NOT NULL DEFAULT 'all',
        branch_id BIGINT UNSIGNED NULL,
        segment_id BIGINT UNSIGNED NULL,
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (id)
    ) {$charset}",

    "CREATE TABLE IF NOT EXISTS {$pre}election_packages (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        barcode VARCHAR(40) NOT NULL,
        size_type VARCHAR(10) NOT NULL DEFAULT '21',
        branch_id BIGINT UNSIGNED NULL,
        title VARCHAR(200) NULL,
        status VARCHAR(30) NOT NULL DEFAULT 'ready',
        distributed_count INT UNSIGNED NOT NULL DEFAULT 0,
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (id),
        UNIQUE KEY idx_barcode (barcode)
    ) {$charset}",

    "CREATE TABLE IF NOT EXISTS {$pre}election_sms_log (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        phone VARCHAR(30) NOT NULL,
        message TEXT NOT NULL,
        user_id BIGINT UNSIGNED NULL,
        status VARCHAR(20) NOT NULL DEFAULT 'sent',
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (id)
    ) {$charset}",

    "CREATE TABLE IF NOT EXISTS {$pre}election_reports (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        user_id BIGINT UNSIGNED NOT NULL,
        branch_id BIGINT UNSIGNED NULL,
        report_type VARCHAR(40) NOT NULL DEFAULT 'activity',
        title VARCHAR(200) NULL,
        body TEXT NULL,
        segment_id BIGINT UNSIGNED NULL,
        status VARCHAR(30) NOT NULL DEFAULT 'submitted',
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (id),
        KEY idx_user (user_id)
    ) {$charset}",
];

foreach ( $ddl as $sql ) {
    $wpdb->query( $sql );
    $log[] = 'table_ok';
}

foreach ( [
    [ 'election.manage', 'مدیریت ستاد انتخابات', 'election' ],
    [ 'election.branch', 'سرشاخه هواداران', 'election' ],
    [ 'election.supporter', 'هوادار انتخابات', 'election' ],
] as [ $key, $label, $grp ] ) {
    if ( ! $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$pre}acl_permissions WHERE permission_key=%s", $key ) ) ) {
        $wpdb->insert( "{$pre}acl_permissions", [
            'permission_key' => $key, 'label' => $label, 'group_slug' => $grp, 'sort_order' => 0,
        ] );
    }
}

foreach ( [
    [ 'election_admin', 'مدیر ستاد انتخابات', 22 ],
    [ 'election_branch', 'سرشاخه', 23 ],
    [ 'election_supporter', 'هوادار', 24 ],
] as $r ) {
    if ( ! $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$pre}acl_roles WHERE slug=%s", $r[0] ) ) ) {
        $wpdb->insert( "{$pre}acl_roles", [
            'slug' => $r[0], 'name' => $r[1], 'description' => $r[1], 'sort_order' => $r[2], 'is_system' => 1,
        ] );
    }
}

$role_perms = [
    'election_admin'     => [ 'election.manage', 'election.branch', 'election.supporter' ],
    'election_branch'    => [ 'election.branch', 'election.supporter' ],
    'election_supporter' => [ 'election.supporter' ],
];
foreach ( $role_perms as $slug => $perms ) {
    $rid = (int) $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$pre}acl_roles WHERE slug=%s", $slug ) );
    foreach ( $perms as $pk ) {
        $wpdb->query( $wpdb->prepare(
            "INSERT IGNORE INTO {$pre}acl_role_permissions (role_id, permission_key) VALUES (%d, %s)", $rid, $pk
        ) );
    }
}

function el_user( string $login, string $name, string $role ): int {
    global $wpdb, $pass, $log, $pre;
    $id = (int) $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM {$wpdb->users} WHERE user_login=%s", $login ) );
    if ( ! $id ) {
        $id = (int) $wpdb->get_var( "SELECT COALESCE(MAX(ID),0) FROM {$wpdb->users}" ) + 1;
        $wpdb->insert( "{$wpdb->users}", [
            'ID' => $id, 'user_login' => $login, 'user_pass' => wp_hash_password( $pass ),
            'user_nicename' => sanitize_title( $login ), 'user_email' => $login . '@election.test',
            'user_registered' => current_time( 'mysql' ), 'display_name' => $name, 'user_status' => 0,
        ] );
        $log[] = "user:{$login}";
    }
    $rid = (int) $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$pre}acl_roles WHERE slug=%s", $role ) );
    if ( $rid && ! (int) $wpdb->get_var( $wpdb->prepare(
        "SELECT COUNT(*) FROM {$pre}acl_user_roles WHERE user_id=%d AND role_id=%d", $id, $rid
    ) ) ) {
        $wpdb->insert( "{$pre}acl_user_roles", [
            'user_id' => $id, 'role_id' => $rid, 'scope_type' => 'global', 'scope_id' => null, 'granted_by' => 2,
        ] );
    }
    return $id;
}

$uid_admin = el_user( 'election_admin', 'مدیر ستاد — GIS', 'election_admin' );
$uid_waste = el_user( 'election_branch_waste', 'سرشاخه پسماند — آقای رحیمی', 'election_branch' );
$uid_green = el_user( 'election_branch_green', 'سرشاخه فضای سبز — خانم کاظمی', 'election_branch' );
$uid_dense = el_user( 'election_branch_dense', 'سرشاخه ساختمان پرتراکم — آقای موسوی', 'election_branch' );
$uid_sup1  = el_user( 'election_supporter_01', 'هوادار — رضا نوروزی', 'election_supporter' );
$uid_sup2  = el_user( 'election_supporter_02', 'هوادار — مریم صادقی', 'election_supporter' );
$uid_sup3  = el_user( 'election_supporter_03', 'هوادار — علی حیدری', 'election_supporter' );

$st = Election_Havadaran::stations_table();
$sg = Election_Havadaran::segments_table();

$stations = [
    [ 'S-101', 'صندوق ۱۰۱ — زند', 'بلوار زند، مدرسه شهید فلاح', 'زند', 29.6100, 52.5310 ],
    [ 'S-102', 'صندوق ۱۰۲ — معالی‌آباد', 'معالی‌آباد، فرهنگ‌شهر', 'معالی‌آباد', 29.6380, 52.4880 ],
    [ 'S-103', 'صندوق ۱۰۳ — درکی', 'درکی، کوچه گلستان', 'درکی', 29.6280, 52.5120 ],
    [ 'S-104', 'صندوق ۱۰۴ — ستارخان', 'ستارخان، نبش کوچه ۱۲', 'ستارخان', 29.6520, 52.4780 ],
];
$station_ids = [];
foreach ( $stations as $s ) {
    $exists = (int) $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$st} WHERE code=%s", $s[0] ) );
    $row = [ 'code' => $s[0], 'name' => $s[1], 'address' => $s[2], 'neighborhood' => $s[3], 'lat' => $s[4], 'lng' => $s[5] ];
    if ( $exists ) {
        $wpdb->update( $st, $row, [ 'id' => $exists ] );
        $station_ids[ $s[0] ] = $exists;
    } else {
        $wpdb->insert( $st, $row );
        $station_ids[ $s[0] ] = (int) $wpdb->insert_id;
    }
}

$neighborhoods = [
    [ 'زند', 'S-101', 3 ], [ 'معالی‌آباد', 'S-102', 3 ], [ 'درکی', 'S-103', 3 ],
    [ 'ستارخان', 'S-104', 3 ], [ 'ملک‌آباد', 'S-101', 3 ], [ 'گلستان', 'S-102', 3 ],
    [ 'پارک آزادی', 'S-103', 2 ], [ 'دروازه قرآن', 'S-104', 2 ],
];
$segment_ids = [];
$seg_num = 0;
foreach ( $neighborhoods as [ $nb, $st_code, $parts ] ) {
    for ( $p = 1; $p <= $parts; $p++ ) {
        $seg_num++;
        $code = sprintf( 'SHZ-%04d', $seg_num );
        $voters = rand( 180, 420 );
        $age = wp_json_encode( [
            '18-25' => rand( 15, 25 ), '26-40' => rand( 30, 45 ),
            '41-60' => rand( 20, 35 ), '60+' => rand( 8, 18 ),
        ] );
        $exists = (int) $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$sg} WHERE code=%s", $code ) );
        $data = [
            'code' => $code, 'neighborhood' => $nb, 'part_no' => $p,
            'station_id' => $station_ids[ $st_code ] ?? null,
            'voter_count' => $voters, 'age_profile_json' => $age,
            'lat' => 29.60 + ( $seg_num * 0.002 ), 'lng' => 52.48 + ( $seg_num * 0.003 ),
            'notes' => "پهنه GIS — {$nb} بخش {$p}",
        ];
        if ( $exists ) {
            $wpdb->update( $sg, $data, [ 'id' => $exists ] );
            $segment_ids[] = $exists;
        } else {
            $wpdb->insert( $sg, $data );
            $segment_ids[] = (int) $wpdb->insert_id;
        }
    }
}

$bt = Election_Havadaran::branches_table();
$branch_defs = [
    [ $uid_waste, 'سرشاخه کارکنان پسماند — منطقه ۱', 'waste', array_slice( $segment_ids, 0, 6 ) ],
    [ $uid_green, 'سرشاخه فضای سبز — پارک و بوستان', 'green_space', array_slice( $segment_ids, 6, 6 ) ],
    [ $uid_dense, 'سرشاخه ساختمان‌های پرتراکم', 'dense_buildings', array_slice( $segment_ids, 12, 6 ) ],
];
$branch_ids = [];
foreach ( $branch_defs as [ $uid, $title, $cat, $segs ] ) {
    $exists = (int) $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$bt} WHERE user_id=%d", $uid ) );
    $row = [
        'user_id' => $uid, 'title' => $title, 'category' => $cat,
        'zone_json' => wp_json_encode( [ 'segment_ids' => $segs, 'city' => 'شیراز' ], JSON_UNESCAPED_UNICODE ),
        'phone' => '0917' . rand( 1000000, 9999999 ), 'is_active' => 1,
        'created_at' => current_time( 'mysql' ),
    ];
    if ( $exists ) {
        $wpdb->update( $bt, $row, [ 'id' => $exists ] );
        $branch_ids[] = $exists;
    } else {
        $wpdb->insert( $bt, $row );
        $branch_ids[] = (int) $wpdb->insert_id;
    }
}

$supt = Election_Havadaran::supporters_table();
$sup_defs = [
    [ $uid_sup1, $branch_ids[0], 'رضا نوروزی', [ $segment_ids[0], $segment_ids[1] ], 12 ],
    [ $uid_sup2, $branch_ids[1], 'مریم صادقی', [ $segment_ids[6], $segment_ids[7] ], 8 ],
    [ $uid_sup3, $branch_ids[2], 'علی حیدری', [ $segment_ids[12], $segment_ids[13] ], 15 ],
];
foreach ( $sup_defs as [ $uid, $bid, $name, $segs, $score ] ) {
    $exists = (int) $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$supt} WHERE user_id=%d", $uid ) );
    $row = [
        'user_id' => $uid, 'branch_id' => $bid, 'display_name' => $name,
        'phone' => '0918' . rand( 1000000, 9999999 ),
        'segment_ids_json' => wp_json_encode( $segs ),
        'performance_score' => $score, 'tasks_done' => $score, 'is_active' => 1,
        'created_at' => current_time( 'mysql' ),
    ];
    if ( $exists ) {
        $wpdb->update( $supt, $row, [ 'id' => $exists ] );
    } else {
        $wpdb->insert( $supt, $row );
    }
}

$ct = Election_Havadaran::content_table();
$content = [
    [ 'آموزش هوادار — اصول رفتار انتخاباتی', 'محتوای اختصاصی بر اساس پهنه GIS شما. لطفاً فقط در محدوده جغرافیایی تعیین‌شده فعالیت کنید.', 'training', 'supporter', null, null ],
    [ 'راهنمای سرشاخه — توزیع بسته ۲۱ نفره', 'بسته‌های بارکددار را طبق برنامه بند ۸ توزیع کنید.', 'guide', 'branch', $branch_ids[0], null ],
    [ 'تحلیل سن رأی‌دهندگان — محله زند', 'پراکندگی سنی در پهنه SHZ-0001 تا SHZ-0003', 'analysis', 'supporter', null, $segment_ids[0] ],
    [ 'معرفی سامانه هواداری', 'کاهش هزینه تبلیغات با سایت هواداری و SMS خودکار', 'intro', 'all', null, null ],
];
foreach ( $content as $c ) {
    $exists = (int) $wpdb->get_var( $wpdb->prepare(
        "SELECT id FROM {$ct} WHERE title=%s", $c[0]
    ) );
    if ( ! $exists ) {
        $wpdb->insert( $ct, [
            'title' => $c[0], 'body' => $c[1], 'content_type' => $c[2],
            'audience' => $c[3], 'branch_id' => $c[4], 'segment_id' => $c[5],
            'created_at' => current_time( 'mysql' ),
        ] );
    }
}

$pt = Election_Havadaran::packages_table();
foreach ( [ '21', '31', '01', '111' ] as $size ) {
    $bc = 'ELC-' . strtoupper( $size ) . '-' . substr( md5( $size ), 0, 8 );
    if ( ! $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$pt} WHERE barcode=%s", $bc ) ) ) {
        $wpdb->insert( $pt, [
            'barcode' => $bc, 'size_type' => $size,
            'branch_id' => $branch_ids[ array_rand( $branch_ids ) ],
            'title' => Election_Havadaran::PACKAGE_SIZES[ $size ]['label'],
            'status' => 'ready', 'created_at' => current_time( 'mysql' ),
        ] );
    }
}

$site_url = '/acc-engine/election.php';
Election_Havadaran::queue_sms( [
    'phone' => '09171234567',
    'message' => "سامانه هوادران: {$site_url}\nکاربر: election_supporter_01\nرمز: {$pass}",
    'user_id' => $uid_sup1,
] );

echo json_encode( [
    'ok'      => true,
    'message' => 'سامانه هوادران انتخابات نصب شد',
    'demo'    => [
        'password' => $pass,
        'url'      => $site_url,
        'users'    => [
            [ 'login' => 'election_admin', 'role' => 'مدیر ستاد' ],
            [ 'login' => 'election_branch_waste', 'role' => 'سرشاخه پسماند' ],
            [ 'login' => 'election_branch_green', 'role' => 'سرشاخه فضای سبز' ],
            [ 'login' => 'election_branch_dense', 'role' => 'سرشاخه ساختمان پرتراکم' ],
            [ 'login' => 'election_supporter_01', 'role' => 'هوادار' ],
            [ 'login' => 'election_supporter_02', 'role' => 'هوادار' ],
            [ 'login' => 'election_supporter_03', 'role' => 'هوادار' ],
        ],
    ],
    'stats' => Election_Havadaran::stats(),
    'log'   => $log,
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT );
