<!-- <html><head>
  <link rel="stylesheet" href="styles.css">
</head>
<body>
<?php
// session_start();
// $sessionid=session_id();
// require_once("constants.php");
// echo "<h2>SAML Session</h2>";
// echo "<table>";
// echo "<tr>";
// echo "<td>PHP Session ID</td>";
// echo "<td>".$sessionid."</td>";
// echo "<tr>";
// echo "</tr>";
// echo "<td>SAML Session index</td>";
// echo "<td>".$_SESSION['samlSessionIndex']."</td>";
// echo "</tr>";
// echo "</table>";

// // check if already logged in
// if (isset($_SESSION['samlUserdata'])) {
//     if (!empty($_SESSION['samlUserdata'])) {
//         // get user related data
//         $attributes = $_SESSION['samlUserdata'];
//         echo "<h2>SAML User Data</h2>";
//         echo "<table>";

//         foreach ($attributes as $attributeName => $attributeValues) {
//             echo '<tr>';
//             echo "<td>".htmlentities($attributeName)."</td>";
//             foreach ($attributeValues as $attributeValue) {
//                 echo '<td>'.htmlentities($attributeValue)."</td>";
//             }
//             echo "</tr>";
//         }
//         echo "</table>";
//     }

//     echo "<h2>SAML NameId related</h2>";
//     echo "<table>";
//     if (!empty($_SESSION['samlNameId'])) {
//         echo "<tr>";
//         echo "<td>NameId</td>";
//         echo "<td>".htmlentities($_SESSION['samlNameId'])."</td>";
//         echo "</tr>";
//     }
//     if (!empty($_SESSION['samlNameIdFormat'])) {
//         echo "<tr>";
//         echo "<td>samlNameIdFormat</td>";
//         echo "<td>".htmlentities($_SESSION['samlNameIdFormat'])."</td>";
//         echo "</tr>";
//     }
//     if (!empty($_SESSION['samlNameIdNameQualifier'])) {
//         echo "<tr>";
//         echo "<td>samlNameIdNameQualifier</td>";
//         echo "<td>".htmlentities($_SESSION['samlNameIdNameQualifier'])."</td>";
//         echo "</tr>";
//     }
//     if (!empty($_SESSION['samlNameIdSPNameQualifier'])) {
//         echo "<tr>";
//         echo "<td>samlNameIdSPNameQualifier</td>";
//         echo "<td>".htmlentities($_SESSION['samlNameIdSPNameQualifier'])."</td>";
//         echo "</tr>";
//     }
//     echo "</table>";

//     if (!empty($_SESSION['emp_id'])) {
//         echo "<h2>OTHERS</h2>";
//         echo "<table>";
//         echo "<tr>";
//         echo "<td>emp_id</td>";
//         echo "<td>".htmlentities($_SESSION['emp_id'])."</td>";
//         echo "</tr>";
//         echo "</table>";
//     }
// 	echo '<p><a href="info.php" target="_blank">PHP Info</a></p>';
//     echo '<p><a href="slo.php" >Logout</a></p>';
// }
// else {
//     header('location:'.constants::INDEX_SSO_PAGE);
// }


// // #region  //  sso auth process

// // #region // sso auth data
// // getting data from sso using saml assertion method

// $_REQUEST['agent'] = $_SERVER['HTTP_USER_AGENT'];
// $_REQUEST['width'] = $_SESSION['browser_width'];
// $_REQUEST['height'] = $_SESSION['browser_height'];

// $attr = $_SESSION['samlUserdata'];
// $user_principalName = htmlentities($attr['userPrincipalName'][0]);
// $user_samAccName = htmlentities($attr['samAccountName'][0]);


// if (isset($attr['mailldap'][0])) {

// 	$user_email = htmlentities($attr['mailldap'][0]);

// }

// if (isset($attr['mail'][0])) {

// 	$user_email = htmlentities($attr['mail'][0]);

// }

// // #endregion // sso auth data

// $user = User::where('u_email', $user_email)->first();
//     if ($user) {
//         Auth::login($user);
//         //dd(Auth::check(), Auth::user(), url()->previous());
//         //$request->session()->regenerate();
//         return redirect()->route('dashboard-analytics')->with('success', 'Welcome back, ' . $user->u_name . '!');
//     }

//     return back()->withErrors(['Invalid username or password.']);



// #endregion  // sso auth process


?>
</body></html> -->
<?php
/**
 * SSO Bridge (Standalone) — index.php
 *
 * Place either at:
 *   - public/sso/index.php      (keep ../../ paths)
 *   - /sso/index.php (project)  (change ../../ -> ../)
 */

// ---------------------------
// (A) Start session for SAML
// ---------------------------
session_start();

