<?php
/**
 * v6 — GIS هوادار، onboarding، زنجیره انبار-محموله
 * C:\xampp\php\php.exe run-election-v6-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 = [];

$wpdb->query( "CREATE TABLE IF NOT EXISTS {$pre}election_onboarding (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    phone VARCHAR(20) NOT NULL,
    otp_code VARCHAR(10) NOT NULL,
    token VARCHAR(64) NOT NULL,
    status VARCHAR(20) NOT NULL DEFAULT 'pending',
    invited_by BIGINT UNSIGNED NULL,
    user_id BIGINT UNSIGNED NULL,
    expires_at DATETIME NOT NULL,
    verified_at DATETIME NULL,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    KEY idx_phone (phone),
    KEY idx_token (token)
) DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci" );
$log[] = 'onboarding_table';

$sht = Election_Havadaran::shipments_table();
$cols = $wpdb->get_col( "SHOW COLUMNS FROM {$sht}", 0 );
if ( ! in_array( 'warehouse_move_id', $cols, true ) ) {
    $wpdb->query( "ALTER TABLE {$sht} ADD COLUMN warehouse_move_id BIGINT UNSIGNED NULL AFTER package_id" );
    $log[] = 'shipments_warehouse_move_id';
}
if ( ! in_array( 'items_json', $cols, true ) ) {
    $wpdb->query( "ALTER TABLE {$sht} ADD COLUMN items_json TEXT NULL AFTER warehouse_move_id" );
    $log[] = 'shipments_items_json';
}

$mt = Election_Havadaran::warehouse_moves_table();
if ( $wpdb->get_var( "SHOW TABLES LIKE '{$mt}'" ) === $mt ) {
    $mcols = $wpdb->get_col( "SHOW COLUMNS FROM {$mt}", 0 );
    if ( ! in_array( 'shipment_id', $mcols, true ) ) {
        $wpdb->query( "ALTER TABLE {$mt} ADD COLUMN shipment_id BIGINT UNSIGNED NULL AFTER station_id" );
        $log[] = 'warehouse_moves_shipment_id';
    }
}

$poi_t = Election_Havadaran::station_pois_table();
$pcols = $wpdb->get_col( "SHOW COLUMNS FROM {$poi_t}", 0 );
if ( ! in_array( 'lat', $pcols, true ) ) {
    $wpdb->query( "ALTER TABLE {$poi_t} ADD COLUMN lat DECIMAL(10,7) NULL, ADD COLUMN lng DECIMAL(10,7) NULL" );
    $log[] = 'poi_lat_lng';
}

echo json_encode( [
    'ok'      => true,
    'message' => 'v6 — GIS + onboarding + shipment chain',
    'log'     => $log,
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT );
