<?php
/**
 * نصب/ارتقای الگوریتم جامع خدمات v17.9
 * php run-service-algorithm-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;
$pre = $wpdb->prefix;

$alters = [
    "ALTER TABLE {$pre}svc_requests ADD COLUMN priority VARCHAR(20) NOT NULL DEFAULT 'normal'",
    "ALTER TABLE {$pre}svc_requests ADD COLUMN extra_data JSON NULL",
    "ALTER TABLE {$pre}svc_requests ADD COLUMN cost_estimate DECIMAL(15,2) NOT NULL DEFAULT 0",
    "ALTER TABLE {$pre}svc_requests ADD COLUMN cost_approved TINYINT(1) NOT NULL DEFAULT 0",
    "ALTER TABLE {$pre}svc_requests ADD COLUMN cost_approved_at DATETIME NULL",
    "ALTER TABLE {$pre}svc_reports ADD COLUMN photos_before JSON NULL",
    "ALTER TABLE {$pre}svc_reports ADD COLUMN photos_after JSON NULL",
    "ALTER TABLE {$pre}svc_reports ADD COLUMN cost_approval_status VARCHAR(20) NOT NULL DEFAULT 'none'",
    "ALTER TABLE {$pre}svc_reports ADD COLUMN cost_approval_at DATETIME NULL",
    "ALTER TABLE {$pre}svc_pm_contracts ADD COLUMN operating_hours INT UNSIGNED NOT NULL DEFAULT 0",
    "ALTER TABLE {$pre}svc_pm_contracts ADD COLUMN visit_result JSON NULL",
    "ALTER TABLE {$pre}svc_reward_accounts ADD COLUMN active_benefits JSON NULL",
];

$applied = [];
foreach ( $alters as $sql ) {
    preg_match( '/ADD COLUMN (\w+)/', $sql, $m );
    $col = $m[1] ?? '';
    $table = str_contains( $sql, 'svc_requests' ) ? 'svc_requests'
        : ( str_contains( $sql, 'svc_reports' ) ? 'svc_reports'
        : ( str_contains( $sql, 'svc_pm_contracts' ) ? 'svc_pm_contracts' : 'svc_reward_accounts' ) );
    if ( $col && $wpdb->get_var( "SHOW COLUMNS FROM {$pre}{$table} LIKE '{$col}'" ) ) {
        continue;
    }
    $wpdb->query( $sql );
    $applied[] = "{$table}.{$col}";
}

$charset = 'DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci';

$wpdb->query( "CREATE TABLE IF NOT EXISTS {$pre}svc_parts_orders (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    request_id BIGINT UNSIGNED NULL,
    tracking_code VARCHAR(6) NULL,
    customer_name VARCHAR(200) NOT NULL DEFAULT '',
    phone VARCHAR(20) NOT NULL DEFAULT '',
    part_number VARCHAR(100) NOT NULL DEFAULT '',
    part_qty INT NOT NULL DEFAULT 1,
    status VARCHAR(30) NOT NULL DEFAULT 'pending',
    supplier_id BIGINT UNSIGNED NULL,
    quote_price DECIMAL(15,2) NOT NULL DEFAULT 0,
    deposit_amount DECIMAL(15,2) NOT NULL DEFAULT 0,
    eta_days INT NOT NULL DEFAULT 5,
    in_stock TINYINT(1) NOT NULL DEFAULT 0,
    notes TEXT NULL,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    KEY request_id (request_id),
    KEY status (status)
) {$charset}" );

$wpdb->query( "CREATE TABLE IF NOT EXISTS {$pre}svc_equipment_inquiries (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    request_id BIGINT UNSIGNED NULL,
    tracking_code VARCHAR(6) NULL,
    customer_name VARCHAR(200) NOT NULL DEFAULT '',
    phone VARCHAR(20) NOT NULL DEFAULT '',
    project_city VARCHAR(100) NOT NULL DEFAULT '',
    application VARCHAR(100) NOT NULL DEFAULT '',
    required_capacity VARCHAR(100) NOT NULL DEFAULT '',
    budget_range VARCHAR(100) NOT NULL DEFAULT '',
    status VARCHAR(30) NOT NULL DEFAULT 'inquiry',
    quote_options JSON NULL,
    selected_option VARCHAR(50) NULL,
    notes TEXT NULL,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (id)
) {$charset}" );

update_option( 'acc_engine_db_version', '17.9' );

echo json_encode( [
    'success' => true,
    'db_version' => '17.9',
    'columns_added' => $applied,
    'tables' => [ 'svc_parts_orders', 'svc_equipment_inquiries' ],
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT );
