<?php
// includes/post_login_router.php
@session_start();
require_once __DIR__.'/device.php';

function post_login_redirect(): void {
    $auth = $_SESSION['auth'] ?? null;
    if (!$auth || !is_array($auth)) {
        header('Location: /mobile/login.php'); exit;
    }

    $source   = strtolower(trim((string)($auth['source'] ?? '')));
    $roleName = strtolower(trim((string)($auth['role_name'] ?? '')));
    $isMobile = is_mobile_ua();

    // Broker routes
    if ($source === 'broker' || $roleName === 'broker') {
        if ($isMobile) {
            header('Location: /mobile/crm_mobile.php');
        } else {
            header('Location: /mobile/crm_mobile.php');
        }
        exit;
    }

    // Employee / DST routes
    if ($source === 'employee' || in_array($roleName, ['employee','dst','sales','telecaller'], true)) {
        if ($isMobile) {
            header('Location: /mobile/dst.php');
        } else {
            header('Location: /mobile/dst.php');
        }
        exit;
    }

    // Fallback (AMS)
    header('Location: /mobile/ams/user/dashboard.php');
    exit;
}
