<?php
session_start();
require __DIR__ . '/helpers.php';

$ADMIN_KEY = getenv('FLIXCOOKS_ADMIN_KEY') ?: 'REWnqLYwQtZZDgXcNxnt';
$authed = isset($_SESSION['fc_admin']) && $_SESSION['fc_admin'] === true;

if (!$authed && isset($_POST['password'])) {
    if (hash_equals($ADMIN_KEY, $_POST['password'])) {
        $_SESSION['fc_admin'] = true;
        $authed = true;
    } else {
        $error = 'Wrong password';
    }
}

if (!$authed) {
    ?>
    <!doctype html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>FlixCooks Admin Login</title>
      <link rel="stylesheet" href="/assets/style.css">
      <style>
        body { display: grid; place-items: center; min-height: 100vh; }
        .login-card { background: #fff; padding: 24px; border-radius: 16px; box-shadow: var(--shadow); width: min(360px, 90vw); }
        .login-card h1 { margin: 0 0 12px; }
        .login-card form { display: grid; gap: 12px; }
        .login-card input { padding: 12px; border-radius: 10px; border: 1px solid rgba(0,0,0,0.1); }
        .login-card button { padding: 12px; border-radius: 10px; border: none; background: var(--accent); color: #fff; font-weight: 700; cursor: pointer; }
        .error { color: #b00020; margin: 0; }
      </style>
    </head>
    <body>
      <div class="login-card">
        <h1>Admin</h1>
        <p>Enter your password to manage recipes.</p>
        <?php if (!empty($error)): ?><p class="error"><?php echo e($error); ?></p><?php endif; ?>
        <form method="post">
          <input type="password" name="password" placeholder="Password" required>
          <button type="submit">Login</button>
        </form>
      </div>
    </body>
    </html>
    <?php
    exit;
}

$allRecipes = load_recipes();
$message = null;
$editing = null;
$editIndex = null;
$editingEn = [];
$editingDe = [];

if (isset($_GET['edit'])) {
    $slugEdit = trim($_GET['edit']);
    foreach ($allRecipes as $idx => $r) {
        if (($r['slug'] ?? '') === $slugEdit) {
            $editing = $r;
            $editIndex = $idx;
            $editingEn = $r['i18n']['en'] ?? [];
            $editingDe = $r['i18n']['de'] ?? [];
            break;
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'delete') {
    $slugDel = trim($_POST['slug'] ?? '');
    $before = count($allRecipes);
    $allRecipes = array_values(array_filter($allRecipes, fn($r) => ($r['slug'] ?? '') !== $slugDel));
    if ($before !== count($allRecipes) && save_recipes($allRecipes)) {
        $message = 'Recipe deleted.';
    } else {
        $message = 'Could not delete. Check permissions.';
    }
    $editing = null;
    $editIndex = null;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'save') {
    // helpers
    $parse_csv = fn($text) => array_values(array_filter(array_map('trim', explode(',', $text ?? '')), 'strlen'));
    $parse_lines = fn($text) => array_values(array_filter(array_map('trim', preg_split('/\\r?\\n/', $text ?? '')), 'strlen'));

    $titleEn = trim($_POST['title_en'] ?? '');
    $titleDe = trim($_POST['title_de'] ?? '');
    $descriptionEn = trim($_POST['description_en'] ?? '');
    $descriptionDe = trim($_POST['description_de'] ?? '');
    $hero = trim($_POST['hero'] ?? '');
    $categoryEn = trim($_POST['category_en'] ?? '');
    $categoryDe = trim($_POST['category_de'] ?? '');
    $tagsEn = $parse_csv($_POST['tags_en'] ?? '');
    $tagsDe = $parse_csv($_POST['tags_de'] ?? '');
    $prep = (int) ($_POST['prep_time'] ?? 0);
    $cook = (int) ($_POST['cook_time'] ?? 0);
    $total = (int) ($_POST['total_time'] ?? ($prep + $cook));
    $servings = (int) ($_POST['servings'] ?? 0);
    $difficultyEn = trim($_POST['difficulty_en'] ?? 'Easy');
    $difficultyDe = trim($_POST['difficulty_de'] ?? 'Einfach');
    $ingredientsEn = $parse_lines($_POST['ingredients_en'] ?? '');
    $ingredientsDe = $parse_lines($_POST['ingredients_de'] ?? '');
    $utensilsEn = $parse_lines($_POST['utensils_en'] ?? '');
    $utensilsDe = $parse_lines($_POST['utensils_de'] ?? '');
    $stepsEn = $parse_lines($_POST['steps_en'] ?? '');
    $stepsDe = $parse_lines($_POST['steps_de'] ?? '');
    $featured = isset($_POST['featured']) && $_POST['featured'] === '1';
    $comingSoon = isset($_POST['coming_soon']) && $_POST['coming_soon'] === '1';
    $slugOriginal = trim($_POST['slug_original'] ?? '');

    // keep previous language data if fields left blank while editing
    $prevEn = $editing['i18n']['en'] ?? [];
    $prevDe = $editing['i18n']['de'] ?? [];

    $titleEn = $titleEn !== '' ? $titleEn : ($prevEn['title'] ?? '');
    $titleDe = $titleDe !== '' ? $titleDe : ($prevDe['title'] ?? '');
    $descriptionEn = $descriptionEn !== '' ? $descriptionEn : ($prevEn['description'] ?? '');
    $descriptionDe = $descriptionDe !== '' ? $descriptionDe : ($prevDe['description'] ?? '');
    $categoryEn = $categoryEn !== '' ? $categoryEn : ($prevEn['category'] ?? '');
    $categoryDe = $categoryDe !== '' ? $categoryDe : ($prevDe['category'] ?? '');
    $difficultyEn = $difficultyEn !== '' ? $difficultyEn : ($prevEn['difficulty'] ?? 'Easy');
    $difficultyDe = $difficultyDe !== '' ? $difficultyDe : ($prevDe['difficulty'] ?? 'Einfach');
    $tagsEn = !empty($tagsEn) ? $tagsEn : ($prevEn['tags'] ?? []);
    $tagsDe = !empty($tagsDe) ? $tagsDe : ($prevDe['tags'] ?? []);
    $ingredientsEn = !empty($ingredientsEn) ? $ingredientsEn : ($prevEn['ingredients'] ?? []);
    $ingredientsDe = !empty($ingredientsDe) ? $ingredientsDe : ($prevDe['ingredients'] ?? []);
    $utensilsEn = !empty($utensilsEn) ? $utensilsEn : ($prevEn['utensils'] ?? []);
    $utensilsDe = !empty($utensilsDe) ? $utensilsDe : ($prevDe['utensils'] ?? []);
    $stepsEn = !empty($stepsEn) ? $stepsEn : ($prevEn['steps'] ?? []);
    $stepsDe = !empty($stepsDe) ? $stepsDe : ($prevDe['steps'] ?? []);

    if ($titleEn === '') {
        $message = 'English title is required.';
    } elseif (!$comingSoon && (empty($ingredientsEn) || empty($stepsEn))) {
        $message = 'Ingredients and steps are required unless marked coming soon.';
    } else {
        // determine slug
        if ($slugOriginal) {
            $slug = $slugOriginal;
        } else {
            $slug = slugify($titleEn ?: $titleDe);
            // ensure unique slug
            $existingSlugs = array_map(fn($r) => $r['slug'] ?? '', $allRecipes);
            $base = $slug;
            $i = 1;
            while (in_array($slug, $existingSlugs, true)) {
                $slug = $base . '-' . $i;
                $i++;
            }
        }

        if ($featured) {
            foreach ($allRecipes as &$r) {
                $r['featured'] = false;
            }
            unset($r);
        }

        $record = [
            'slug' => $slug,
            'hero' => $hero,
            'prep_time' => $prep,
            'cook_time' => $cook,
            'total_time' => $total,
            'servings' => $servings,
            'featured' => $featured,
            'coming_soon' => $comingSoon,
            'i18n' => [
                'en' => [
                    'title' => $titleEn,
                    'description' => $descriptionEn,
                    'category' => $categoryEn,
                    'difficulty' => $difficultyEn,
                    'tags' => $tagsEn,
                    'ingredients' => $ingredientsEn,
                    'utensils' => $utensilsEn,
                    'steps' => $stepsEn,
                ],
                'de' => [
                    'title' => $titleDe ?: $titleEn,
                    'description' => $descriptionDe ?: $descriptionEn,
                    'category' => $categoryDe ?: $categoryEn,
                    'difficulty' => $difficultyDe,
                    'tags' => !empty($tagsDe) ? $tagsDe : $tagsEn,
                    'ingredients' => !empty($ingredientsDe) ? $ingredientsDe : $ingredientsEn,
                    'utensils' => !empty($utensilsDe) ? $utensilsDe : $utensilsEn,
                    'steps' => !empty($stepsDe) ? $stepsDe : $stepsEn,
                ],
            ],
        ];

        if ($slugOriginal && $editIndex !== null) {
            $allRecipes[$editIndex] = $record;
        } else {
            $allRecipes[] = $record;
        }

        if (save_recipes($allRecipes)) {
            $message = $slugOriginal ? 'Saved changes.' : 'Saved! New recipe added.';
        } else {
            $message = 'Could not save the file. Check permissions on data/recipes.json.';
        }
    }
}
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>FlixCooks Admin</title>
  <link rel="stylesheet" href="/assets/style.css">
  <style>
    body { max-width: 1100px; margin: 24px auto 64px; padding: 0 16px; color: var(--ink); }
    .admin-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 18px; }
    form.admin-form {
      display: grid;
      gap: 12px;
      background: var(--surface-2);
      padding: 18px;
      border-radius: 16px;
      box-shadow: var(--shadow);
      border: 1px solid rgba(255,255,255,0.08);
      color: var(--ink);
    }
    form.admin-form label { font-weight: 700; display: block; margin-bottom: 6px; color: var(--ink); }
    form.admin-form input, form.admin-form textarea, form.admin-form select {
      width: 100%;
      padding: 12px;
      border-radius: 12px;
      border: 1px solid rgba(255,255,255,0.18);
      background: rgba(255,255,255,0.08);
      color: var(--ink);
    }
    form.admin-form textarea { resize: vertical; }
    form.admin-form input::placeholder,
    form.admin-form textarea::placeholder {
      color: rgba(255,255,255,0.6);
    }
    form.admin-form textarea { min-height: 120px; }
    .row { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 12px; }
    .message { padding: 12px; border-radius: 12px; background: var(--accent-soft); color: var(--ink); }
    .list { margin-top: 18px; }
    .list-item { padding: 12px 0; border-bottom: 1px solid rgba(255,255,255,0.08); display: flex; justify-content: space-between; align-items: center; }
    .pill { background: rgba(255,255,255,0.06); color: var(--ink); }
  </style>
</head>
<body>
  <div class="admin-header">
    <h1>FlixCooks Admin</h1>
    <div>
      <a class="button" href="/index.php" style="padding:10px 14px;">View site</a>
      <?php if ($editing): ?>
        <a class="button" href="/admin.php" style="padding:10px 14px;">Back</a>
      <?php endif; ?>
    </div>
  </div>

  <?php if ($message): ?>
    <div class="message"><?php echo e($message); ?></div>
  <?php endif; ?>

  <form class="admin-form" method="post">
    <input type="hidden" name="action" value="save">
    <?php if ($editing): ?>
      <input type="hidden" name="slug_original" value="<?php echo e($editing['slug']); ?>">
    <?php endif; ?>
    <label>Hero Image URL</label>
    <input type="text" name="hero" placeholder="https://... or /assets/images/hero.jpg" value="<?php echo e($editing['hero'] ?? ''); ?>">
    <p style="color: var(--muted); margin: 4px 0 8px; font-size: 13px;">Accepts full URLs or relative paths (e.g. /assets/images/hero.jpg).</p>

    <div class="row">
      <div>
        <label>Prep time (minutes)</label>
        <input type="number" name="prep_time" min="0" value="<?php echo e($editing['prep_time'] ?? 0); ?>">
      </div>
      <div>
        <label>Cook time (minutes)</label>
        <input type="number" name="cook_time" min="0" value="<?php echo e($editing['cook_time'] ?? 0); ?>">
      </div>
      <div>
        <label>Total time (minutes)</label>
        <input type="number" name="total_time" min="0" value="<?php echo e($editing['total_time'] ?? 0); ?>" placeholder="0 to auto-sum">
      </div>
      <div>
        <label>Servings</label>
        <input type="number" name="servings" min="1" value="<?php echo e($editing['servings'] ?? 2); ?>">
      </div>
    </div>

    <hr>
    <h3>English</h3>
    <div class="row">
      <div>
        <label>Title (EN) *</label>
        <input type="text" name="title_en" required value="<?php echo e($editingEn['title'] ?? ''); ?>">
      </div>
      <div>
        <label>Category (EN)</label>
        <input type="text" name="category_en" placeholder="Dinner, Dessert..." value="<?php echo e($editingEn['category'] ?? ''); ?>">
      </div>
      <div>
        <label>Difficulty (EN)</label>
        <?php $diffEn = $editingEn['difficulty'] ?? 'Easy'; ?>
        <select name="difficulty_en">
          <option <?php echo $diffEn==='Easy'?'selected':''; ?>>Easy</option>
          <option <?php echo $diffEn==='Medium'?'selected':''; ?>>Medium</option>
          <option <?php echo $diffEn==='Hard'?'selected':''; ?>>Hard</option>
        </select>
      </div>
    </div>
    <label>Description (EN)</label>
    <textarea name="description_en" placeholder="Short teaser"><?php echo e($editingEn['description'] ?? ''); ?></textarea>
    <label>Tags (EN, comma separated)</label>
    <input type="text" name="tags_en" placeholder="gluten-free, 30-minutes" value="<?php echo e(isset($editingEn['tags']) ? implode(', ', $editingEn['tags']) : ''); ?>">
    <label>Ingredients (EN, one per line) *</label>
    <textarea name="ingredients_en" placeholder="1 cup flour&#10;2 eggs"><?php echo isset($editingEn['ingredients']) ? e(implode("\n", $editingEn['ingredients'])) : ''; ?></textarea>
    <label>Utensils (EN, one per line)</label>
    <textarea name="utensils_en" placeholder="12&quot; skillet&#10;Sheet pan&#10;Rubber spatula"><?php echo isset($editingEn['utensils']) ? e(implode("\n", $editingEn['utensils'])) : ''; ?></textarea>
    <label>Steps (EN, one per line) *</label>
    <textarea name="steps_en" placeholder="Preheat oven...&#10;Mix dry ingredients..."><?php echo isset($editingEn['steps']) ? e(implode("\n", $editingEn['steps'])) : ''; ?></textarea>

    <hr>
    <h3>Deutsch</h3>
    <div class="row">
      <div>
        <label>Titel (DE)</label>
        <input type="text" name="title_de" value="<?php echo e($editingDe['title'] ?? ''); ?>">
      </div>
      <div>
        <label>Kategorie (DE)</label>
        <input type="text" name="category_de" placeholder="Abendessen, Dessert..." value="<?php echo e($editingDe['category'] ?? ''); ?>">
      </div>
      <div>
        <label>Schwierigkeitsgrad (DE)</label>
        <?php $diffDe = $editingDe['difficulty'] ?? 'Einfach'; ?>
        <select name="difficulty_de">
          <option <?php echo strtolower($diffDe)==='einfach'?'selected':''; ?>>Einfach</option>
          <option <?php echo strtolower($diffDe)==='mittel'?'selected':''; ?>>Mittel</option>
          <option <?php echo strtolower($diffDe)==='schwer'?'selected':''; ?>>Schwer</option>
        </select>
      </div>
    </div>
    <label>Beschreibung (DE)</label>
    <textarea name="description_de" placeholder="Kurzer Teaser"><?php echo e($editingDe['description'] ?? ''); ?></textarea>
    <label>Tags (DE, komma-getrennt)</label>
    <input type="text" name="tags_de" placeholder="schnell, vegetarisch" value="<?php echo e(isset($editingDe['tags']) ? implode(', ', $editingDe['tags']) : ''); ?>">
    <label>Zutaten (DE, eine pro Zeile)</label>
    <textarea name="ingredients_de" placeholder="300 g Mehl&#10;2 Eier"><?php echo isset($editingDe['ingredients']) ? e(implode("\n", $editingDe['ingredients'])) : ''; ?></textarea>
    <label>Werkzeug (DE, eine pro Zeile)</label>
    <textarea name="utensils_de" placeholder="Pfanne&#10;Kochtopf"><?php echo isset($editingDe['utensils']) ? e(implode("\n", $editingDe['utensils'])) : ''; ?></textarea>
    <label>Schritte (DE, eine pro Zeile)</label>
    <textarea name="steps_de" placeholder="Backofen vorheizen...&#10;Teig kneten..."><?php echo isset($editingDe['steps']) ? e(implode("\n", $editingDe['steps'])) : ''; ?></textarea>

    <label><input type="checkbox" name="featured" value="1" <?php echo !empty($editing['featured']) ? 'checked' : ''; ?>> Mark as featured</label>
    <label><input type="checkbox" name="coming_soon" value="1" <?php echo !empty($editing['coming_soon']) ? 'checked' : ''; ?>> Mark as coming soon (name & image only)</label>

    <button type="submit" class="button" style="width: fit-content;"><?php echo $editing ? 'Save changes' : 'Save recipe'; ?></button>
  </form>

  <div class="list">
    <h2>Existing recipes (<?php echo count($allRecipes); ?>)</h2>
    <?php if (empty($allRecipes)): ?>
      <p>No recipes yet.</p>
    <?php else: ?>
      <?php foreach ($allRecipes as $r): ?>
        <?php $display = localize_recipe($r, 'en'); ?>
        <div class="list-item">
          <div>
            <strong><?php echo e($display['title'] ?? $r['slug']); ?></strong>
            <span class="pill"><?php echo e($display['category'] ?? ''); ?></span>
            <?php if (!empty($r['featured'])): ?><span class="pill">Featured</span><?php endif; ?>
            <?php if (!empty($r['coming_soon'])): ?><span class="pill">Coming soon</span><?php endif; ?>
          </div>
          <div style="display:flex; gap:8px; align-items:center;">
            <small><?php echo e($r['slug']); ?></small>
            <a class="button" href="/admin.php?edit=<?php echo urlencode($r['slug']); ?>" style="padding:8px 12px;">Edit</a>
            <form method="post" style="margin:0;" onsubmit="return confirm('Delete this recipe?');">
              <input type="hidden" name="action" value="delete">
              <input type="hidden" name="slug" value="<?php echo e($r['slug']); ?>">
              <button type="submit" class="button" style="padding:8px 12px;">Delete</button>
            </form>
          </div>
        </div>
      <?php endforeach; ?>
    <?php endif; ?>
  </div>
</body>
</html>
