<?php
require_once __DIR__ . '/vendor/autoload.php';
use App\Product;

// Basic HTTP auth using credentials from `.env` or environment variables.
// Note: in production replace with a proper auth system and HTTPS.
$envPath = __DIR__ . '/.env';
$env = file_exists($envPath) ? (parse_ini_file($envPath, INI_SCANNER_RAW) ?: []) : [];
$envAdminUser = getenv('ADMIN_USER');
$envAdminPass = getenv('ADMIN_PASS');
$adminUser = isset($env['ADMIN_USER']) ? (string)$env['ADMIN_USER'] : (($envAdminUser !== false) ? (string)$envAdminUser : 'admin');
$adminPass = isset($env['ADMIN_PASS']) ? (string)$env['ADMIN_PASS'] : (($envAdminPass !== false) ? (string)$envAdminPass : 'change-me');

if (!isset($_SERVER['PHP_AUTH_USER'])) {
  header('WWW-Authenticate: Basic realm="Admin Area"');
  header('HTTP/1.0 401 Unauthorized');
  echo 'Authentication required.';
  exit;
}
if (!hash_equals($adminUser, $_SERVER['PHP_AUTH_USER']) || !hash_equals($adminPass, $_SERVER['PHP_AUTH_PW'] ?? '')) {
  header('HTTP/1.0 403 Forbidden');
  echo 'Forbidden';
  exit;
}

// Very small admin: add products via a form
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = trim($_POST['title'] ?? '');
    $slug = trim($_POST['slug'] ?? '');
    $desc = trim($_POST['description'] ?? '');
    $price = (int)($_POST['price_cents'] ?? 0);
    $template = trim($_POST['template_file'] ?? '');
    $imageUrl = trim($_POST['image_url'] ?? '');
    if ($title && $slug && $price>0) {
        Product::create([
            'title'=>$title,
            'slug'=>$slug,
            'description'=>$desc,
            'price_cents'=>$price,
            'template_file'=>$template,
            'image_url'=>$imageUrl !== '' ? $imageUrl : null
        ]);
        header('Location: ' . (dirname($_SERVER['SCRIPT_NAME']) === '\\' ? '/admin.php' : dirname($_SERVER['SCRIPT_NAME']) . '/admin.php')); exit;
    }
}

