<?php
/**
 * نصب + تست بهای تمام‌شده فعالیت فروشگاه
 * php run-arag-abc-test.php
 */
declare(strict_types=1);

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

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

global $wpdb;
Arag_Activity_Cost::ensure_tables();

$order = $wpdb->get_row(
    "SELECT * FROM {$wpdb->prefix}arag_orders WHERE payment_status IN ('paid','cod','pending') ORDER BY id DESC LIMIT 1",
    ARRAY_A
);

if (!$order) {
    echo json_encode(['ok' => false, 'error' => 'سفارشی نیست — ابتدا خرید تست بزنید'], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    exit(1);
}

$order['items'] = json_decode($order['items_json'] ?? '[]', true) ?: [];
$alloc = Arag_Activity_Cost::allocate($order);
Arag_Activity_Cost::persist((int) $order['id'], $alloc);
$graph = Arag_Activity_Cost::cost_graph(['order_id' => (int) $order['id']]);

echo json_encode([
    'ok' => true,
    'order_id' => (int) $order['id'],
    'order_number' => $order['order_number'] ?? 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_shop' => 'http://localhost/acc-engine/shop.php',
    'ui_acct' => 'http://localhost/acc-engine/shop-accounting.php → تب گراف فعالیت',
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
