<?php
/**
 * TRRC REST API endpoint for menu tree
 */
if (!defined('ABSPATH')) {
    exit;
}

error_log('*** TRRC REST API file IS LOADED! ***'); // این خط را اضافه کنید

add_action('rest_api_init', function () {
    register_rest_route('acc/v1', '/trrc/tree', [
        'methods'  => 'GET',
        'callback' => 'acc_trrc_get_menu_tree',
        'permission_callback' => 'acc_jwt_check_permission',

    ]);

    register_rest_route('acc/v1', '/trrc/test-tree', [ // آدرس را عوض کردیم به test-tree
        'methods'  => 'GET',
        'callback' => 'acc_trrc_get_menu_tree',
        'permission_callback' => 'acc_jwt_check_permission',
    ]);
});

/**
 * ساخت درخت منو برای کاربر جاری
 */
function acc_trrc_get_menu_tree(WP_REST_Request $request)
{
    global $wpdb;

    // ✅ گرفتن userId از Query String
    $user_id_param = $request->get_param('userId');

    // ✅ تعیین user فعال
    if (!empty($user_id_param)) {
        $user_id = (int) $user_id_param;
    } else {
        $user_id = get_current_user_id();
    }

    error_log('[TRRC DEBUG] Using user_id = ' . $user_id);

    // ✅ Query صحیح
    $query = $wpdb->prepare("
        SELECT m.*
        FROM {$wpdb->prefix}accj_menus m
        INNER JOIN {$wpdb->prefix}accj_menu_permissions p ON p.menu_id = m.id
        INNER JOIN {$wpdb->prefix}accj_user_roles ur ON ur.role_id = p.role_id
        WHERE ur.user_id = %d
          AND p.can_view = 1
        ORDER BY m.menu_order ASC
    ", $user_id);

    error_log('[TRRC DEBUG] SQL = ' . $query);

    $rows = $wpdb->get_results($query);

    error_log('[TRRC DEBUG] Rows Found = ' . count($rows));

    if (empty($rows)) {
        return new WP_REST_Response([
            'id' => 'root',
            'name' => 'Root',
            'children' => []
        ], 200);
    }

    // ساخت درخت
    $items = [];
    foreach ($rows as $row) {
        $items[$row->id] = [
            'id'        => (int) $row->id,
            'name'      => $row->title ?? 'Unnamed',
            'icon'      => $row->icon ?? null,
            'route'     => $row->route ?? null,
            'module'    => $row->module ?? null,
            'view_file' => $row->view_file ?? null,
            'menu_order'=> (int) ($row->menu_order ?? 0),
            'parent_id' => $row->parent_id !== null ? (int) $row->parent_id : null,
            'children'  => [],
        ];
    }

    $tree = [];
    foreach ($items as &$node) {
        if ($node['parent_id'] && isset($items[$node['parent_id']])) {
            $items[$node['parent_id']]['children'][] = &$node;
        } else {
            $tree[] = &$node;
        }
    }
    unset($node);

    return new WP_REST_Response([
        'id'       => 'root',
        'name'     => 'Root',
        'children' => $tree,
    ], 200);
}

