<?php
/**
 * به‌روزرسانی joined_at و added_by برای پرونده‌های دمو (بدون reset)
 * php run-melk-enrich-participants.php
 */
declare(strict_types=1);

define('ACC_BASE_PATH', __DIR__);
require __DIR__ . '/standalone/bootstrap.php';

header('Content-Type: application/json; charset=utf-8');
global $wpdb;
$pre = $wpdb->prefix;

$GLOBALS['_melk_install_quiet'] = true;
ob_start();
include __DIR__ . '/run-melk-install.php';
ob_end_clean();

$logins = [
    'lead_d1'  => 'melk_lead_d1',
    'legal'    => 'melk_legal',
    'shahr'    => 'melk_shahrdari',
    'registry' => 'melk_registry',
    'mgr_n007' => 'melk_mgr_007',
    'coord'    => 'melk_coord',
    'lead_d2'  => 'melk_lead_d2',
    'mgr_n006' => 'melk_mgr_006',
];
$uids = [];
foreach ( $logins as $key => $login ) {
    $uids[$key] = (int) $wpdb->get_var( $wpdb->prepare(
        "SELECT ID FROM {$wpdb->users} WHERE user_login = %s", $login
    ) );
}

function melk_name( int $uid ): string {
    global $wpdb;
    return (string) $wpdb->get_var( $wpdb->prepare(
        "SELECT display_name FROM {$wpdb->users} WHERE ID = %d", $uid
    ) );
}

$case_id = (int) $wpdb->get_var(
    "SELECT id FROM {$pre}melk_cases WHERE case_key = 'MK-DEMO-02' LIMIT 1"
);
if ( ! $case_id ) {
    echo json_encode( ['success' => false, 'message' => 'MK-DEMO-02 not found'], JSON_UNESCAPED_UNICODE );
    exit;
}

$base = strtotime( '-10 days' );
$rows = [
    [$uids['lead_d1'], 'agent', null, date( 'Y-m-d H:i:s', $base )],
    [$uids['legal'], 'legal', $uids['lead_d1'], date( 'Y-m-d H:i:s', $base + 86400 )],
    [$uids['shahr'], 'municipality', $uids['lead_d1'], date( 'Y-m-d H:i:s', $base + 90000 )],
    [$uids['registry'], 'registry', $uids['lead_d1'], date( 'Y-m-d H:i:s', $base + 172800 )],
    [$uids['mgr_n007'], 'agent', $uids['lead_d1'], date( 'Y-m-d H:i:s', $base + 259200 )],
];

$updated = 0;
foreach ( $rows as [$uid, $role, $added_by, $joined_at] ) {
    if ( ! $uid ) continue;
    $data = [
        'role_type'     => $role,
        'user_name'     => melk_name( $uid ),
        'joined_at'     => $joined_at,
        'added_by'      => $added_by ?: null,
        'added_by_name' => $added_by ? melk_name( $added_by ) : null,
    ];
    $exists = (int) $wpdb->get_var( $wpdb->prepare(
        "SELECT id FROM {$pre}melk_case_participants WHERE case_id = %d AND user_id = %d",
        $case_id, $uid
    ) );
    if ( $exists ) {
        $wpdb->update( "{$pre}melk_case_participants", $data, ['id' => $exists] );
    } else {
        $wpdb->insert( "{$pre}melk_case_participants", array_merge( $data, [
            'case_id' => $case_id,
            'user_id' => $uid,
        ] ) );
    }
    $updated++;
}

require_once ACC_PATH . 'includes/controllers/Eqtesad_Melk_Controller.php';
$req = new WP_REST_Request( 'GET', '/acc/v1/melk/cases/' . $case_id );
$req->set_param( 'id', $case_id );

// mock logged in user as lead
if ( ! is_user_logged_in() && $uids['lead_d1'] ) {
    wp_set_current_user( $uids['lead_d1'] );
}

$res = Eqtesad_Melk_Controller::get_case( $req );
$body = $res->get_data();
$data = $body['data'] ?? [];

echo json_encode( [
    'success'   => true,
    'case_id'   => $case_id,
    'updated'   => $updated,
    'participants' => array_map( static function ( $p ) {
        return [
            'name' => $p['display_name'] ?? $p['user_name'],
            'login' => $p['user_login'] ?? '',
            'join_label' => $p['join_label'] ?? '',
            'joined_at' => $p['joined_at'] ?? '',
            'note_count' => $p['note_count'] ?? 0,
        ];
    }, $data['participants'] ?? [] ),
    'timeline_count' => count( $data['activity_timeline'] ?? [] ),
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT );
