<?php

require __DIR__ . '/../bootstrap.php';

use KeyLair\Auth;
use KeyLair\Csrf;
use KeyLair\Database;
use KeyLair\Helpers;
use KeyLair\AuditLog;
use KeyLair\I18n;

Auth::requireLogin();
$admin = Auth::user();
$isDemo = $admin['role'] === 'demo';
$pdo = Database::connection();

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['form_action'] ?? '') === 'delete') {
    Auth::requireEditAccess();
    Csrf::requireValid();
    $id = (int) ($_POST['id'] ?? 0);
    $stmt = $pdo->prepare('SELECT cover_image_path FROM products WHERE id = :id');
    $stmt->execute(['id' => $id]);
    $product = $stmt->fetch();
    if ($product) {
        $pdo->prepare('DELETE FROM products WHERE id = :id')->execute(['id' => $id]);
        if ($product['cover_image_path']) {
            @unlink(ROOT_PATH . '/public/uploads/products/' . $product['cover_image_path']);
        }
        AuditLog::log($admin['id'], 'product_deleted', (string) $id);
    }
    Helpers::redirect('products.php');
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['form_action'] ?? '') === 'update_status') {
    Auth::requireEditAccess();
    Csrf::requireValid();
    $id = (int) ($_POST['id'] ?? 0);
    $status = in_array($_POST['status'] ?? '', ['draft', 'active', 'archived'], true) ? $_POST['status'] : 'draft';
    $pdo->prepare('UPDATE products SET status = :status WHERE id = :id')->execute(['status' => $status, 'id' => $id]);
    AuditLog::log($admin['id'], 'product_status_changed', $id . ':' . $status);
    Helpers::redirect('products.php');
}

$products = $pdo->query(
    'SELECT p.*,
        (SELECT COUNT(*) FROM `keys` k WHERE k.product_id = p.id) AS key_count,
        (SELECT COUNT(*) FROM `keys` k WHERE k.product_id = p.id AND k.status = "available") AS available_count
     FROM products p ORDER BY p.created_at DESC'
)->fetchAll();

$pageTitle = I18n::t('products.page_title');
$activeNav = 'products';
require __DIR__ . '/includes/layout_header.php';
?>
<div class="topbar">
  <h1><?= Helpers::e(I18n::t('products.page_title')) ?></h1>
  <?php if (Auth::canEdit()): ?>
  <a href="product_form.php" class="campaign-select" style="text-decoration:none; color:var(--signal); border-color:var(--signal-dim);">+ <?= Helpers::e(I18n::t('products.new_product')) ?></a>
  <?php elseif ($isDemo): ?>
  <span class="campaign-select" style="text-decoration:none; color:var(--text-faint); border-color:var(--signal-dim); cursor:not-allowed;">+ <?= Helpers::e(I18n::t('products.new_product')) ?></span>
  <?php endif; ?>
</div>

<div class="panel">
  <?php if (empty($products)): ?>
    <p style="color:var(--text-faint); font-size:13px;"><?= Helpers::e(I18n::t('products.empty_state')) ?></p>
  <?php else: ?>
  <table>
    <thead><tr><th></th><th><?= Helpers::e(I18n::t('products.col_name')) ?></th><th><?= Helpers::e(I18n::t('products.col_status')) ?></th><th><?= Helpers::e(I18n::t('products.col_keys_available_total')) ?></th><th></th></tr></thead>
    <tbody>
      <?php foreach ($products as $p): ?>
      <tr>
        <td style="width:52px;">
          <div style="width:44px; aspect-ratio:16/9; border-radius:6px; overflow:hidden; background:var(--bg-void); border:1px solid var(--line);">
            <?php if ($p['cover_image_path']): ?>
              <img src="/uploads/products/<?= Helpers::e($p['cover_image_path']) ?>" alt="" style="width:100%;height:100%;object-fit:cover;">
            <?php endif; ?>
          </div>
        </td>
        <td class="creator" data-label="<?= Helpers::e(I18n::t('products.col_name')) ?>"><?= Helpers::e($p['name']) ?></td>
        <td data-label="<?= Helpers::e(I18n::t('products.col_status')) ?>">
          <?php if (Auth::canEdit() || $isDemo): ?>
          <form method="post" style="display:inline;">
            <?= Csrf::field() ?>
            <input type="hidden" name="form_action" value="update_status">
            <input type="hidden" name="id" value="<?= (int) $p['id'] ?>">
            <fieldset <?= $isDemo ? 'disabled' : '' ?> style="border:0; margin:0; padding:0; display:inline;">
              <select name="status" class="status-select status-<?= Helpers::e($p['status']) ?>" onchange="this.form.submit()">
                <option value="draft" <?= $p['status'] === 'draft' ? 'selected' : '' ?>><?= Helpers::e(I18n::t('products.status_draft')) ?></option>
                <option value="active" <?= $p['status'] === 'active' ? 'selected' : '' ?>><?= Helpers::e(I18n::t('products.status_active')) ?></option>
                <option value="archived" <?= $p['status'] === 'archived' ? 'selected' : '' ?>><?= Helpers::e(I18n::t('products.status_archived')) ?></option>
              </select>
            </fieldset>
          </form>
          <?php else: ?>
          <span class="plat-tag" style="<?= $p['status'] !== 'active' ? 'background:rgba(136,144,164,0.12); color:var(--text-muted);' : '' ?>">
            <?= Helpers::e(I18n::t('products.status_' . $p['status'])) ?>
          </span>
          <?php endif; ?>
        </td>
        <td class="time-cell" data-label="<?= Helpers::e(I18n::t('products.col_keys_available_total')) ?>"><?= (int) $p['available_count'] ?> / <?= (int) $p['key_count'] ?></td>
        <td>
          <?php if (Auth::canEdit() || $isDemo): ?>
          <?php if (Auth::canEdit()): ?>
          <a href="product_form.php?id=<?= (int) $p['id'] ?>" style="color:var(--signal); font-size:12px; text-decoration:none; margin-right:10px;"><?= Helpers::e(I18n::t('products.edit')) ?></a>
          <?php else: ?>
          <span style="color:var(--text-faint); font-size:12px; text-decoration:none; margin-right:10px; cursor:not-allowed;"><?= Helpers::e(I18n::t('products.edit')) ?></span>
          <?php endif; ?>
          <fieldset <?= $isDemo ? 'disabled' : '' ?> style="border:0; margin:0; padding:0; display:inline;">
          <form method="post" style="display:inline;" onsubmit="return confirm(<?= json_encode(I18n::t('products.delete_confirm_js'), JSON_HEX_APOS | JSON_HEX_QUOT) ?>);">
            <?= Csrf::field() ?>
            <input type="hidden" name="form_action" value="delete">
            <input type="hidden" name="id" value="<?= (int) $p['id'] ?>">
            <button type="submit" style="background:none; border:none; color:var(--danger); font-size:12px; cursor:pointer; padding:0;"><?= Helpers::e(I18n::t('products.delete')) ?></button>
          </form>
          </fieldset>
          <?php endif; ?>
        </td>
      </tr>
      <?php endforeach; ?>
    </tbody>
  </table>
  <?php endif; ?>
</div>

<?php require __DIR__ . '/includes/layout_footer.php'; ?>
