<?php
/**
 * Admin: list all door configurations (saved from storefront + DB).
 */
require __DIR__ . '/config.php';
require_once __DIR__ . '/admin_config_helpers.php';

 header_remove('X-Frame-Options');
header('Content-Security-Policy: frame-ancestors https://admin.shopify.com https://*.myshopify.com');

function h($v) { return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }

$statusFilter = $_GET['status'] ?? '';
if ($statusFilter) {
    $stmt = $pdo->prepare("SELECT * FROM door_configurations WHERE status = ? ORDER BY created_at DESC");
    $stmt->execute([$statusFilter]);
} else {
    $stmt = $pdo->query("SELECT * FROM door_configurations ORDER BY created_at DESC");
}
$configs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$statusLabels = [
    'draft' => 'Draft',
    'in_progress' => 'In progress',
    'awaiting_customer' => 'Awaiting customer',
    'finalized' => 'Finalized',
    'ordered' => 'Ordered',
    'archived' => 'Archived',
];
$admin_current_nav = 'filter';
$admin_app_title = 'Door Configurator';
$list_error = isset($_GET['error']) ? trim((string)$_GET['error']) : '';
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Configurations · Door Configurator</title>
  <?php include __DIR__ . '/includes/admin_layout_styles.php'; ?>
</head>
<body>

  <main class="admin-main">
  <div class="admin-wrap">
    <h1 class="admin-page-title">Configurations</h1>
    <p class="admin-page-meta">Saved door configurations from the storefront. Filter by status or open one to edit.</p>
    <?php if ($list_error !== ''): ?>
    <div class="admin-alert admin-alert--error">
      <div><?= h($list_error) ?></div>
    </div>
    <?php endif; ?>

    <div class="admin-card">
      <p class="admin-card-title">Filter by status</p>
      <form method="get" class="admin-filter">
        <label for="status-select" class="admin-label">Status</label>
        <select id="status-select" name="status" class="admin-select" onchange="this.form.submit()">
          <option value="">All statuses</option>
          <?php foreach (['draft','in_progress','awaiting_customer','finalized','ordered','archived'] as $s): ?>
            <option value="<?= h($s) ?>" <?= $statusFilter === $s ? 'selected' : '' ?>><?= h($statusLabels[$s] ?? $s) ?></option>
          <?php endforeach; ?>
        </select>
      </form>
    </div>

    <div class="admin-card">
      <p class="admin-card-title">All configurations</p>
      <div class="admin-table-wrap">
        <table class="admin-table">
          <thead>
            <tr>
              <th>ID</th>
              <th>Product</th>
              <th>Email</th>
              <th>Status</th>
              <th>Base price</th>
              <th>Applied price</th>
              <th>Selected options</th>
              <th>Created</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($configs as $c):
              $opts = json_decode($c['options_json'], true) ?: [];
              $productTitle = $opts['_product_title'] ?? '';
              $productImage = $opts['_product_image_url'] ?? '';
              $pillClass = 'admin-pill--' . $c['status'];
            ?>
              <tr>
                <td><a href="../admin/configuration_detail.php?id=<?= h($c['id']) ?>">#<?= h($c['id']) ?></a></td>
                <td>
                  <div class="admin-product-cell">
                    <?php if ($productImage): ?>
                      <img src="<?= h($productImage) ?>" alt="">
                    <?php endif; ?>
                    <span class="admin-product-name" title="<?= h($productTitle) ?>"><?= h($productTitle) ?: '—' ?></span>
                  </div>
                </td>
                <td><?= h($c['customer_email']) ?></td>
                <td><span class="admin-pill <?= h($pillClass) ?>"><?= h($statusLabels[$c['status']] ?? $c['status']) ?></span></td>
                <td>$<?= h(number_format($c['base_price'], 2)) ?></td>
                <td class="admin-money">$<?= h(number_format(admin_get_applied_unit_price($opts, (float)$c['base_price'], (float)$c['computed_price']), 2)) ?></td>
                <td class="admin-date">
                  <?php
                    $optsOut = [];
                    foreach ($opts as $ok => $ov) {
                      if (is_string($ok) && strlen($ok) && $ok[0] === '_') continue;
                      if (is_array($ov)) $optsOut[] = $ok . ': ' . implode(', ', array_map('strval', $ov));
                      else $optsOut[] = $ok . ': ' . (string)$ov;
                    }
                    echo h(implode('; ', $optsOut));
                  ?>
                </td>
                <td class="admin-date"><?= h($c['created_at']) ?></td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
      <?php if (empty($configs)): ?>
        <div class="admin-empty">
          <p><?= $statusFilter ? 'No configurations with this status.' : 'No configurations yet. Customers can save configurations from the door product page.' ?></p>
        </div>
      <?php endif; ?>
    </div>
  </div>
  </main>
</body>
</html>
