<?php
/**
 * نصب + تست بهای تمام‌شده فعالیت اقتصاد ملک
 * C:\xampp\php\php.exe run-melk-abc-test.php
 */
declare(strict_types=1);

define('ACC_BASE_PATH', __DIR__);
require __DIR__ . '/standalone/bootstrap.php';
require_once ACC_PATH . 'includes/helpers/melk-activity-cost.php';

header('Content-Type: application/json; charset=utf-8');

global $wpdb;
Melk_Activity_Cost::ensure_tables();

$project = $wpdb->get_row(
    "SELECT * FROM {$wpdb->prefix}melk_construction_projects ORDER BY id DESC LIMIT 1",
    ARRAY_A
);

if (!$project) {
    /* پروژه دمو برای تست */
    $key = 'MLK-ABC-' . date('ymdHis');
    $wpdb->insert("{$wpdb->prefix}melk_construction_projects", [
        'project_key' => $key,
        'title' => 'پروژه آزمایشی ABC — زرهی شیراز',
        'project_type' => 'partnership',
        'status' => 'active',
        'budget' => 120000000000,
        'area_sqm' => 2200,
        'floors' => 7,
        'description' => 'پروژه تست گراف هزینه مشارکت',
        'created_by' => 1,
        'created_by_name' => 'ABC Test',
    ]);
    $pid = (int) $wpdb->insert_id;
    if ($pid) {
        foreach ([
            ['user_id' => 1, 'role_type' => 'owner', 'share_percent' => 35],
            ['user_id' => 1, 'role_type' => 'contractor', 'share_percent' => 40],
            ['user_id' => 1, 'role_type' => 'investor', 'share_percent' => 20],
            ['user_id' => 1, 'role_type' => 'supervisor', 'share_percent' => 5],
        ] as $pt) {
            /* UNIQUE (project_id, user_id) — فقط یک ردیف؛ crew از نقش‌های استنباطی استفاده می‌کند */
        }
        $wpdb->replace("{$wpdb->prefix}melk_construction_participants", [
            'project_id' => $pid,
            'user_id' => 1,
            'role_type' => 'owner',
            'share_percent' => 35,
            'status' => 'active',
            'added_by' => 1,
        ]);
        $project = Melk_Activity_Cost::get_project($pid);
    }
}

if (!$project) {
    echo json_encode(['ok' => false, 'error' => 'پروژه ساخت یافت نشد'], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    exit(1);
}

$alloc = Melk_Activity_Cost::allocate($project);
Melk_Activity_Cost::persist((int) $project['id'], $alloc);
$graph = Melk_Activity_Cost::cost_graph(['project_id' => (int) $project['id']]);

echo json_encode([
    'ok' => true,
    'project_id' => (int) $project['id'],
    'project_key' => $project['project_key'] ?? null,
    'title' => $project['title'] ?? null,
    'pools' => $alloc['pools'],
    'person_shares' => $alloc['person_shares'],
    'lines_count' => count($alloc['lines']),
    'totals' => $alloc['totals'],
    'graph' => [
        'nodes' => count($graph['nodes']),
        'edges' => count($graph['edges']),
        'types' => array_count_values(array_column($graph['nodes'], 'type')),
    ],
    'ui' => 'http://localhost/acc-engine/melk.php → ورود → تب حسابداری مشارکت',
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
