<?php
/**
 * داده دمو HVAC Reward Engine
 * php run-service-reward-seed.php [--reset]
 */
declare(strict_types=1);

if ( ! defined( 'ACC_BASE_PATH' ) ) {
    define( 'ACC_BASE_PATH', __DIR__ );
    require __DIR__ . '/standalone/bootstrap.php';
}

require_once ACC_PATH . 'includes/helpers/svc-rewards.php';

header( 'Content-Type: application/json; charset=utf-8' );
global $wpdb;
$pre = $wpdb->prefix;
$reset = in_array( '--reset', $argv ?? [], true );

function seed_assign_role( int $user_id, string $role_slug ): void {
    global $wpdb;
    $role_id = (int) $wpdb->get_var( $wpdb->prepare(
        "SELECT id FROM {$wpdb->prefix}acl_roles WHERE slug=%s", $role_slug
    ) );
    if ( ! $role_id ) return;
    $exists = $wpdb->get_var( $wpdb->prepare(
        "SELECT id FROM {$wpdb->prefix}acl_user_roles WHERE user_id=%d AND role_id=%d AND scope_type='global'",
        $user_id, $role_id
    ) );
    if ( ! $exists ) {
        $wpdb->insert( "{$wpdb->prefix}acl_user_roles", [
            'user_id' => $user_id, 'role_id' => $role_id, 'scope_type' => 'global', 'scope_id' => null,
        ] );
    }
}

if ( $reset ) {
    $wpdb->query( "DELETE FROM {$pre}svc_reward_badges" );
    $wpdb->query( "DELETE FROM {$pre}svc_reward_ledger" );
    $wpdb->query( "DELETE FROM {$pre}svc_reward_accounts" );
}

function seed_ensure_user( string $login, string $display, string $email ): int {
    global $wpdb;
    $id = (int) $wpdb->get_var( $wpdb->prepare(
        "SELECT ID FROM {$wpdb->users} WHERE user_login=%s AND ID>0", $login
    ) );
    if ( $id ) return $id;

    $new_id = (int) $wpdb->get_var( "SELECT COALESCE(MAX(ID),0)+1 FROM {$wpdb->users}" );
    $wpdb->insert( $wpdb->users, [
        'ID' => $new_id,
        'user_login' => $login,
        'user_pass' => password_hash( 'SvcReward@1404', PASSWORD_BCRYPT ),
        'user_nicename' => $login,
        'user_email' => $email,
        'user_registered' => current_time( 'mysql' ),
        'display_name' => $display,
    ] );
    return $new_id;
}

// ── مشتریان دمو ──
$cust1 = Svc_Rewards::get_or_create_account( 'customer', [
    'phone' => '09121234567',
    'display_name' => 'علی رضایی — مشتری دمو',
] );
$cust2 = Svc_Rewards::get_or_create_account( 'customer', [
    'phone' => '09129876543',
    'display_name' => 'مریم احمدی — مشتری VIP',
] );

// ── تکنسین (svc_tech1_demo اگر موجود باشد) ──
$tech_uid = (int) $wpdb->get_var( $wpdb->prepare(
    "SELECT ID FROM {$wpdb->users} WHERE user_login=%s", 'svc_tech1_demo'
) );
if ( ! $tech_uid ) {
    $tech_uid = seed_ensure_user( 'svc_tech1_demo', 'رضا موسوی — تکنسین دمو', 'tech1.demo@test.local' );
}
$tech = Svc_Rewards::get_or_create_account( 'technician', [ 'user_id' => $tech_uid ] );

// ── تأمین‌کننده ──
$sup_uid = seed_ensure_user( 'svc_supplier_demo', 'شرکت قطعات سردخانه', 'supplier.demo@test.local' );
$supplier = Svc_Rewards::get_or_create_account( 'supplier', [ 'user_id' => $sup_uid ] );

seed_assign_role( $tech_uid, 'service_technician' );
seed_assign_role( $sup_uid, 'service_supplier' );

// امتیاز اولیه (فقط اگر ledger خالی)
$seeds = [
    [ (int) $cust1['id'], 'register', [ 'dedupe_key' => 'seed_reg1' ] ],
    [ (int) $cust1['id'], 'first_request', [ 'dedupe_key' => 'seed_req1', 'order_value' => 3500000 ] ],
    [ (int) $cust1['id'], 'online_payment', [ 'dedupe_key' => 'seed_pay1', 'order_value' => 2500000 ] ],
    [ (int) $cust2['id'], 'register', [ 'dedupe_key' => 'seed_reg2' ] ],
    [ (int) $cust2['id'], 'pm_annual', [ 'dedupe_key' => 'seed_pm2' ] ],
    [ (int) $cust2['id'], 'referral', [ 'dedupe_key' => 'seed_ref2' ] ],
    [ (int) $tech['id'], 'mission_done', [ 'dedupe_key' => 'seed_m1', 'order_value' => 12000000 ] ],
    [ (int) $tech['id'], 'full_report', [ 'dedupe_key' => 'seed_rep1' ] ],
    [ (int) $tech['id'], 'high_satisfaction', [ 'dedupe_key' => 'seed_sat1', 'quality_mult' => 1.5 ] ],
    [ (int) $tech['id'], 'no_revisit', [ 'dedupe_key' => 'seed_nrv1' ] ],
    [ (int) $supplier['id'], 'on_time_delivery', [ 'dedupe_key' => 'seed_del1' ] ],
    [ (int) $supplier['id'], 'high_quality', [ 'dedupe_key' => 'seed_q1', 'quality_mult' => 1.8 ] ],
    [ (int) $supplier['id'], 'fast_shipping', [ 'dedupe_key' => 'seed_ship1' ] ],
];

$earned = 0;
foreach ( $seeds as [ $aid, $key, $opts ] ) {
    if ( Svc_Rewards::earn( $aid, $key, $opts ) ) $earned++;
}

// ارتقای سطح مشتری ۲ با امتیاز بیشتر
for ( $i = 0; $i < 8; $i++ ) {
    Svc_Rewards::earn( (int) $cust2['id'], 'review', [ 'dedupe_key' => 'seed_rev_' . $i ] );
}

Svc_Rewards::recalc_tier( (int) $cust1['id'] );
Svc_Rewards::recalc_tier( (int) $cust2['id'] );
Svc_Rewards::recalc_tier( (int) $tech['id'] );
Svc_Rewards::recalc_tier( (int) $supplier['id'] );

$cust1 = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$pre}svc_reward_accounts WHERE id=%d", (int) $cust1['id'] ), ARRAY_A );
$cust2 = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$pre}svc_reward_accounts WHERE id=%d", (int) $cust2['id'] ), ARRAY_A );
$tech = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$pre}svc_reward_accounts WHERE id=%d", (int) $tech['id'] ), ARRAY_A );
$supplier = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$pre}svc_reward_accounts WHERE id=%d", (int) $supplier['id'] ), ARRAY_A );

echo json_encode( [
    'success' => true,
    'earned_events' => $earned,
    'demo_accounts' => [
        'customer_1' => [
            'phone' => '09121234567',
            'name' => $cust1['display_name'] ?? '',
            'referral_code' => $cust1['referral_code'] ?? '',
            'tier' => $cust1['tier'] ?? '',
            'points' => (int) ( $cust1['points_available'] ?? 0 ),
            'login' => 'ورود با موبایل در service.php',
        ],
        'customer_2' => [
            'phone' => '09129876543',
            'referral_code' => $cust2['referral_code'] ?? '',
            'tier' => $cust2['tier'] ?? '',
            'points' => (int) ( $cust2['points_available'] ?? 0 ),
        ],
        'technician' => [
            'login' => 'svc_tech1_demo',
            'password' => 'Demo@2026',
            'tier' => $tech['tier'] ?? '',
            'points' => (int) ( $tech['points_available'] ?? 0 ),
        ],
        'supplier' => [
            'login' => 'svc_supplier_demo',
            'password' => 'SvcReward@1404',
            'tier' => $supplier['tier'] ?? '',
            'points' => (int) ( $supplier['points_available'] ?? 0 ),
        ],
    ],
    'portal_url' => '/acc-engine/service.php',
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT );
