<?php
// superadmin/edit-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();

$pdo = getDB();
$id  = intval($_GET['id'] ?? 0);
$project = $pdo->prepare("SELECT * FROM projects WHERE id=?");
$project->execute([$id]);
$p = $project->fetch();

if (!$p) { header('Location: index.php'); exit; }

$photos = $pdo->prepare("SELECT filename FROM project_photos WHERE project_id=? ORDER BY sort_order");
$photos->execute([$id]);
$bgPhotos = $photos->fetchAll(PDO::FETCH_COLUMN);

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $projectDir = PROJECTS_DIR . '/' . $p['directory_name'];
    $imgDir     = $projectDir . '/img';

    function uploadFileEdit(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     = uploadFileEdit('music_file', $imgDir, ['mp3','ogg','wav']);
    $lastImgFile   = uploadFileEdit('last_image_file', $imgDir, ['png','jpg','jpeg','webp']);
    $thumbnailFile = uploadFileEdit('thumbnail_file', $imgDir, ['jpg','jpeg','png','webp']);

    // New bg photos
    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;
                $pdo->prepare("INSERT INTO project_photos (project_id,filename,sort_order) VALUES (?,?,?)")
                    ->execute([$id, $name, count($bgPhotos)]);
            }
        }
    }

    $fields = [
        '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',
    ];
    $data = [];
    foreach ($fields as $f) $data[$f] = $_POST[$f] ?? $p[$f];
    if ($musicFile)     $data['music_file']     = 'img/' . $musicFile;
    if ($lastImgFile)   $data['last_image_file'] = 'img/' . $lastImgFile;
    if ($thumbnailFile) $data['thumbnail_file']  = 'img/' . $thumbnailFile;

    // Build SET clause
    $sets = implode(',', array_map(fn($k) => "$k=?", array_keys($data)));
    $vals = array_values($data);
    $vals[] = $id;
    $pdo->prepare("UPDATE projects SET $sets WHERE id=?")->execute($vals);

    // Regenerate index.html
    $updatedProj  = $pdo->query("SELECT * FROM projects WHERE id=$id")->fetch();
    $currentPhotos = $pdo->prepare("SELECT filename FROM project_photos WHERE project_id=? ORDER BY sort_order");
    $currentPhotos->execute([$id]);
    $photoList = $currentPhotos->fetchAll(PDO::FETCH_COLUMN);
    file_put_contents($projectDir . '/index.html', generateWeddingIndex($updatedProj, $photoList));

    $p = $updatedProj;
    $success = 'Project updated and website regenerated!';
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>Edit 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; ?>

      <div class="alert alert-info">
        Editing: <strong><?= htmlspecialchars($p['directory_name']) ?></strong> &nbsp;|&nbsp;
        <a href="<?= PROJECTS_URL ?>/<?= urlencode($p['directory_name']) ?>/" target="_blank" style="color:var(--gold-light)">View Site ↗</a>
      </div>

      <form method="post" enctype="multipart/form-data">
        <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" value="<?= htmlspecialchars($p['groom_name']) ?>" required/>
            </div>
            <div class="form-group">
              <label>Bride Name</label>
              <input type="text" name="bride_name" value="<?= htmlspecialchars($p['bride_name']) ?>" required/>
            </div>
            <div class="form-group">
              <label>Wedding Date &amp; Time</label>
              <input type="datetime-local" name="wedding_datetime" value="<?= date('Y-m-d\TH:i', strtotime($p['wedding_datetime'])) ?>"/>
            </div>
            <div class="form-group">
              <label>RSVP Deadline</label>
              <input type="date" name="rsvp_deadline" value="<?= htmlspecialchars($p['rsvp_deadline'] ?? '') ?>"/>
            </div>
            <div class="form-group">
              <label>Groom Phone</label>
              <input type="tel" name="groom_phone" value="<?= htmlspecialchars($p['groom_phone'] ?? '') ?>"/>
            </div>
            <div class="form-group">
              <label>Bride Phone</label>
              <input type="tel" name="bride_phone" value="<?= htmlspecialchars($p['bride_phone'] ?? '') ?>"/>
            </div>
          </div>
        </div>

        <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"><?= htmlspecialchars($p['quote'] ?? '') ?></textarea>
            </div>
            <div class="form-group">
              <label>Quote Reference</label>
              <input type="text" name="quote_reference" value="<?= htmlspecialchars($p['quote_reference'] ?? '') ?>"/>
            </div>
            <div class="form-group">
              <label>Groom Family</label>
              <input type="text" name="groom_family" value="<?= htmlspecialchars($p['groom_family'] ?? '') ?>"/>
            </div>
            <div class="form-group">
              <label>Bride Family</label>
              <input type="text" name="bride_family" value="<?= htmlspecialchars($p['bride_family'] ?? '') ?>"/>
            </div>
          </div>
        </div>

        <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" value="<?= htmlspecialchars($p['church_name'] ?? '') ?>"/>
            </div>
            <div class="form-group">
              <label>Church Google Maps Link</label>
              <input type="url" name="church_location_url" value="<?= htmlspecialchars($p['church_location_url'] ?? '') ?>"/>
            </div>
            <div class="form-group">
              <label>Venue Name</label>
              <input type="text" name="venue_name" value="<?= htmlspecialchars($p['venue_name'] ?? '') ?>"/>
            </div>
            <div class="form-group">
              <label>Venue Google Maps Link</label>
              <input type="url" name="venue_location_url" value="<?= htmlspecialchars($p['venue_location_url'] ?? '') ?>"/>
            </div>
          </div>
        </div>

        <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" <?= ($p['gift_method']==='whish')?'selected':'' ?>>Whish Money</option>
                <option value="omt"   <?= ($p['gift_method']==='omt')?'selected':'' ?>>OMT</option>
              </select>
            </div>
            <div class="form-group">
              <label>Number</label>
              <input type="text" name="gift_number" value="<?= htmlspecialchars($p['gift_number'] ?? '') ?>"/>
            </div>
          </div>
        </div>

        <div class="card">
          <div class="card-header"><span class="card-title">🎵 Media (leave blank to keep current)</span></div>
          <?php if ($bgPhotos): ?>
          <p style="font-size:13px;color:var(--text-muted);margin-bottom:12px;">Current background photos: <?= implode(', ', $bgPhotos) ?></p>
          <?php endif; ?>
          <div class="form-grid">
            <div class="form-group">
              <label>Replace Music (MP3)</label>
              <div class="file-zone"><div class="file-icon">🎵</div><p>Upload new MP3</p>
              <input type="file" name="music_file" accept=".mp3,.ogg,.wav"/></div>
            </div>
            <div class="form-group">
              <label>Replace Last Image</label>
              <div class="file-zone"><div class="file-icon">🖼️</div><p>Upload new image</p>
              <input type="file" name="last_image_file" accept=".jpg,.jpeg,.png,.webp"/></div>
            </div>
            <div class="form-group">
              <label>Replace Thumbnail</label>
              <div class="file-zone"><div class="file-icon">🔗</div><p>1200×630px</p>
              <input type="file" name="thumbnail_file" accept=".jpg,.jpeg,.png,.webp"/></div>
            </div>
            <div class="form-group full">
              <label>Add More Background Photos</label>
              <div class="file-zone"><div class="file-icon">📸</div><p>Select multiple</p>
              <input type="file" name="bg_photos[]" accept=".jpg,.jpeg,.png,.webp" multiple/></div>
            </div>
          </div>
        </div>

        <button type="submit" class="btn btn-primary" style="font-size:16px;padding:14px 32px;">
          💾 Save Changes &amp; Regenerate Website
        </button>
        &nbsp;
        <a href="index.php" class="btn btn-outline">Cancel</a>
      </form>

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