<?php
// superadmin/create-project.php
session_start();
require_once '../includes/config.php';
require_once '../includes/sa_auth.php';
require_once '../includes/db.php';
require_once '../includes/template_generator.php';
requireSuperAdmin();

$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $pdo = getDB();

    $groomName   = trim($_POST['groom_name'] ?? '');
    $brideName   = trim($_POST['bride_name'] ?? '');
    $dirName     = preg_replace('/[^a-zA-Z0-9_-]/', '', $groomName . $brideName);

    if (!$groomName || !$brideName) {
        $error = 'Groom and Bride names are required.';
    } elseif ($pdo->prepare("SELECT id FROM projects WHERE directory_name=?")->execute([$dirName]) &&
              $pdo->query("SELECT id FROM projects WHERE directory_name='$dirName'")->fetch()) {
        $error = "Directory '$dirName' already exists. Choose different names or edit the existing project.";
    } else {
        $projectDir = PROJECTS_DIR . '/' . $dirName;
        $imgDir     = $projectDir . '/img';

        // Create directories
        foreach (['', '/admin', '/user', '/css', '/img'] as $sub) {
            if (!is_dir($projectDir . $sub)) mkdir($projectDir . $sub, 0755, true);
        }

        // Handle uploaded files
        function uploadFile(string $key, string $dest, array $allowed = []): ?string {
            if (empty($_FILES[$key]['name'])) return null;
            $ext = strtolower(pathinfo($_FILES[$key]['name'], PATHINFO_EXTENSION));
            if ($allowed && !in_array($ext, $allowed)) return null;
            $filename = $key . '_' . time() . '.' . $ext;
            move_uploaded_file($_FILES[$key]['tmp_name'], $dest . '/' . $filename);
            return $filename;
        }

        $musicFile    = uploadFile('music_file', $imgDir, ['mp3','ogg','wav']) ?? '';
        $lastImgFile  = uploadFile('last_image_file', $imgDir, ['png','jpg','jpeg','webp']) ?? '';
        $thumbnailFile= uploadFile('thumbnail_file', $imgDir, ['jpg','jpeg','png','webp']) ?? '';

        // Background photos (up to 10)
        $bgPhotos = [];
        if (!empty($_FILES['bg_photos']['name'][0])) {
            $total = count($_FILES['bg_photos']['name']);
            for ($i = 0; $i < min($total, 10); $i++) {
                if ($_FILES['bg_photos']['error'][$i] === UPLOAD_ERR_OK) {
                    $ext  = strtolower(pathinfo($_FILES['bg_photos']['name'][$i], PATHINFO_EXTENSION));
                    $name = 'bg_' . ($i+1) . '_' . time() . '.' . $ext;
                    move_uploaded_file($_FILES['bg_photos']['tmp_name'][$i], $imgDir . '/' . $name);
                    $bgPhotos[] = $name;
                }
            }
        }

        // Admin password for per-project admin panel
        $rawAdminPass = $_POST['admin_password'] ?? 'Admin123!';
        $hashedAdminPass = password_hash($rawAdminPass, PASSWORD_BCRYPT);

        $ogUrl = PROJECTS_URL . '/' . $dirName;

        // Insert project
        $stmt = $pdo->prepare("INSERT INTO projects
          (directory_name,groom_name,bride_name,wedding_datetime,quote,quote_reference,
           groom_family,bride_family,church_name,church_location_url,venue_name,venue_location_url,
           gift_method,gift_number,rsvp_deadline,groom_phone,bride_phone,
           music_file,last_image_file,thumbnail_file,og_url,admin_password)
          VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");

        $stmt->execute([
            $dirName,
            $groomName, $brideName,
            $_POST['wedding_datetime'],
            $_POST['quote'] ?? '',
            $_POST['quote_reference'] ?? '',
            $_POST['groom_family'] ?? '',
            $_POST['bride_family'] ?? '',
            $_POST['church_name'] ?? '',
            $_POST['church_location_url'] ?? '',
            $_POST['venue_name'] ?? '',
            $_POST['venue_location_url'] ?? '',
            $_POST['gift_method'] ?? 'whish',
            $_POST['gift_number'] ?? '',
            $_POST['rsvp_deadline'] ?? null,
            $_POST['groom_phone'] ?? '',
            $_POST['bride_phone'] ?? '',
            $musicFile ? 'img/' . $musicFile : '',
            $lastImgFile ? 'img/' . $lastImgFile : 'img/love.png',
            $thumbnailFile ? 'img/' . $thumbnailFile : 'img/thumbnail.jpg',
            $ogUrl,
            $hashedAdminPass,
        ]);

        $projectId = $pdo->lastInsertId();

        // Insert photos
        if ($bgPhotos) {
            $photoStmt = $pdo->prepare("INSERT INTO project_photos (project_id,filename,sort_order) VALUES (?,?,?)");
            foreach ($bgPhotos as $i => $photo) {
                $photoStmt->execute([$projectId, $photo, $i]);
            }
        }

        // Copy shared CSS & icons from MichelMaria template
        $templateDir = BASE_DIR . '/MichelMaria';
        if (is_dir($templateDir . '/css')) {
            copy($templateDir . '/css/main.css', $projectDir . '/css/main.css');
            copy($templateDir . '/css/admin.css', $projectDir . '/css/admin.css');
        }
        // Copy icon images
        foreach (['icon-date.png','icon-church.png','icon-venue.png','love.png'] as $ico) {
            $src = $templateDir . '/img/' . $ico;
            if (file_exists($src)) copy($src, $imgDir . '/' . $ico);
        }
        // Copy fonts
        foreach (['High Spirited.ttf','LuxuriousRoman-Regular.ttf'] as $font) {
            $src = $templateDir . '/img/' . $font;
            if (file_exists($src)) copy($src, $imgDir . '/' . $font);
        }

        // Fetch project data back for template
        $proj   = $pdo->query("SELECT * FROM projects WHERE id=$projectId")->fetch();
        $photos = $pdo->query("SELECT filename FROM project_photos WHERE project_id=$projectId ORDER BY sort_order")->fetchAll(PDO::FETCH_COLUMN);

        // Generate index.html
        file_put_contents($projectDir . '/index.html', generateWeddingIndex($proj, $photos));

        // Copy and adapt PHP files
        copyProjectPHP($projectDir, $projectId, $dirName);

        $success = "Project '$dirName' created! <a href='" . PROJECTS_URL . "/$dirName/' target='_blank' style='color:var(--gold-light)'>View Site ↗</a>";
    }
}