// --------------------------------------------------
// (B) Bootstrap Laravel via Console Kernel (providers)
// --------------------------------------------------
require __DIR__ . '/../../vendor/autoload.php';       // adjust to ../ if at project-root /sso/index.php
$app = require __DIR__ . '/../../bootstrap/app.php';  // adjust to ../ if at project-root /sso/index.php

// Boot providers (DB/Eloquent, Facades, URL generator, etc.)
$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();

// Imports AFTER Composer autoload
use App\Models\User;
use Illuminate\Support\Facades\Auth;

// ------------------------------------------
// (C) Load constants/config used by this file
// ------------------------------------------
require_once __DIR__ . '/constants.php';

// ------------------------
// (D) Helpers & Parameters
// ------------------------
$isDebug = isset($_GET['debug']) && $_GET['debug'] == '1';
$isMock  = isset($_GET['mock'])  && $_GET['mock']  == '1';

// Optionally simulate SAML attributes via ?mock=1
if ($isMock) {
    $_SESSION['samlSessionIndex'] = 'SIMULATED-INDEX-123';
    $_SESSION['samlUserdata'] = [
        'userPrincipalName' => ['tester@domain.local'],
        'samAccountName'    => ['tester'],
        // Prefer mailldap if present, else mail
        'mail'              => ['test@example.com'],
        // 'mailldap'        => ['test@example.com'],
        'displayName'       => ['Tester User'],
        'cn'                => ['Tester User CN'],
    ];
}

// If you store browser size in session elsewhere, show it here safely
$_REQUEST['agent']  = $_SERVER['HTTP_USER_AGENT']     ?? '';
$_REQUEST['width']  = $_SESSION['browser_width']      ?? '';
$_REQUEST['height'] = $_SESSION['browser_height']     ?? '';

// ---------------------------------------------
// (E) Extract SAML attributes we care about
// ---------------------------------------------
$attr               = $_SESSION['samlUserdata'] ?? [];
$user_principalName = isset($attr['userPrincipalName'][0]) ? htmlentities($attr['userPrincipalName'][0]) : null;
$user_samAccName    = isset($attr['samAccountName'][0])    ? htmlentities($attr['samAccountName'][0])    : null;

// Email selection priority: mailldap > mail
$user_email = null;
if (isset($attr['mailldap'][0])) {
    $user_email = htmlentities($attr['mailldap'][0]);
}
if (isset($attr['mail'][0])) {
    $user_email = htmlentities($attr['mail'][0]);
}

// If NO SAML data at all, bounce to SSO start page (INDEX_SSO_PAGE)
if (empty($attr)) {
    header('Location: ' . \constants::INDEX_SSO_PAGE);
    exit;
}

// If we DO have SAML but no email, show an error (or redirect)
if (!$user_email) {
    if (!$isDebug) {
        // No email; can’t proceed — return to SSO start
        header('Location: ' . \constants::INDEX_SSO_PAGE);
        exit;
    }
    // In debug mode, we continue to render the table + show the error below
}

// ---------------------------------------------
// (F) Attempt Laravel login if we have an email
// ---------------------------------------------
if ($user_email) {
    // Find user by your schema column
    //dd('masuk if ' ,$user_email);
    $user = User::where('u_email', $user_email)->first();

    if ($user) {
      //dd('masuk if 2' ,$user);
        Auth::login($user);

        // Build target URL via URL generator (works outside HTTP kernel)
        // IMPORTANT: Ensure APP_URL is set in .env, and route name exists.
        $target = null;
        try {
          //dd('masuk try' ,$user);
            $target = app('url')->route('dashboard-analytics');
        } catch (Throwable $e) {
          //dd('masuk catch' ,$user);
            // Fallback to a path if named route isn't available here
            //$target = app('url')->to('/dashboard-analytics');
            echo '<p class="error">Missing email in SSO attributes (mailldap/mail).</p>';
        }

        // If not in debug mode, redirect immediately
        if (!$isDebug) {
          // dd('masuk debug' ,$user);
            header('Location: ' . $target);
            exit;
        }
        // In debug mode, we’ll render debug tables below and show the target URL.
    } else {
      //dd('masuk else ' ,$user_email);
      echo '<p class="error">Invalid user in SSO attributes (mailldap/mail): No matching user in DB for <strong>' . htmlentities($user_email) . '</strong>.</p>';
        // User not found. In a pure-SSO flow you might auto-create the user instead.
        // For safety, we’ll just drop to the debug view and show “Invalid user”.
    }
}