$products = Product::all();
?>
<!doctype html>
<html lang="es">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Admin - Invitaciones</title>
  <style>
    :root {
      --bg: #f5efe6;
      --panel: #fffdf9;
      --line: #e7dac7;
      --text: #1f2933;
      --muted: #64748b;
      --accent: #b45309;
      --accent-2: #0f766e;
      --danger: #b91c1c;
      --shadow: 0 16px 32px rgba(46, 33, 16, 0.08);
      --radius: 14px;
    }
    * { box-sizing: border-box; }
    body {
      margin: 0;
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
      color: var(--text);
      background:
        radial-gradient(circle at 15% 20%, rgba(180, 83, 9, 0.10), transparent 35%),
        radial-gradient(circle at 85% 0%, rgba(15, 118, 110, 0.12), transparent 30%),
        var(--bg);
      min-height: 100vh;
    }
    .wrap {
      max-width: 1024px;
      margin: 0 auto;
      padding: 28px 18px 48px;
    }
    .topbar {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 18px;
      gap: 12px;
      flex-wrap: wrap;
    }
    .title {
      margin: 0;
      font-size: 28px;
      line-height: 1.2;
      color: #7c2d12;
    }
    .chip {
      padding: 8px 12px;
      border-radius: 999px;
      background: rgba(15, 118, 110, 0.12);
      color: #0b5f57;
      font-size: 13px;
      font-weight: 600;
    }
    .grid {
      display: grid;
      grid-template-columns: 1.1fr 1fr;
      gap: 18px;
    }
    .card {
      background: var(--panel);
      border: 1px solid var(--line);
      border-radius: var(--radius);
      box-shadow: var(--shadow);
      padding: 18px;
    }
    .card h2 {
      margin: 0 0 12px;
      font-size: 18px;
      color: #7c2d12;
    }
    .field {
      display: grid;
      gap: 6px;
      margin-bottom: 12px;
    }
    label {
      font-size: 13px;
      color: var(--muted);
      font-weight: 600;
    }
    input, textarea {
      width: 100%;
      border: 1px solid #d8c7af;
      background: #fff;
      border-radius: 10px;
      padding: 11px 12px;
      font-size: 14px;
      color: var(--text);
      outline: none;
      transition: border-color .2s, box-shadow .2s;
    }
    textarea {
      min-height: 92px;
      resize: vertical;
    }
    input:focus, textarea:focus {
      border-color: var(--accent-2);
      box-shadow: 0 0 0 3px rgba(15, 118, 110, 0.15);
    }
    .btn {
      border: 0;
      border-radius: 10px;
      padding: 11px 14px;
      background: linear-gradient(135deg, #b45309, #92400e);
      color: #fff;
      font-weight: 700;
      cursor: pointer;
      width: 100%;
    }
    .btn:hover { filter: brightness(1.05); }
    .list {
      display: grid;
      gap: 10px;
      margin: 0;
      padding: 0;
      list-style: none;
    }
    .item {
      border: 1px solid var(--line);
      border-radius: 10px;
      padding: 12px;
      background: #fffcf7;
      display: flex;
      justify-content: space-between;
      align-items: center;
      gap: 12px;
    }
    .name {
      margin: 0;
      font-size: 14px;
      font-weight: 700;
      color: #334155;
    }
    .price {
      margin: 3px 0 0;
      font-size: 13px;
      color: var(--muted);
    }
    .tag {
      white-space: nowrap;
      background: rgba(180, 83, 9, 0.12);
      color: #9a3412;
      border-radius: 8px;
      padding: 6px 8px;
      font-size: 12px;
      font-weight: 700;
    }
    .empty {
      border: 1px dashed #d8c7af;
      border-radius: 10px;
      padding: 14px;
      color: var(--muted);
      background: #fff;
      font-size: 14px;
    }
    @media (max-width: 900px) {
      .grid { grid-template-columns: 1fr; }
    }
  </style>
</head>
<body>
  <div class="wrap">
    <div class="topbar">
      <h1 class="title">Panel Admin de Invitaciones</h1>
      <div class="chip">Acceso protegido</div>
    </div>

    <div class="grid">
      <section class="card">
        <h2>Crear producto</h2>
        <form method="post">
          <div class="field">
            <label for="title">Titulo</label>
            <input id="title" name="title" required>
          </div>
          <div class="field">
            <label for="slug">Slug</label>
            <input id="slug" name="slug" required>
          </div>
          <div class="field">
            <label for="description">Descripcion</label>
            <textarea id="description" name="description"></textarea>
          </div>
          <div class="field">
            <label for="price_cents">Precio (cents)</label>
            <input id="price_cents" name="price_cents" type="number" min="1" required>
          </div>
          <div class="field">
            <label for="template_file">Template file (relative)</label>
            <input id="template_file" name="template_file" placeholder="designs/boda-floral.pen">
          </div>
          <div class="field">
            <label for="image_url">Image URL / ruta publica</label>
            <input id="image_url" name="image_url" placeholder="/assets/imagen1.png o https://...">
          </div>
          <button class="btn" type="submit">Guardar producto</button>
        </form>
      </section>

      <section class="card">
        <h2>Productos existentes (<?=count($products)?>)</h2>
        <?php if (empty($products)): ?>
          <div class="empty">No hay productos cargados todavia.</div>
        <?php else: ?>
          <ul class="list">
            <?php foreach($products as $p): ?>
              <li class="item">
                <div>
                  <p class="name"><?=htmlspecialchars($p['title'])?></p>
                  <p class="price">$<?=number_format($p['price_cents']/100,2)?> USD</p>
                  <?php if (!empty($p['image_url'])): ?>
                    <p class="price"><?=htmlspecialchars((string)$p['image_url'])?></p>
                  <?php endif; ?>
                </div>
                <span class="tag">#<?= (int)$p['id'] ?></span>
              </li>
            <?php endforeach; ?>
          </ul>
        <?php endif; ?>
      </section>
    </div>
  </div>
</body>
</html>
