<?php
/**
 * Mobile data collection router (entry from index.php or direct /mobile/app.php).
 */
require_once __DIR__ . '/init.php';
if (!isset($route_action)) {
    $route_action = null;
}
if (!isset($route_id)) {
    $route_id = null;
}
require_once __DIR__ . '/bootstrap.php';

$sub = $route_action ?? null;
$mid = isset($route_id) ? (int)$route_id : null;

if ($sub === 'login') {
    require __DIR__ . '/login.php';
    exit;
}

if ($sub === 'forgot-password') {
    require __DIR__ . '/forgot-password.php';
    exit;
}

require_once __DIR__ . '/../includes/auth.php';

if ($sub === 'change-password') {
    require __DIR__ . '/change-password.php';
    exit;
}

if (empty($_SESSION['user_id'])) {
    $target = BASE_PATH . '/mobile';
    if ($sub === 'new') {
        $target = BASE_PATH . '/mobile/new';
    } elseif ($sub === 'edit' && $mid) {
        $target = BASE_PATH . '/mobile/edit/' . $mid;
    } elseif ($sub === 'view' && $mid) {
        $target = BASE_PATH . '/mobile/view/' . $mid;
    }
    header('Location: ' . BASE_PATH . '/mobile/login?next=' . urlencode($target));
    exit;
}

if (($_SESSION['role'] ?? '') !== 'data_collector') {
    header('Location: ' . BASE_PATH . '/dashboard');
    exit;
}

if (!empty($_SESSION['must_change_password'])) {
    header('Location: ' . BASE_PATH . '/mobile/change-password');
    exit;
}

if ($sub === 'establish') {
    $pwaEstablishRedirect = trim((string) ($_GET['next'] ?? ''));
    if ($pwaEstablishRedirect === '' || strpos($pwaEstablishRedirect, '//') !== false) {
        $pwaEstablishRedirect = BASE_PATH . '/mobile';
    } elseif (strncmp($pwaEstablishRedirect, BASE_PATH, strlen(BASE_PATH)) !== 0) {
        $pwaEstablishRedirect = BASE_PATH . '/mobile';
    }
    require __DIR__ . '/establish.php';
    exit;
}

if ($sub === 'new') {
    $id = null;
    $isEdit = false;
    require __DIR__ . '/form.php';
    exit;
}

if ($sub === 'edit' && $mid > 0) {
    $id = $mid;
    $isEdit = true;
    require __DIR__ . '/form.php';
    exit;
}

if ($sub === 'view' && $mid > 0) {
    $id = $mid;
    require __DIR__ . '/view.php';
    exit;
}

require __DIR__ . '/list.php';