// -----------------------------
// (G) Render Debug/Info Page
// -----------------------------
// Only HTML output now (to avoid “headers already sent” before redirects)
?>
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>SSO Session Debug</title>
  <link rel="stylesheet" href="styles.css">
  <style>
    body { font-family: system-ui, -apple-system, Segoe UI, Roboto, Arial, sans-serif; padding: 16px; }
    table { border-collapse: collapse; margin: 8px 0 24px; width: 100%; max-width: 900px; }
    td, th { border: 1px solid #ccc; padding: 8px 10px; vertical-align: top; }
    h2 { margin: 24px 0 8px; }
    .note { background: #f6f8fa; border:1px solid #e1e4e8; padding:10px 12px; border-radius:6px; margin-bottom:12px; }
    .error { color: #b00020; font-weight: 600; }
    .ok { color: #1b5e20; font-weight: 600; }
    .links a { margin-right: 12px; }
  </style>
</head>
<body>

<?php if ($isDebug): ?>
  <div class="note"><strong>DEBUG MODE:</strong> This page appears because you opened with <code>?debug=1</code>.
  Without <code>?debug=1</code>, this file redirects to <code>dashboard-analytics</code> after SSO.</div>
<?php endif; ?>

<?php if ($isMock): ?>
  <div class="note"><strong>MOCK ENABLED:</strong> Dummy SAML data injected via <code>?mock=1</code>.</div>
<?php endif; ?>

<h2>SAML Session</h2>
<table>
  <tr><td>PHP Session ID</td><td><?= session_id() ?></td></tr>
  <tr><td>SAML Session index</td><td><?= htmlentities($_SESSION['samlSessionIndex'] ?? '') ?></td></tr>
  <tr><td>Agent</td><td><?= htmlentities($_REQUEST['agent'] ?? '') ?></td></tr>
  <tr><td>Width</td><td><?= htmlentities($_REQUEST['width'] ?? '') ?></td></tr>
  <tr><td>Height</td><td><?= htmlentities($_REQUEST['height'] ?? '') ?></td></tr>
</table>

<h2>SAML User Data</h2>
<table>
  <?php if (!empty($attr)): ?>
    <?php foreach ($attr as $attributeName => $attributeValues): ?>
      <tr>
        <td><?= htmlentities($attributeName) ?></td>
        <td>
          <?php
            if (is_array($attributeValues)) {
                echo implode(', ', array_map('htmlentities', $attributeValues));
            } else {
                echo htmlentities((string)$attributeValues);
            }
          ?>
        </td>
      </tr>
    <?php endforeach; ?>
  <?php else: ?>
    <tr><td colspan="2" class="error">No SAML attributes found in session.</td></tr>
  <?php endif; ?>
</table>

<h2>SAML NameId related</h2>
<table>
  <?php if (!empty($_SESSION['samlNameId'])): ?>
    <tr><td>NameId</td><td><?= htmlentities($_SESSION['samlNameId']) ?></td></tr>
  <?php endif; ?>
  <?php if (!empty($_SESSION['samlNameIdFormat'])): ?>
    <tr><td>samlNameIdFormat</td><td><?= htmlentities($_SESSION['samlNameIdFormat']) ?></td></tr>
  <?php endif; ?>
  <?php if (!empty($_SESSION['samlNameIdNameQualifier'])): ?>
    <tr><td>samlNameIdNameQualifier</td><td><?= htmlentities($_SESSION['samlNameIdNameQualifier']) ?></td></tr>
  <?php endif; ?>
  <?php if (!empty($_SESSION['samlNameIdSPNameQualifier'])): ?>
    <tr><td>samlNameIdSPNameQualifier</td><td><?= htmlentities($_SESSION['samlNameIdSPNameQualifier']) ?></td></tr>
  <?php endif; ?>
</table>

<?php if (!empty($_SESSION['emp_id'])): ?>
  <h2>OTHERS</h2>
  <table>
    <tr><td>emp_id</td><td><?= htmlentities($_SESSION['emp_id']) ?></td></tr>
  </table>
<?php endif; ?>

<div class="links">
  <p><a href="info.php" target="_blank">PHP Info</a>
     <a href="slo.php">Logout</a>
  </p>
</div>

<?php
// -------------------------------
// (H) Outcome / next step message
// -------------------------------
if (!$user_email) {
    echo '<p class="error">Missing email in SSO attributes (mailldap/mail).</p>';
} else {
    $exists = isset($user) && $user;
    if ($exists) {
        echo '<p class="ok">User found and (in non-debug mode) would be logged in & redirected.</p>';
        try {
            $target = app('url')->route('dashboard-analytics');
        } catch (Throwable $e) {
            $target = app('url')->to('/dashboard-analytics');
        }
        echo '<p>Target: <code>' . htmlentities($target) . '</code></p>';
    } else {
        echo '<p class="error">Invalid user: No matching user in DB for <strong>' . htmlentities($user_email) . '</strong>.</p>';
        echo '<p>Option: auto-create on-the-fly in SSO flow (via a Laravel controller endpoint) if desired.</p>';
    }
}
?>

</body>
</html>
