<?php
// verify.php
// Full verification page with UI
// Place this file in your cert/ folder

// ----- Configuration -----
$dbHost = 'localhost';
$dbUser = 'hmrsaasc_cert765';
$dbPass = 'hmrsaasc_cert765';
$dbName = 'hmrsaasc_cert765';

// Logo / sample image path provided by developer (will be converted to a URL in final deploy)
$logoUrl = '/mnt/data/Certificate.jpg'; // developer-provided local path (keeps the same as uploaded asset)

// ----- Connect -----
$mysqli = new mysqli($dbHost, $dbUser, $dbPass, $dbName);
if ($mysqli->connect_error) {
    http_response_code(500);
    echo "Database connection failed: " . htmlspecialchars($mysqli->connect_error);
    exit;
}

// ----- Get token from query string -----
$token = isset($_GET['token']) ? trim($_GET['token']) : '';

if ($token === '') {
    // Nice UI for missing token
    ?>
    <!doctype html>
    <html>
    <head>
      <meta charset="utf-8">
      <title>Certificate Verification</title>
      <style>
        body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial; background:#f6f8fb; margin:0; padding:30px; }
        .card { background:#fff; max-width:820px; margin:40px auto; padding:30px; border-radius:8px; box-shadow:0 6px 18px rgba(0,0,0,0.07); text-align:center; }
        h1 { margin:0 0 10px; font-size:22px; color:#222; }
        p { color:#555; }
        .hint { margin-top:18px; color:#777; }
      </style>
    </head>
    <body>
      <div class="card">
        <img src="<?php echo htmlspecialchars($logoUrl); ?>" alt="Logo" style="max-height:70px; margin-bottom:16px;">
        <h1>No token supplied</h1>
        <p>Please scan the QR code on the certificate or open the verification link that contains the token query parameter.</p>
        <p class="hint">Example: <code>?token=ABCD-1234-EFGH</code></p>
      </div>
    </body>
    </html>
    <?php
    exit;
}

// ----- Lookup token -----
$stmt = $mysqli->prepare("SELECT id, token_code, status, used_by, used_on FROM tokens WHERE token_code = ? LIMIT 1");
$stmt->bind_param('s', $token);
$stmt->execute();
$tokenResult = $stmt->get_result();

if (!$tokenResult || $tokenResult->num_rows === 0) {
    // Invalid token
    ?>
    <!doctype html>
    <html>
    <head>
      <meta charset="utf-8">
      <title>Certificate Verification</title>
      <meta name="viewport" content="width=device-width,initial-scale=1">
      <style>
        body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial; background:#f6f8fb; margin:0; padding:30px; }
        .card { background:#fff; max-width:820px; margin:40px auto; padding:30px; border-radius:8px; box-shadow:0 6px 18px rgba(0,0,0,0.07); text-align:center; }
        .invalid { color:#b62727; font-weight:700; font-size:20px; }
        img.logo { max-height:70px; margin-bottom:16px; }
      </style>
    </head>
    <body>
      <div class="card">
        <img src="<?php echo htmlspecialchars($logoUrl); ?>" alt="Logo" class="logo">
        <div class="invalid">❌ Invalid or Unknown Token</div>
        <p>The token provided does not exist in our system. Make sure you scanned the correct QR code or contact the issuer for assistance.</p>
      </div>
    </body>
    </html>
    <?php
    $stmt->close();
    $mysqli->close();
    exit;
}

$tokenRow = $tokenResult->fetch_assoc();
$stmt->close();

// ----- If token exists but not used yet, tell user certificate not generated -----
if ($tokenRow['status'] !== 'used') {
    // Token exists but not used -> no certificate generated yet
    ?>
    <!doctype html>
    <html>
    <head>
      <meta charset="utf-8">
      <title>Certificate Verification</title>
      <meta name="viewport" content="width=device-width,initial-scale=1">
      <style>
        body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial; background:#f6f8fb; margin:0; padding:30px; }
        .card { background:#fff; max-width:820px; margin:40px auto; padding:30px; border-radius:8px; box-shadow:0 6px 18px rgba(0,0,0,0.07); text-align:center; }
        .pending { color:#d98200; font-weight:700; font-size:20px; }
        img.logo { max-height:70px; margin-bottom:16px; }
      </style>
    </head>
    <body>
      <div class="card">
        <img src="<?php echo htmlspecialchars($logoUrl); ?>" alt="Logo" class="logo">
        <div class="pending">⏳ Token Not Redeemed Yet</div>
        <p>This token is valid but has not been used to generate a certificate yet.</p>
        <p>If you believe this is an error, please contact the issuer.</p>
      </div>
    </body>
    </html>
    <?php
    $mysqli->close();
    exit;
}

// ----- Token used: find intern record by used_by email -----
$usedByEmail = $tokenRow['used_by'] ?? '';

if (empty($usedByEmail)) {
    // Odd case: token marked used but no email recorded
    ?>
    <!doctype html>
    <html>
    <head>
      <meta charset="utf-8">
      <title>Certificate Verification</title>
      <meta name="viewport" content="width=device-width,initial-scale=1">
      <style>
        body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial; background:#f6f8fb; margin:0; padding:30px; }
        .card { background:#fff; max-width:820px; margin:40px auto; padding:30px; border-radius:8px; box-shadow:0 6px 18px rgba(0,0,0,0.07); text-align:center; }
        .invalid { color:#b62727; font-weight:700; font-size:20px; }
        img.logo { max-height:70px; margin-bottom:16px; }
      </style>
    </head>
    <body>
      <div class="card">
        <img src="<?php echo htmlspecialchars($logoUrl); ?>" alt="Logo" class="logo">
        <div class="invalid">❌ Token used but no user data found</div>
        <p>Please contact the certificate issuer and provide this token for support.</p>
      </div>
    </body>
    </html>
    <?php
    $mysqli->close();
    exit;
}

// Fetch intern record safely with prepared statement
$stmt2 = $mysqli->prepare("SELECT NAME, EMAIL, POST, START_DATE, END_DATE, PASSPORT FROM intern WHERE EMAIL = ? LIMIT 1");
$stmt2->bind_param('s', $usedByEmail);
$stmt2->execute();
$internResult = $stmt2->get_result();

if (!$internResult || $internResult->num_rows === 0) {
    // No intern record matching used_by email
    ?>
    <!doctype html>
    <html>
    <head>
      <meta charset="utf-8">
      <title>Certificate Verification</title>
      <meta name="viewport" content="width=device-width,initial-scale=1">
      <style>
        body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial; background:#f6f8fb; margin:0; padding:30px; }
        .card { background:#fff; max-width:820px; margin:40px auto; padding:30px; border-radius:8px; box-shadow:0 6px 18px rgba(0,0,0,0.07); text-align:center; }
        .invalid { color:#b62727; font-weight:700; font-size:20px; }
      </style>
    </head>
    <body>
      <div class="card">
        <img src="<?php echo htmlspecialchars($logoUrl); ?>" alt="Logo" style="max-height:70px; margin-bottom:16px;">
        <div class="invalid">❌ No certificate data found</div>
        <p>The token was redeemed but we couldn't find the certificate details. Contact the issuer.</p>
      </div>
    </body>
    </html>
    <?php
    $stmt2->close();
    $mysqli->close();
    exit;
}

$intern = $internResult->fetch_assoc();
$stmt2->close();

// Prepare passport image path (handle both possible upload paths you used)
$passportRelative = $intern['PASSPORT'] ?? '';
$passportPath = '';
$passportUrl = ''; // what we'll print into <img src="...">

if ($passportRelative) {
    // try cert/uploads and cert/Register/uploads, and also allow absolute relative string
    $tryPaths = [
        __DIR__ . '/' . ltrim($passportRelative, "/"),
        __DIR__ . '/Register/' . ltrim($passportRelative, "/"),
        __DIR__ . '/uploads/' . ltrim($passportRelative, "/"),
        __DIR__ . '/Register/uploads/' . ltrim($passportRelative, "/"),
    ];
    foreach ($tryPaths as $p) {
        if (file_exists($p)) {
            $passportPath = $p;
            break;
        }
    }
}

// If we found a file on disk, create a URL path relative to webroot
if ($passportPath) {
    // Attempt to create a web-accessible path from server path.
    // Most common: if document root is parent of this folder, we can build relative URL.
    // We'll fallback to using a PHP script to serve the image if needed.
    $webPathGuess = str_replace('\\', '/', $passportPath); // normalize
    // If passportPath is inside the current directory, we can reference it relatively:
    $relativeForHtml = str_replace($_SERVER['DOCUMENT_ROOT'], '', $passportPath);
    if ($relativeForHtml && $relativeForHtml !== $passportPath) {
        $passportUrl = $relativeForHtml;
    } else {
        // fallback: use a simple image proxy (serve image via PHP)
        $passportUrl = 'serve_image.php?file=' . urlencode(basename($passportPath)) . '&loc=' . urlencode(dirname($passportPath));
    }
} else {
    // fallback avatar / placeholder
    $passportUrl = 'data:image/svg+xml;utf8,' . rawurlencode('<svg xmlns="http://www.w3.org/2000/svg" width="300" height="300"><rect width="100%" height="100%" fill="#f0f2f5"/><text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle" fill="#9aa4b2" font-size="18">No photo</text></svg>');
}

// ----- Render beautiful verification page -----
?>
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Certificate Verification</title>
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <style>
    :root{
      --bg:#f6f8fb;
      --card:#ffffff;
      --muted:#6b7280;
      --accent:#0f172a;
      --green:#059669;
      --red:#ef4444;
      --panel:#eef2ff;
    }
    body{font-family: Inter, ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial; background:var(--bg); margin:0; padding:24px;}
    .wrap{max-width:980px; margin:28px auto;}
    .card{background:var(--card); border-radius:12px; padding:22px; box-shadow:0 8px 30px rgba(16,24,40,0.08); display:grid; grid-template-columns: 1fr 320px; gap:20px; align-items:start;}
    header{display:flex; align-items:center; gap:12px;}
    header img.logo{height:64px; object-fit:contain; border-radius:8px;}
    h1{font-size:20px; margin:0; color:var(--accent);}
    .meta{color:var(--muted); margin-top:6px; font-size:14px;}
    .left{padding-right:8px;}
    .detail{margin-top:12px; display:flex; gap:12px; flex-direction:column;}
    .row{display:flex; gap:12px; align-items:center;}
    .label{color:var(--muted); font-size:13px;}
    .value{font-weight:700; color:var(--accent); font-size:16px;}
    .status{display:inline-block; padding:8px 12px; border-radius:999px; font-weight:700; color:white; font-size:14px;}
    .valid{background:linear-gradient(90deg,#059669,#10b981);}
    .invalid{background:linear-gradient(90deg,#ef4444,#f97316);}
    .right{background:linear-gradient(180deg,rgba(15,23,42,0.03),transparent); padding:16px; border-radius:8px; text-align:center;}
    .passport{width:160px; height:160px; object-fit:cover; border-radius:8px; border:4px solid #fff; box-shadow:0 8px 22px rgba(2,6,23,0.08);}
    .small{font-size:13px; color:var(--muted);}
    .qr{margin-top:12px;}
    .footer{margin-top:18px; font-size:13px; color:var(--muted);}
    @media (max-width:820px){
      .card{grid-template-columns: 1fr; }
      .right{order:-1;}
    }
  </style>
</head>
<body>
  <div class="wrap">
    <div class="card">
      <div class="left">
        <header>
          
          <div>
            <h1>Certificate Verification</h1>
            <div class="meta">Verification for token: <strong><?php echo htmlspecialchars($token); ?></strong></div>
          </div>
        </header>

        <div class="detail">
          <div>
            <div class="label">Name</div>
            <div class="value"><?php echo htmlspecialchars($intern['NAME']); ?></div>
          </div>

          <div>
            <div class="label">Training</div>
            <div class="value"><?php echo htmlspecialchars($intern['POST']); ?></div>
          </div>

          <div class="row">
            <div style="flex:1">
              <div class="label">Start Date</div>
              <div class="value"><?php echo htmlspecialchars($intern['START_DATE']); ?></div>
            </div>
            <div style="flex:1">
              <div class="label">End Date</div>
              <div class="value"><?php echo htmlspecialchars($intern['END_DATE']); ?></div>
            </div>
          </div>

          <div>
            <div class="label">Verified On</div>
            <div class="value"><?php echo date("Y-m-d H:i:s"); ?></div>
          </div>

          <div class="footer">
            <strong>Note:</strong> This certificate was issued by Lancet Hospitals Limited. If you suspect impersonation of any sort, please contact the issuer on +2347033384818 or mail lancethospitalsltd@yahoo.com.
          </div>
        </div>
      </div>

      <aside class="right">
        <?php if ($passportUrl): ?>
          <img src="<?php echo htmlspecialchars($passportUrl); ?>" alt="Passport" class="passport">
        <?php endif; ?>

        <div style="margin-top:12px;">
          <?php if ($tokenRow['status'] === 'used'): ?>
            <div class="status valid">VALID</div>
          <?php else: ?>
            <div class="status invalid">INVALID</div>
          <?php endif; ?>
        </div>

        <div class="small" style="margin-top:14px;">
          Used by: <strong><?php echo htmlspecialchars($tokenRow['used_by'] ?: '-'); ?></strong><br>
          Used on: <strong><?php echo htmlspecialchars($tokenRow['used_on'] ?: '-'); ?></strong>
        </div>

        
      </aside>
    </div>
  </div>
</body>
</html>
<?php
$mysqli->close();
?>
