
­­­­­­­­­­­­­­­­­­
<!DOCTYPE html>
<html>
<?php
/**
 * RSVP Landing Page (MySQL)
 * URL: index.php?t=UNIQUE_TOKEN
 */

declare(strict_types=1);
date_default_timezone_set('Asia/Riyadh');

function h(string $s): string {
  return htmlspecialchars($s, ENT_QUOTES, 'UTF-8');
}

/* =========================
   DATABASE CONFIG
========================= */
$dbHost = 'localhost';
$dbName = 'balubaid_invitation';
$dbUser = 'balubaid_invitation';
$dbPass = 'BGCjeddah@69';

try {
  $pdo = new PDO(
    "mysql:host=$dbHost;dbname=$dbName;charset=utf8mb4",
    $dbUser,
    $dbPass,
    [
      PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
      PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
    ]
  );
} catch (PDOException $e) {
  http_response_code(500);
  exit('Database connection failed.');
}

/* =========================
   TOKEN VALIDATION
========================= */
$token = $_GET['t'] ?? '';
$token = trim($token);

if ($token === '' || !preg_match('/^[A-Za-z0-9_-]{6,64}$/', $token)) {
  http_response_code(400);
  exit('Invalid invitation link.');
}

/* =========================
   FETCH INVITEE
========================= */
$stmt = $pdo->prepare("SELECT * FROM invitees WHERE token = :token LIMIT 1");
$stmt->execute(['token' => $token]);
$invitee = $stmt->fetch();

if (!$invitee) {
  http_response_code(404);
  exit('Invitation not found or expired.');
}

$inviteeName = trim(($invitee['title'] ?? '') . ' ' . $invitee['full_name']);

/* =========================
   HANDLE RSVP SUBMISSION
========================= */
$successMsg = '';
$errorMsg = '';

$redirectBaseUrl = 'https://inv.balubaid.com/thank-you.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

  $response = $_POST['response'] ?? '';
  $note = trim($_POST['note'] ?? '');

  if (!in_array($response, ['yes', 'no'], true)) {
    $errorMsg = 'Please select an option.';
  } else {

    $insert = $pdo->prepare("
      INSERT INTO rsvps
      (invitee_id, token, response, note, ip_address, user_agent, created_at)
      VALUES
      (:invitee_id, :token, :response, :note, :ip, :ua, NOW())
    ");

    $insert->execute([
      'invitee_id' => $invitee['id'],
      'token'      => $token,
      'response'   => $response,
      'note'       => $note,
      'ip'         => $_SERVER['REMOTE_ADDR'] ?? '',
      'ua'         => $_SERVER['HTTP_USER_AGENT'] ?? ''
    ]);

    // ✅ Redirect after successful submission
    header('Location: ' . $redirectBaseUrl . '?status=' . $response);
    exit;
  }
}

/* =========================
   FETCH LATEST RSVP
========================= */
$latestStmt = $pdo->prepare("
  SELECT response, created_at
  FROM rsvps
  WHERE token = :token
  ORDER BY id DESC
  LIMIT 1
");
$latestStmt->execute(['token' => $token]);
$latest = $latestStmt->fetch();
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Invitation – Evening of Appreciation</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <style>
    body { background:#f5f6f8; }
    .card { border-radius:16px; border:0; }
    .btn-lg { border-radius:14px; }
    .bginv{
  background-image: url("bgcinv.png");
  background-size: cover;      /* cover | contain */
  background-repeat: no-repeat;
  background-position: center center;
}
input[type="radio"] {
  accent-color: #000;
  border-color:black;
}
  </style>
</head>
<body >
<div class="container py-5">
  <div class="row justify-content-center">
    <div class="col-lg-8 col-xl-7 ">
      <div class="card shadow-sm">
          
    <img src="Pattern.png" class="img-responsive" alt="" style="    position: absolute;
    height: 230px;
    right: 1px;
    "> 
    
        <div class="card-body p-4 p-md-5 bginv">
            
            
       <img src="Logo.png" class="img-responsive" alt="" style="height:42px;"> 
       
       <div style="height:32px;"></div>

          <h4 class="mb-3" style="color:#ba8751 !important;" >Invitation to an Evening of Appreciation</h4>

          <?php if ($successMsg): ?>
            <div class="alert alert-success"><?= h($successMsg) ?><br> <a href="https://inv.balubaid.com/calendar/ceremony.ics">add to you calender</a></div>
          <?php endif; ?>

          <?php if ($errorMsg): ?>
            <div class="alert alert-danger"><?= h($errorMsg) ?></div>
          <?php endif; ?>

          <p>Dear <strong><?= h($inviteeName) ?></strong>,</p>

          <p>
            I am pleased to invite you to a gala dinner in appreciation of 
            <strong>Mr. Mohammed Al-Haj</strong>, marking the conclusion of his tenure as Group CEO at the end of December, following 8 years period of strong leadership, strategic progress, and solid performance.
          </p>

          <p>
            As he transitions to a new professional role, he will continue his engagement with the company as a Board Member and Chairman of the Executive Committee, supporting continuity in strategy and long-term growth.
          </p>

          <p>
            <strong>Date:</strong> Saturday, December 20 2025<br>
            <strong>Time:</strong> 8:00 PM<br>
            <strong>Venue:</strong> Balubaid family residence<br>
            <strong>Dress code:</strong> Formal
          </p>

          <p>
            For any inquiries, please contact <br> <strong>Mr. Esam</strong> at
            <strong>0555137832</strong>
            
            <br>
            
            <strong>Mr. Faiz</strong> at
            <strong>0500654254</strong>.
            </p>
          </p>
         
          <p class="mt-4">
            Warm regards,<br>
            <strong>Khalid Balubaid</strong><br>
            Chairman – BGC
          </p>

          <hr>

          <h6 class="mb-3">Kindly confirm your attendance</h6>

          <form method="post">
            <div class="mb-3">
              <div class="form-check">
                <input class="form-check-input" type="radio" name="response" value="yes" required>
                <label class="form-check-label">I will attend</label>
              </div>
              <div class="form-check">
                <input class="form-check-input" type="radio" name="response" value="no" required>
                <label class="form-check-label">I will not attend</label>
              </div>
            </div>

            <div class="mb-3">
              <label class="form-label">Note (optional)</label>
              <textarea class="form-control" name="note" rows="3"></textarea>
            </div>

            <button style="background:#004275 !important;border:#004275;" class="btn btn-primary btn-lg w-100">Submit</button>

          <!--  <?php if ($latest): ?>
              <p class="text-muted small mt-3 mb-0">
                Last response: <strong><?= h($latest['response']) ?></strong>
                (<?= h($latest['created_at']) ?>)
              </p>
            <?php endif; ?>  -->
          </form>

        </div>
      </div>
    </div>
  </div>
</div>
</body>
</html>