<?php

declare(strict_types=1);

require_once __DIR__ . '/connect.php';
require_once __DIR__ . '/config.php';

// Helpers
function h(string $v): string
{
  return htmlspecialchars($v, ENT_QUOTES, 'UTF-8');
}
function render404(string $message = 'Not Found'): void
{
  http_response_code(404);
  $msg = h($message);
?>
  <!doctype html>
  <html lang="en">

  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><?= h(APP_NAME) ?> | Profile Not Found</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="assets/styles.css">
    <link rel="icon" href="assets/favicon.png" type="image/jpeg">
  </head>

  <body>
    <main class="container">
      <header class="header">
        <img src="assets/logo.png" alt="Logo" class="logo" />
        <h1 class="title">Profile</h1>
        <p class="subtitle"><?= $msg ?></p>
      </header>
      <section class="card">
        <p>We could not find the requested profile. It may have been removed or the link is incorrect.</p>
        <div class="actions">
          <a class="btn btn-outline" href="index.php">Back to Registration</a>
        </div>
      </section>
    </main>
  </body>

  </html>
<?php
  exit;
}

// Validate and read ID
$id = $_GET['id'] ?? '';
$id = is_string($id) ? trim($id) : '';
if ($id === '' || !preg_match('/^[a-f0-9]{32}$/i', $id)) {
  render404('Invalid or missing profile ID.');
}

$record = null;

// Prefer DB when enabled
if (defined('ENABLE_DB') && ENABLE_DB) {
  try {
    $pdo = pdo();
    $stmt = $pdo->prepare('SELECT uuid, first_name, last_name, email, phone, scfhs_id, national_id, speciality, hospital, created_at FROM registrations WHERE uuid = :uuid LIMIT 1');
    $stmt->execute([':uuid' => $id]);
    $row = $stmt->fetch();
    if (is_array($row) && $row) {
      $record = $row;
    }
  } catch (Throwable $e) {
    // Fallback to file
  }
}

// File-based fallback
if (!$record) {
  $path = __DIR__ . '/storage/registrations/' . $id . '.json';
  if (is_readable($path)) {
    $json = json_decode((string)file_get_contents($path), true);
    if (is_array($json)) {
      $record = $json;
    }
  }
}

if (!$record) {
  render404('Profile not found.');
}

// Normalize fields and sanitize
$first = h((string)($record['first_name'] ?? ''));
$last = h((string)($record['last_name'] ?? ''));
$email = h((string)($record['email'] ?? ''));
$phone = h((string)($record['phone'] ?? ''));
$scfhs = h((string)($record['scfhs_id'] ?? ''));
$national = h((string)($record['national_id'] ?? ''));
$spec = h((string)($record['speciality'] ?? ''));
$hosp = h((string)($record['hospital'] ?? ''));
$created = h((string)($record['created_at'] ?? ''));
$uuid = h((string)($record['uuid'] ?? $id));
// Display name
$name = trim($first . ' ' . $last);

?>
<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title><?= h(APP_NAME) ?> | Profile</title>
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="assets/styles.css">
  <link rel="icon" href="assets/favicon.png" type="image/jpeg">
  <style>
    .details {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 16px;
      max-width: 100%;
    }

    .details .row {
      display: flex;
      flex-direction: column;
      gap: 6px;
      padding: 12px;
      border: 1px solid var(--border);
      border-radius: 12px;
      min-width: 0;
      /* allow grid children to shrink to container */
    }

    .label {
      font-weight: 600;
      color: var(--muted)
    }

    .value {
      font-weight: 600;
      overflow-wrap: anywhere;
      /* wrap long emails/IDs */
      word-break: break-word;
      line-break: anywhere;
    }

    @media (max-width:720px) {
      .details {
        grid-template-columns: 1fr;
      }

      .card {
        padding: 16px;
      }

      /* give a bit more room on small screens */
    }
  </style>
</head>

<body>
  <main class="container">
    <header class="header">
      <img src="assets/logo.png" alt="Logo" class="logo" />
      <h1 class="title">User Profile</h1>
      <!-- <p class="subtitle">Registration details</p> -->
    </header>

    <section class="card" aria-labelledby="profile-title">
      <h2 id="profile-title" class="sr-only">Profile details</h2>
      <div class="details">
        <div class="row"><span class="label">Name</span><span class="value"><?= $name !== '' ? $name : ($first ?: '—') ?></span></div>
        <div class="row"><span class="label">Email</span><span class="value"><?= $email ?></span></div>
        <div class="row"><span class="label">Phone</span><span class="value"><?= $phone ?></span></div>
        <div class="row"><span class="label">Created At</span><span class="value"><?= $created !== '' ? $created : '—' ?></span></div>

      </div>

      <div class="actions" style="margin-top:24px">
        <a class="btn btn-outline" href="index.php">Back to Registration</a>
      </div>
    </section>
  </main>
</body>

</html>