<?php
/*
|--------------------------------------------------------------------------
| open_service_portal.php
| Generates a fresh signed SSO token for the logged-in Seven user and
| redirects them into the Service Portal (admin or staff dashboard).
| Building the token at click-time avoids stale/expired links.
|--------------------------------------------------------------------------
*/
ob_start(); // buffer output so the redirect header always works, even if an included file emits whitespace
session_start();
require_once '../config/database.php';
require_once '../config/sso_config.php';

$debug = isset($_GET['debug']);

if (!isset($_SESSION['user_id'])) {
    if ($debug) { exit('DEBUG: not logged in (no $_SESSION[user_id]).'); }
    header('Location: ../auth/login.php');
    exit;
}

$companyId = (int)($_SESSION['company_id'] ?? 0);
$role      = (($_GET['role'] ?? '') === 'admin') ? 'admin' : 'staff';

// Find this user's staff_code (the S0xx code) for the current company
$code   = '';
$dbgErr = '';
try {
    $st = $pdo->prepare("SELECT staff_code FROM company_staff WHERE user_id = ? AND company_id = ? LIMIT 1");
    $st->execute([(int)$_SESSION['user_id'], $companyId]);
    $code = (string)($st->fetchColumn() ?: '');
} catch (Throwable $e) {
    $dbgErr = $e->getMessage();
    $code   = '';
}

if ($debug) {
    header('Content-Type: text/plain');
    echo "DEBUG open_service_portal\n";
    echo "user_id     = " . ($_SESSION['user_id'] ?? '(none)') . "\n";
    echo "company_id  = " . $companyId . "\n";
    echo "role        = " . $role . "\n";
    echo "staff_code  = " . ($code === '' ? '(EMPTY - not found in company_staff)' : $code) . "\n";
    echo "db error    = " . ($dbgErr ?: '(none)') . "\n";
    echo "secret set  = " . (defined('SSO_SHARED_SECRET') ? 'yes (' . strlen(SSO_SHARED_SECRET) . ' chars)' : 'NO') . "\n";
    echo "func exists = " . (function_exists('sso_service_portal_link') ? 'yes' : 'NO') . "\n";
    if ($code !== '' && function_exists('sso_service_portal_link')) {
        echo "SSO url     = " . sso_service_portal_link($role, $code) . "\n";
    }
    exit;
}

if ($code === '') {
    http_response_code(400);
    echo 'Your account has no staff code yet, so it cannot be linked to the Service Portal. '
       . 'Please set a Staff Code for your profile first.';
    exit;
}

header('Location: ' . sso_service_portal_link($role, $code));
exit;