<?php
/**
 * v5 — انبار اقلام تبلیغاتی + محل نصب بنر
 * C:\xampp\php\php.exe run-election-v5-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_warehouse_items (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    sku VARCHAR(40) NOT NULL,
    name VARCHAR(200) NOT NULL,
    category VARCHAR(30) NOT NULL DEFAULT 'other',
    unit VARCHAR(20) NOT NULL DEFAULT 'عدد',
    stock_qty INT NOT NULL DEFAULT 0,
    reserved_qty INT NOT NULL DEFAULT 0,
    notes TEXT NULL,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    UNIQUE KEY uk_sku (sku),
    KEY idx_cat (category)
) DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci" );
$log[] = 'warehouse_items';

$wpdb->query( "CREATE TABLE IF NOT EXISTS {$pre}election_warehouse_moves (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    item_id BIGINT UNSIGNED NOT NULL,
    user_id BIGINT UNSIGNED NULL,
    station_id BIGINT UNSIGNED NULL,
    qty INT NOT NULL DEFAULT 1,
    move_type VARCHAR(20) NOT NULL DEFAULT 'issue',
    notes VARCHAR(255) NULL,
    created_by BIGINT UNSIGNED NOT NULL,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    KEY idx_item (item_id)
) DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci" );
$log[] = 'warehouse_moves';

$wpdb->query( "CREATE TABLE IF NOT EXISTS {$pre}election_banner_spots (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    station_id BIGINT UNSIGNED NOT NULL,
    user_id BIGINT UNSIGNED NOT NULL,
    spot_type VARCHAR(30) NOT NULL DEFAULT 'wall',
    location_desc VARCHAR(255) NOT NULL,
    address VARCHAR(255) NULL,
    size VARCHAR(60) NULL,
    status VARCHAR(30) NOT NULL DEFAULT 'planned',
    phase VARCHAR(30) NULL,
    installed_at DATETIME NULL,
    notes TEXT NULL,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    KEY idx_station (station_id),
    KEY idx_user (user_id)
) DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci" );
$log[] = 'banner_spots';

$wt = Election_Havadaran::warehouse_table();
$seed_items = [
    [ 'BNR-3x6', 'بنر ۳×۶ متری',           'banner',  'عدد', 120 ],
    [ 'BNR-2x4', 'بنر ۲×۴ متری',           'banner',  'عدد', 200 ],
    [ 'PST-A4',  'پوستر A4',               'poster',  'عدد', 5000 ],
    [ 'PST-A3',  'پوستر A3',               'poster',  'عدد', 3000 ],
    [ 'FLG-SM',  'پرچم کوچک',              'flag',    'عدد', 800 ],
    [ 'STK-01',  'برچسب شیشه‌ای',          'sticker', 'بسته', 400 ],
    [ 'GFT-PEN', 'خودکار تبلیغاتی',        'gift',    'عدد', 2500 ],
    [ 'GFT-CAP', 'کلاه تبلیغاتی',          'gift',    'عدد', 600 ],
    [ 'BD-ROLL', 'رول بنر خام',            'banner',  'رول', 45 ],
    [ 'ZIP-TIE', 'بست پلاستیکی نصب',       'other',   'بسته', 200 ],
];
foreach ( $seed_items as [ $sku, $name, $cat, $unit, $qty ] ) {
    $exists = (int) $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$wt} WHERE sku=%s", $sku ) );
    if ( $exists ) {
        $wpdb->update( $wt, [ 'stock_qty' => $qty, 'name' => $name ], [ 'id' => $exists ] );
        continue;
    }
    $wpdb->insert( $wt, [
        'sku' => $sku, 'name' => $name, 'category' => $cat,
        'unit' => $unit, 'stock_qty' => $qty, 'reserved_qty' => 0,
    ] );
}
$log[] = 'warehouse_seed';

$bt   = Election_Havadaran::banner_spots_table();
$st   = Election_Havadaran::stations_table();
$sup1 = (int) $wpdb->get_var( "SELECT ID FROM {$wpdb->users} WHERE user_login='election_supporter_01'" );
$s101 = (int) $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$st} WHERE code=%s", 'S-101' ) );
$s102 = (int) $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$st} WHERE code=%s", 'S-102' ) );

if ( $sup1 && $s101 && ! (int) $wpdb->get_var( $wpdb->prepare(
    "SELECT COUNT(*) FROM {$bt} WHERE station_id=%d", $s101
) ) ) {
    $banners = [
        [ $s101, 'facade', 'نمای ساختمان مسجد جامع زند', 'خیابان زند — روبروی صندوق ۱۰۱', '3×6', 'installed' ],
        [ $s101, 'wall',   'دیوار کوچه نانوایی سنگک',    'کوچه ۱۲ زند', '2×4', 'approved' ],
        [ $s102, 'board',  'تابلو ورودی معالی‌آباد',     'میدان معالی‌آباد', '3×6', 'planned' ],
        [ $s102, 'shop',   'ویترین سوپرمارکت',           'بلوار معالی‌آباد', 'A3 پوستر', 'planned' ],
    ];
    foreach ( $banners as [ $sid, $type, $loc, $addr, $size, $status ] ) {
        $wpdb->insert( $bt, [
            'station_id'    => $sid,
            'user_id'       => $sup1,
            'spot_type'     => $type,
            'location_desc' => $loc,
            'address'       => $addr,
            'size'          => $size,
            'status'        => $status,
            'phase'         => Election_Havadaran::current_phase(),
            'installed_at'  => $status === 'installed' ? current_time( 'mysql' ) : null,
            'created_at'    => current_time( 'mysql' ),
        ] );
    }
    $log[] = 'banner_seed';
}

echo json_encode( [
    'ok'      => true,
    'message' => 'v5 — انبار + محل نصب بنر',
    'log'     => $log,
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT );
