<?php
/**
 * Data collection routing: desktop (/collect) vs mobile (/mobile).
 */

require_once __DIR__ . '/device-check.php';

/**
 * Home route segment for the current device (data collectors).
 */
function nazareth_data_collector_home_route(): string
{
    return isMobileOrTablet() ? 'mobile' : 'collect';
}

/**
 * URL path prefix for member CRUD in this UI (collect or members).
 */
function nazareth_members_route(string $path = ''): string
{
    $base = defined('NAZARETH_MEMBERS_ROUTE') ? NAZARETH_MEMBERS_ROUTE : 'members';
    if ($path === '') {
        return nazareth_url($base);
    }
    return nazareth_url($base . '/' . ltrim($path, '/'));
}

/**
 * Redirect data collectors between /collect and /mobile based on device.
 */
function nazareth_apply_data_collector_device_routing(string $page, ?string $action, ?int $routeId): void
{
    if (empty($_SESSION['user_id']) || ($_SESSION['role'] ?? '') !== 'data_collector') {
        return;
    }

    if (isMobileOrTablet()) {
        if ($page === 'collect') {
            if ($action === 'new') {
                nazareth_redirect('mobile/new');
            } elseif ($action === 'edit' && $routeId > 0) {
                nazareth_redirect('mobile/edit/' . $routeId);
            } elseif ($action === 'view' && $routeId > 0) {
                nazareth_redirect('mobile/view/' . $routeId);
            } else {
                nazareth_redirect('mobile');
            }
        }
        return;
    }

    if ($page !== 'mobile') {
        return;
    }

    if (in_array($action, ['login', 'forgot-password', 'change-password', 'establish'], true)) {
        return;
    }

    if ($action === 'new') {
        nazareth_redirect('collect/new');
    } elseif ($action === 'edit' && $routeId > 0) {
        nazareth_redirect('collect/edit/' . $routeId);
    } elseif ($action === 'view' && $routeId > 0) {
        nazareth_redirect('collect/view/' . $routeId);
    } elseif ($action === null || $action === '') {
        nazareth_redirect('collect');
    }
}