function copyProjectPHP(string $dir, int $projectId, string $dirName): void {
    // get_invitees.php
    file_put_contents($dir . '/get_invitees.php', generateGetInvitees($projectId));
    // respond.php
    file_put_contents($dir . '/respond.php', generateRespond($projectId));
    // admin/login.php
    file_put_contents($dir . '/admin/login.php', generateAdminLogin($dirName));
    // admin/index.php  (manage invitees + view RSVP)
    file_put_contents($dir . '/admin/index.php', generateAdminPanel($projectId, $dirName));
    // admin/logout.php
    file_put_contents($dir . '/admin/logout.php', generateLogout('login.php'));
    // admin/get_invitees_api.php
    file_put_contents($dir . '/admin/add_invitees_api.php', generateAddInviteesApi($projectId));
    // admin/import_excel.php
    file_put_contents($dir . '/admin/import_excel.php', generateImportExcel($projectId, $dirName));
    // admin/rsvp_api.php
    file_put_contents($dir . '/admin/rsvp_data.php', generateRsvpData($projectId));
}

function dbInclude(): string {
    return "require_once dirname(__DIR__,3).'/includes/db.php';\n";
}

function generateGetInvitees(int $pid): string {
    return '<?php
header("Content-Type: application/json");
' . dbInclude() . '
try {
  $pdo = getDB();
  if (!isset($_GET["token"])) { echo json_encode(["success"=>false,"message"=>"Token missing"]); exit; }
  $token = $_GET["token"];
  $stmt = $pdo->prepare("SELECT i.id AS invitation_id, iv.id AS invitee_id, iv.name, iv.response_status
    FROM invitations i JOIN invitees iv ON i.id=iv.invitation_id
    WHERE i.project_id=? AND i.token=?");
  $stmt->execute([' . $pid . ', $token]);
  $invitees = $stmt->fetchAll(PDO::FETCH_ASSOC);
  echo json_encode(["success"=>true,"invitees"=>$invitees]);
} catch(PDOException $e) { echo json_encode(["success"=>false,"message"=>"DB error"]); }
';
}

function generateRespond(int $pid): string {
    return '<?php
header("Content-Type: application/json");
' . dbInclude() . '
try {
  $pdo = getDB();
  if (!isset($_GET["invitee_id"],$_GET["status"],$_GET["token"])) {
    echo json_encode(["success"=>false,"message"=>"Missing params"]); exit;
  }
  $invitee_id = intval($_GET["invitee_id"]);
  $status     = in_array($_GET["status"],["Accept","Decline"]) ? $_GET["status"] : null;
  $token      = $_GET["token"];
  if (!$status) { echo json_encode(["success"=>false,"message"=>"Invalid status"]); exit; }
  $stmt = $pdo->prepare("UPDATE invitees iv
    JOIN invitations i ON iv.invitation_id=i.id
    SET iv.response_status=?, iv.responded_at=NOW()
    WHERE iv.id=? AND i.token=? AND i.project_id=?");
  $stmt->execute([$status,$invitee_id,$token,' . $pid . ']);
  echo json_encode(["success"=>true]);
} catch(PDOException $e) { echo json_encode(["success"=>false,"message"=>"DB error"]); }
';
}

function generateAdminLogin(string $dirName): string {
    return '<?php
session_start();
' . dbInclude() . '
if (!empty($_SESSION["admin_auth_' . $dirName . '"])) { header("Location: index.php"); exit; }
$error = "";
if ($_SERVER["REQUEST_METHOD"]==="POST") {
  $pdo  = getDB();
  $proj = $pdo->prepare("SELECT admin_password FROM projects WHERE directory_name=?");
  $proj->execute(["' . $dirName . '"]);
  $row  = $proj->fetch();
  if ($row && password_verify($_POST["password"]??"",$row["admin_password"])) {
    $_SESSION["admin_auth_' . $dirName . '"] = true;
    header("Location: index.php"); exit;
  }
  $error = "Invalid password.";
}
?><!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"/><title>Admin Login</title>
<link rel="stylesheet" href="../css/admin.css"/></head>
<body class="login-page">
<form method="post">
  <h2>Admin Login</h2>
  <?php if($error) echo "<p class=\'error\'>$error</p>"; ?>
  <input type="password" name="password" placeholder="Admin Password" required><br/>
  <button type="submit">Login</button>
</form>
</body></html>
';
}

function generateAdminPanel(int $pid, string $dirName): string {
    return '<?php
session_start();
' . dbInclude() . '
if (empty($_SESSION["admin_auth_' . $dirName . '"])) { header("Location: login.php"); exit; }
$pdo = getDB();
$proj = $pdo->query("SELECT * FROM projects WHERE id=' . $pid . '")->fetch();
$msg = ""; $err = "";

// Handle manual invitee add
if ($_SERVER["REQUEST_METHOD"]==="POST" && isset($_POST["action"])) {
  if ($_POST["action"]==="add_manual") {
    $token    = trim($_POST["token"]);
    $invitees = array_filter(array_map("trim",$_POST["invitees"]??[]));
    if ($token && $invitees) {
      $stmt = $pdo->prepare("SELECT id FROM invitations WHERE project_id=? AND token=?");
      $stmt->execute([' . $pid . ',$token]);
      $inv = $stmt->fetch();
      if (!$inv) {
        $pdo->prepare("INSERT INTO invitations (project_id,token) VALUES (?,?)")->execute([' . $pid . ',$token]);
        $inv_id = $pdo->lastInsertId();
      } else { $inv_id = $inv["id"]; }
      $iStmt = $pdo->prepare("INSERT INTO invitees (invitation_id,name) VALUES (?,?)");
      foreach ($invitees as $name) $iStmt->execute([$inv_id,$name]);
      $msg = "Invitees added! Link: <code>../index.html?token=".urlencode($token)."</code>";
    } else { $err = "Token and at least one name required."; }
  }
}

// Fetch all RSVP data
$rows = $pdo->query("SELECT i.token, iv.id, iv.name, iv.response_status, iv.responded_at
  FROM invitations i JOIN invitees iv ON i.id=iv.invitation_id
  WHERE i.project_id=' . $pid . ' ORDER BY i.created_at DESC,iv.id ASC")->fetchAll();

$grouped = [];
foreach ($rows as $r) {
  $grouped[$r["token"]][] = $r;
}
$total    = count($rows);
$accepted = count(array_filter($rows, fn($r)=>$r["response_status"]==="Accept"));
$declined = count(array_filter($rows, fn($r)=>$r["response_status"]==="Decline"));
?>
<!DOCTYPE html>
<html lang="en"><head>
<meta charset="UTF-8"/><meta name="viewport" content="width=device-width,initial-scale=1"/>
<title>Admin — ' . $dirName . '</title>
<link rel="stylesheet" href="../css/admin.css"/>
</head><body>
<a class="logout-link" href="logout.php">Logout</a>
<h1>' . $dirName . ' — Admin Panel</h1>

<div style="display:flex;gap:20px;max-width:700px;margin:0 auto 30px;text-align:center;">
  <div style="flex:1;background:#222;border-radius:8px;padding:16px;">
    <div style="font-size:32px;font-weight:700;color:#b8a67c;"><?= $total ?></div>
    <div style="color:#888;font-size:13px;">Total</div>
  </div>
  <div style="flex:1;background:#222;border-radius:8px;padding:16px;">
    <div style="font-size:32px;font-weight:700;color:#4caf50;"><?= $accepted ?></div>
    <div style="color:#888;font-size:13px;">Accepted</div>
  </div>
  <div style="flex:1;background:#222;border-radius:8px;padding:16px;">
    <div style="font-size:32px;font-weight:700;color:#e53935;"><?= $declined ?></div>
    <div style="color:#888;font-size:13px;">Declined</div>
  </div>
  <div style="flex:1;background:#222;border-radius:8px;padding:16px;">
    <div style="font-size:32px;font-weight:700;color:#ccc;"><?= $total-$accepted-$declined ?></div>
    <div style="color:#888;font-size:13px;">Pending</div>
  </div>
</div>

<!-- Tabs -->
<div style="max-width:700px;margin:auto;">
  <div style="display:flex;gap:4px;border-bottom:1px solid #333;margin-bottom:24px;">
    <button class="tab-btn active" onclick="showTab(\'add\',this)">Add Invitees</button>
    <button class="tab-btn" onclick="showTab(\'excel\',this)">Import Excel</button>
    <button class="tab-btn" onclick="showTab(\'rsvp\',this)">RSVP Responses</button>
  </div>

  <!-- Tab: Manual Add -->
  <div id="tab-add" class="tab-pane active">
    <?php if($msg): ?><div class="success"><?= $msg ?></div><?php endif; ?>
    <?php if($err): ?><div class="error"><?= htmlspecialchars($err) ?></div><?php endif; ?>
    <form method="post">
      <input type="hidden" name="action" value="add_manual"/>
      <label>Token (unique ID for this group):<br/>
        <input type="text" name="token" placeholder="e.g. family_abc123" required/>
      </label><br/><br/>
      <div id="inviteeContainer">
        <div class="invitee-input">
          <input type="text" name="invitees[]" placeholder="Invitee Full Name" required/>
          <button type="button" onclick="removeRow(this)">✕</button>
        </div>
      </div>
      <button type="button" onclick="addRow()">+ Add Person</button><br/><br/>
      <button type="submit">Save Invitees</button>
    </form>
  </div>

  <!-- Tab: Excel Import -->
  <div id="tab-excel" class="tab-pane">
    <p style="margin-bottom:16px;color:#aaa;">Upload an Excel file with columns: <strong>Token</strong> and <strong>Name</strong></p>
    <p><a href="template.xlsx" class="map-button" download>⬇ Download Template</a></p><br/>
    <form method="post" action="import_excel.php" enctype="multipart/form-data">
      <input type="file" name="excel_file" accept=".xlsx,.xls" required/><br/><br/>
      <button type="submit">Import</button>
    </form>
  </div>

  <!-- Tab: RSVP -->
  <div id="tab-rsvp" class="tab-pane">
    <button class="refresh-button" onclick="location.reload()">↻ Refresh</button>
    <?php if(empty($grouped)): ?>
      <p style="text-align:center;color:#888;">No invitees yet.</p>
    <?php else: ?>
      <?php foreach($grouped as $token => $invitees): ?>
        <div class="group">
          <div class="token-header">
            <strong>Token:</strong> <?= htmlspecialchars($token) ?> &nbsp;|&nbsp;
            <code style="font-size:12px;color:#aaa;">../index.html?token=<?= urlencode($token) ?></code>
          </div>
          <ul class="invitee-list">
            <?php foreach($invitees as $iv): ?>
              <li>
                <?= htmlspecialchars($iv["name"]) ?> —
                <span class="status-<?= $iv["response_status"] ?: "NoResponse" ?>">
                  <?= $iv["response_status"] ?: "No response yet" ?>
                </span>
                <?php if($iv["responded_at"]): ?>
                  <span style="font-size:12px;color:#666;"> (<?= $iv["responded_at"] ?>)</span>
                <?php endif; ?>
              </li>
            <?php endforeach; ?>
          </ul>
        </div>
      <?php endforeach; ?>
    <?php endif; ?>
  </div>
</div>

<style>
.tab-btn{background:none;border:none;color:#888;font-family:inherit;font-size:14px;padding:10px 20px;cursor:pointer;border-bottom:2px solid transparent;margin-bottom:-1px;}
.tab-btn.active{color:#b8a67c;border-bottom-color:#b8a67c;}
.tab-pane{display:none;}.tab-pane.active{display:block;}
</style>
<script>
function showTab(id,btn) {
  document.querySelectorAll(".tab-pane").forEach(p=>p.classList.remove("active"));
  document.querySelectorAll(".tab-btn").forEach(b=>b.classList.remove("active"));
  document.getElementById("tab-"+id).classList.add("active");
  btn.classList.add("active");
}
function addRow() {
  const c=document.getElementById("inviteeContainer");
  const d=document.createElement("div");
  d.className="invitee-input";
  d.innerHTML=\'<input type="text" name="invitees[]" placeholder="Invitee Full Name" required/><button type="button" onclick="removeRow(this)">✕</button>\';
  c.appendChild(d);
}
function removeRow(b){b.parentNode.remove();}
</script>
</body></html>
';
}

function generateImportExcel(int $pid, string $dirName): string {
    return '<?php
session_start();
' . dbInclude() . '
if (empty($_SESSION["admin_auth_' . $dirName . '"])) { header("Location: login.php"); exit; }

if ($_SERVER["REQUEST_METHOD"]!=="POST" || empty($_FILES["excel_file"]["tmp_name"])) {
  header("Location: index.php"); exit;
}

require_once dirname(__DIR__,3)."/vendor/autoload.php"; // PhpSpreadsheet via Composer

use PhpOffice\PhpSpreadsheet\IOFactory;

try {
  $spreadsheet = IOFactory::load($_FILES["excel_file"]["tmp_name"]);
  $sheet       = $spreadsheet->getActiveSheet();
  $pdo         = getDB();
  $added       = 0;

  foreach ($sheet->getRowIterator(2) as $row) {
    $cells  = $row->getCellIterator(); $cells->setIterateOnlyExistingCells(false);
    $data   = [];
    foreach ($cells as $cell) { $data[] = trim((string)$cell->getValue()); if(count($data)>=2)break; }
    [$token,$name] = [$data[0]??"",$data[1]??""]; 
    if (!$token || !$name) continue;

    $stmt = $pdo->prepare("SELECT id FROM invitations WHERE project_id=? AND token=?");
    $stmt->execute([' . $pid . ',$token]);
    $inv = $stmt->fetch();
    if (!$inv) {
      $pdo->prepare("INSERT INTO invitations (project_id,token) VALUES (?,?)")->execute([' . $pid . ',$token]);
      $inv_id = $pdo->lastInsertId();
    } else { $inv_id = $inv["id"]; }
    $pdo->prepare("INSERT INTO invitees (invitation_id,name) VALUES (?,?)")->execute([$inv_id,$name]);
    $added++;
  }
  $_SESSION["import_msg"] = "$added invitees imported successfully.";
} catch(Exception $e) {
  $_SESSION["import_err"] = "Import failed: ".$e->getMessage();
}
header("Location: index.php");
';
}

function generateRsvpData(int $pid): string {
    return '<?php
header("Content-Type: application/json");
' . dbInclude() . '
$pdo = getDB();
$rows = $pdo->query("SELECT i.token,iv.name,iv.response_status,iv.responded_at
  FROM invitations i JOIN invitees iv ON i.id=iv.invitation_id
  WHERE i.project_id=' . $pid . '")->fetchAll();
echo json_encode(["success"=>true,"data"=>$rows]);
';
}

function generateLogout(string $redirect): string {
    return '<?php session_start(); session_destroy(); header("Location: ' . $redirect . '"); exit;';
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>Super Admin — Create Project</title>
  <link rel="stylesheet" href="sa.css"/>
</head>
<body>
<div class="sa-wrapper">
  <?php include 'sidebar.php'; ?>
  <div class="sa-main">
    <?php include 'topbar.php'; ?>
    <div class="sa-content">

      <?php if ($error): ?><div class="alert alert-error"><?= $error ?></div><?php endif; ?>
      <?php if ($success): ?><div class="alert alert-success"><?= $success ?></div><?php endif; ?>

      <form method="post" enctype="multipart/form-data">
        <!-- Couple Info -->
        <div class="card">
          <div class="card-header"><span class="card-title">💍 Couple Information</span></div>
          <div class="form-grid">
            <div class="form-group">
              <label>Groom Name *</label>
              <input type="text" name="groom_name" required placeholder="e.g. Michel" value="<?= htmlspecialchars($_POST['groom_name']??'') ?>"/>
            </div>
            <div class="form-group">
              <label>Bride Name *</label>
              <input type="text" name="bride_name" required placeholder="e.g. Maria" value="<?= htmlspecialchars($_POST['bride_name']??'') ?>"/>
            </div>
            <div class="form-group">
              <label>Wedding Date &amp; Time *</label>
              <input type="datetime-local" name="wedding_datetime" required value="<?= htmlspecialchars($_POST['wedding_datetime']??'') ?>"/>
            </div>
            <div class="form-group">
              <label>RSVP Deadline</label>
              <input type="date" name="rsvp_deadline" value="<?= htmlspecialchars($_POST['rsvp_deadline']??'') ?>"/>
            </div>
            <div class="form-group">
              <label>Groom Phone</label>
              <input type="tel" name="groom_phone" placeholder="+961 70 000 000" value="<?= htmlspecialchars($_POST['groom_phone']??'') ?>"/>
            </div>
            <div class="form-group">
              <label>Bride Phone</label>
              <input type="tel" name="bride_phone" placeholder="+961 70 000 000" value="<?= htmlspecialchars($_POST['bride_phone']??'') ?>"/>
            </div>
          </div>
        </div>

        <!-- Invitation Text -->
        <div class="card">
          <div class="card-header"><span class="card-title">✉️ Invitation Text</span></div>
          <div class="form-grid">
            <div class="form-group full">
              <label>Quote</label>
              <textarea name="quote" placeholder="e.g. We love because He first loved us."><?= htmlspecialchars($_POST['quote']??'') ?></textarea>
            </div>
            <div class="form-group">
              <label>Quote Reference</label>
              <input type="text" name="quote_reference" placeholder="e.g. 1 John 4:19" value="<?= htmlspecialchars($_POST['quote_reference']??'') ?>"/>
            </div>
            <div class="form-group">
              <label>Groom Family Name</label>
              <input type="text" name="groom_family" placeholder="e.g. Azar" value="<?= htmlspecialchars($_POST['groom_family']??'') ?>"/>
            </div>
            <div class="form-group">
              <label>Bride Family Name</label>
              <input type="text" name="bride_family" placeholder="e.g. Kassouf" value="<?= htmlspecialchars($_POST['bride_family']??'') ?>"/>
            </div>
          </div>
        </div>

        <!-- Location -->
        <div class="card">
          <div class="card-header"><span class="card-title">📍 Location</span></div>
          <div class="form-grid">
            <div class="form-group">
              <label>Church Name</label>
              <input type="text" name="church_name" placeholder="e.g. St. Elias Mkhalsiye" value="<?= htmlspecialchars($_POST['church_name']??'') ?>"/>
            </div>
            <div class="form-group">
              <label>Church Google Maps Link</label>
              <input type="url" name="church_location_url" placeholder="https://maps.app.goo.gl/..." value="<?= htmlspecialchars($_POST['church_location_url']??'') ?>"/>
            </div>
            <div class="form-group">
              <label>Venue Name</label>
              <input type="text" name="venue_name" placeholder="e.g. Grand Kadri Hotel" value="<?= htmlspecialchars($_POST['venue_name']??'') ?>"/>
            </div>
            <div class="form-group">
              <label>Venue Google Maps Link</label>
              <input type="url" name="venue_location_url" placeholder="https://maps.app.goo.gl/..." value="<?= htmlspecialchars($_POST['venue_location_url']??'') ?>"/>
            </div>
          </div>
        </div>

        <!-- Gift Registry -->
        <div class="card">
          <div class="card-header"><span class="card-title">🎁 Gift Registry</span></div>
          <div class="form-grid">
            <div class="form-group">
              <label>Payment Method</label>
              <select name="gift_method">
                <option value="whish" <?= (($_POST['gift_method']??'whish')==='whish')?'selected':'' ?>>Whish Money</option>
                <option value="omt"   <?= (($_POST['gift_method']??'')==='omt')?'selected':'' ?>>OMT</option>
              </select>
            </div>
            <div class="form-group">
              <label>Whish / OMT Number</label>
              <input type="text" name="gift_number" placeholder="e.g. 70 000 000" value="<?= htmlspecialchars($_POST['gift_number']??'') ?>"/>
            </div>
          </div>
        </div>

        <!-- Media Uploads -->
        <div class="card">
          <div class="card-header"><span class="card-title">🎵 Media &amp; Photos</span></div>
          <div class="form-grid">
            <div class="form-group">
              <label>Background Music (MP3)</label>
              <div class="file-zone">
                <div class="file-icon">🎵</div>
                <p>Click or drag to upload <strong>MP3</strong></p>
                <input type="file" name="music_file" accept=".mp3,.ogg,.wav"/>
              </div>
            </div>
            <div class="form-group">
              <label>Last Page Image (Love page)</label>
              <div class="file-zone">
                <div class="file-icon">🖼️</div>
                <p>Upload last slide image (PNG/JPG)</p>
                <input type="file" name="last_image_file" accept=".jpg,.jpeg,.png,.webp"/>
              </div>
            </div>
            <div class="form-group">
              <label>Link Thumbnail (OG Image)</label>
              <div class="file-zone">
                <div class="file-icon">🔗</div>
                <p>1200×630px recommended</p>
                <input type="file" name="thumbnail_file" accept=".jpg,.jpeg,.png,.webp"/>
              </div>
            </div>
            <div class="form-group full">
              <label>Background Photos (up to 10 — JPG/PNG/WebP)</label>
              <div class="file-zone">
                <div class="file-icon">📸</div>
                <p>Select <strong>multiple files</strong> — up to 10 photos</p>
                <input type="file" name="bg_photos[]" accept=".jpg,.jpeg,.png,.webp" multiple/>
              </div>
            </div>
          </div>
        </div>

        <!-- Security -->
        <div class="card">
          <div class="card-header"><span class="card-title">🔐 Admin Access</span></div>
          <div class="form-grid">
            <div class="form-group">
              <label>Per-Project Admin Password</label>
              <input type="text" name="admin_password" placeholder="e.g. Admin@Michel2026" required value="<?= htmlspecialchars($_POST['admin_password']??'') ?>"/>
              <span style="font-size:12px;color:var(--text-muted);">This password is used to access the project's /admin/ panel.</span>
            </div>
          </div>
        </div>

        <button type="submit" class="btn btn-primary" style="font-size:16px;padding:14px 32px;">
          🚀 Create Project &amp; Generate Website
        </button>
      </form>

    </div>
  </div>
</div>
</body>
</html>
