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

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

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

global $wpdb;
Svc_Activity_Cost::ensure_tables();

$report = $wpdb->get_row(
    "SELECT * FROM {$wpdb->prefix}svc_reports WHERE status = 'final' ORDER BY id DESC LIMIT 1",
    ARRAY_A
);

if (!$report) {
    /* ساخت گزارش آزمایشی حداقلی اگر جدول reports خالی است */
    $req_id = (int) $wpdb->get_var("SELECT id FROM {$wpdb->prefix}svc_requests ORDER BY id DESC LIMIT 1");
    if (!$req_id) {
        echo json_encode(['ok' => false, 'error' => 'هیچ درخواست/گزارشی نیست — ابتدا دمو سرویس را seed کنید'], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
        exit(1);
    }
    $tech = (int) $wpdb->get_var($wpdb->prepare(
        "SELECT assigned_technician_id FROM {$wpdb->prefix}svc_requests WHERE id=%d", $req_id
    ));
    $wpdb->insert("{$wpdb->prefix}svc_reports", [
        'request_id' => $req_id,
        'tracking_code' => 'ABC-TEST-' . time(),
        'status' => 'final',
        'customer_name' => 'مشتری تست ABC',
        'phone' => '09120000000',
        'technician_id' => $tech ?: null,
        'subtotal_services' => 5000000,
        'subtotal_parts' => 2000000,
        'subtotal_materials' => 0,
        'subtotal_extra' => 0,
        'discount' => 200000,
        'tax' => 0,
        'total' => 6800000,
        'finalized_at' => current_time('mysql'),
    ]);
    $report = $wpdb->get_row($wpdb->prepare(
        "SELECT * FROM {$wpdb->prefix}svc_reports WHERE id = %d", (int) $wpdb->insert_id
    ), ARRAY_A);
}

$request_id = (int) $report['request_id'];
$tech_id = (int) ($report['technician_id'] ?? 0);
if (!$tech_id) {
    $tech_id = (int) $wpdb->get_var($wpdb->prepare(
        "SELECT assigned_technician_id FROM {$wpdb->prefix}svc_requests WHERE id=%d", $request_id
    ));
}

/* خدمه دونفره آزمایشی */
$assistant = (int) $wpdb->get_var(
    "SELECT ID FROM {$wpdb->users} WHERE ID <> {$tech_id} ORDER BY ID DESC LIMIT 1"
);
$crew = [];
if ($tech_id) {
    $crew[] = ['user_id' => $tech_id, 'role' => 'lead', 'weight' => 1.5, 'hours' => 5, 'note' => 'مسئول'];
}
if ($assistant) {
    $crew[] = ['user_id' => $assistant, 'role' => 'assistant', 'weight' => 1, 'hours' => 3, 'note' => 'کمک'];
}
if ($crew) {
    Svc_Activity_Cost::save_crew($request_id, $crew, (int) $report['id']);
}

$splits = Svc_Accounting::calculate_splits($report);
$alloc  = Svc_Activity_Cost::allocate($report, $splits);
Svc_Activity_Cost::persist_allocation((int) $report['id'], $alloc);
$graph  = Svc_Activity_Cost::cost_graph(['report_id' => (int) $report['id']]);

echo json_encode([
    'ok' => true,
    'report_id' => (int) $report['id'],
    'request_id' => $request_id,
    'tracking' => $report['tracking_code'] ?? null,
    'pools' => $alloc['pools'],
    'person_shares' => $alloc['person_shares'],
    'lines_count' => count($alloc['lines']),
    'sample_lines' => array_slice($alloc['lines'], 0, 6),
    'graph' => [
        'nodes' => count($graph['nodes']),
        'edges' => count($graph['edges']),
        'node_types' => array_count_values(array_column($graph['nodes'], 'type')),
    ],
    'ui' => 'service.php → ورود حسابدار/مدیر → عملیات → صدور سند → تب «گراف فعالیت»',
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
