<?php
require_once __DIR__ . '/../common/config.php';
require_once __DIR__ . '/common/auth-check.php';
require_once __DIR__ . '/common/header.php';
require_once __DIR__ . '/common/sidebar.php';
$editId = (int)($_GET['edit'] ?? 0);
$filter = sanitize($_GET['cat'] ?? '');
$edit = null;
if ($editId) {
    $st=$pdo->prepare("SELECT * FROM games WHERE id=?"); $st->execute([$editId]); $edit=$st->fetch();
}
$packages = [];
if ($edit) {
    $st=$pdo->prepare("SELECT * FROM packages WHERE game_id=? ORDER BY sort_order ASC"); $st->execute([$editId]); $packages=$st->fetchAll();
}
$cats = $pdo->query("SELECT * FROM categories ORDER BY sort_order ASC")->fetchAll();
if (!$cats) {
    $cats = [
        ['slug'=>'flash','name'=>'FLASH SALE'],
        ['slug'=>'hot','name'=>'HOT PRODUCT'],
        ['slug'=>'pes','name'=>'All PES Football'],
        ['slug'=>'others','name'=>'Others'],
        ['slug'=>'subscription','name'=>'Others Subscription'],
    ];
}
$sql = "SELECT * FROM games ORDER BY sort_order ASC, id DESC";
$games = $pdo->query($sql)->fetchAll();
if ($filter) $games = array_values(array_filter($games, fn($g)=>($g['category']??'')===$filter));
$editPk = null;
if (!empty($_GET['pk'])) {
    foreach ($packages as $pk) if ((int)$pk['id']===(int)$_GET['pk']) $editPk=$pk;
}
?>
<div class="admin-page">
<header class="h-16 bg-white border-b flex items-center justify-between px-6">
  <h2 class="text-xl font-bold">Products</h2>
  <a href="product.php" class="bg-orange-500 text-white px-4 py-2 rounded-lg text-sm font-bold">Add product</a>
</header>
<main class="flex-1 overflow-y-auto bg-adminbg p-6 space-y-6">
  <div class="flex flex-wrap gap-2">
    <a href="product.php" class="px-3 py-1.5 rounded-full text-xs font-bold <?= !$filter?'bg-orange-500 text-white':'bg-white border' ?>">All</a>
    <?php foreach ($cats as $c): ?>
      <a href="product.php?cat=<?= urlencode($c['slug']) ?>" class="px-3 py-1.5 rounded-full text-xs font-bold <?= $filter===$c['slug']?'bg-orange-500 text-white':'bg-white border' ?>"><?= htmlspecialchars($c['name']) ?></a>
    <?php endforeach; ?>
  </div>

  <div class="bg-white rounded-xl border p-6">
    <h3 class="font-bold mb-4"><?= $edit ? 'Edit product' : 'Add product' ?></h3>
    <form action="../ajax/admin-action.php" method="POST" enctype="multipart/form-data" class="ajax-form grid md:grid-cols-2 gap-4">
      <input type="hidden" name="action" value="save_game">
      <input type="hidden" name="id" value="<?= (int)($edit['id'] ?? 0) ?>">
      <div><label class="text-xs font-bold">Name</label><input name="name" required value="<?= htmlspecialchars($edit['name'] ?? '') ?>" class="w-full border rounded-lg px-3 py-2 text-sm"></div>
      <div><label class="text-xs font-bold">Slug</label><input name="slug" value="<?= htmlspecialchars($edit['slug'] ?? '') ?>" class="w-full border rounded-lg px-3 py-2 text-sm"></div>
      <div>
        <label class="text-xs font-bold">Type</label>
        <select name="type" class="w-full border rounded-lg px-3 py-2 text-sm">
          <option value="uid" <?= (($edit['type']??'')==='uid')?'selected':'' ?>>Diamond / UID topup</option>
          <option value="voucher" <?= (($edit['type']??'')==='voucher')?'selected':'' ?>>Voucher</option>
        </select>
      </div>
      <div>
        <label class="text-xs font-bold">Category</label>
        <select name="category" class="w-full border rounded-lg px-3 py-2 text-sm">
          <?php foreach ($cats as $c): ?>
          <option value="<?= htmlspecialchars($c['slug']) ?>" <?= (($edit['category']??'')===$c['slug'])?'selected':'' ?>><?= htmlspecialchars($c['name']) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="md:col-span-2">
        <label class="text-xs font-bold">Thumbnail</label>
        <?php if (!empty($edit['thumbnail'])): ?><img src="<?= htmlspecialchars($edit['thumbnail']) ?>" class="w-16 h-16 rounded mb-2 object-cover"><?php endif; ?>
        <input type="file" name="thumbnail_file" accept="image/*" class="w-full text-sm mb-2">
        <input name="thumbnail" value="<?= htmlspecialchars($edit['thumbnail'] ?? '') ?>" class="w-full border rounded-lg px-3 py-2 text-sm" placeholder="or paste image URL">
      </div>
      <div><label class="text-xs font-bold">Stock note</label><input name="stock_note" value="<?= htmlspecialchars($edit['stock_note'] ?? '') ?>" class="w-full border rounded-lg px-3 py-2 text-sm"></div>
      <div><label class="text-xs font-bold">Sort</label><input type="number" name="sort_order" value="<?= htmlspecialchars($edit['sort_order'] ?? 0) ?>" class="w-full border rounded-lg px-3 py-2 text-sm"></div>
      <div>
        <label class="text-xs font-bold">Status</label>
        <select name="status" class="w-full border rounded-lg px-3 py-2 text-sm">
          <option value="active">ON</option>
          <option value="inactive" <?= (($edit['status']??'')==='inactive')?'selected':'' ?>>OFF</option>
        </select>
      </div>
      <div class="md:col-span-2"><label class="text-xs font-bold">Rules</label><textarea name="rules" rows="3" class="w-full border rounded-lg px-3 py-2 text-sm"><?= htmlspecialchars($edit['rules'] ?? '') ?></textarea></div>
      <div class="md:col-span-2"><button class="bg-orange-500 text-white font-bold px-5 py-2 rounded-lg">Save product</button></div>
    </form>

    <?php if ($edit): ?>
    <div class="mt-8 border-t pt-4">
      <h4 class="font-bold mb-3">Prices / packages / discount</h4>
      <form action="../ajax/admin-action.php" method="POST" class="ajax-form grid md:grid-cols-6 gap-2 mb-4">
        <input type="hidden" name="action" value="save_package">
        <input type="hidden" name="game_id" value="<?= $editId ?>">
        <input type="hidden" name="id" value="<?= (int)($editPk['id']??0) ?>">
        <input name="name" required value="<?= htmlspecialchars($editPk['name']??'') ?>" placeholder="Package name" class="border rounded-lg px-3 py-2 text-sm md:col-span-2">
        <input name="old_price" type="number" step="0.01" value="<?= htmlspecialchars($editPk['old_price']??'') ?>" placeholder="Old price" class="border rounded-lg px-3 py-2 text-sm">
        <input name="price" type="number" step="0.01" required value="<?= htmlspecialchars($editPk['price']??'') ?>" placeholder="Sell price" class="border rounded-lg px-3 py-2 text-sm">
        <input name="discount" type="number" step="0.01" value="<?= htmlspecialchars($editPk['discount']??'') ?>" placeholder="Discount %" class="border rounded-lg px-3 py-2 text-sm">
        <button class="bg-slate-800 text-white font-bold px-3 py-2 rounded-lg text-sm"><?= $editPk?'Update price':'Add price' ?></button>
      </form>
      <table class="w-full text-sm">
        <thead class="text-xs text-gray-500 uppercase"><tr><th class="py-2 text-left">Package</th><th>Old</th><th>Price</th><th>Off</th><th>Status</th><th></th></tr></thead>
        <?php foreach ($packages as $pk): ?>
        <tr class="border-b">
          <td class="py-2"><?= htmlspecialchars($pk['name']) ?></td>
          <td class="py-2 text-center text-gray-400"><?= !empty($pk['old_price'])? $pk['old_price'] : '-' ?></td>
          <td class="py-2 text-center font-bold text-orange-600"><?= $pk['price'] ?></td>
          <td class="py-2 text-center"><?= !empty($pk['discount'])? $pk['discount'].'%' : '-' ?></td>
          <td class="py-2 text-center"><?= ($pk['status']??'active')==='active'?'ON':'OFF' ?></td>
          <td class="py-2 text-right space-x-2">
            <a href="?edit=<?= $editId ?>&pk=<?= $pk['id'] ?>" class="text-blue-600 font-bold">Edit</a>
            <button onclick="adminPost({action:'toggle_package',id:'<?= $pk['id'] ?>'})" class="text-amber-600 font-bold">On/Off</button>
            <button onclick="adminPost({action:'delete_package',id:'<?= $pk['id'] ?>'})" class="text-red-500 font-bold">Delete</button>
          </td>
        </tr>
        <?php endforeach; ?>
      </table>
    </div>
    <?php endif; ?>
  </div>

  <div class="bg-white rounded-xl border overflow-hidden">
    <table class="w-full text-left">
      <thead class="bg-gray-50 text-xs uppercase text-gray-500 border-b">
        <tr><th class="p-4">Icon</th><th class="p-4">Product</th><th class="p-4">Category</th><th class="p-4">Type</th><th class="p-4">Status</th><th class="p-4 text-right">Action</th></tr>
      </thead>
      <tbody class="text-sm divide-y">
      <?php foreach ($games as $g): ?>
        <tr>
          <td class="p-3"><img src="<?= htmlspecialchars($g['thumbnail']??'') ?>" class="w-12 h-12 rounded-lg object-cover"></td>
          <td class="p-3 font-bold"><?= htmlspecialchars($g['name']) ?></td>
          <td class="p-3"><span class="text-xs bg-orange-50 text-orange-600 px-2 py-1 rounded font-bold"><?= htmlspecialchars($g['category']) ?></span></td>
          <td class="p-3 uppercase text-xs font-bold"><?= htmlspecialchars($g['type']) ?></td>
          <td class="p-3"><?= ($g['status']??'')==='active' ? '<span class="text-green-600 font-bold text-xs">ON</span>' : '<span class="text-red-500 font-bold text-xs">OFF</span>' ?></td>
          <td class="p-3 text-right space-x-1">
            <a href="?edit=<?= $g['id'] ?>" class="inline-block bg-blue-50 text-blue-600 p-2 rounded"><i class="fa-solid fa-pen-to-square"></i></a>
            <button onclick="adminPost({action:'toggle_game',id:'<?= $g['id'] ?>'})" class="bg-amber-50 text-amber-600 p-2 rounded"><i class="fa-solid fa-power-off"></i></button>
            <button onclick="adminPost({action:'delete_game',id:'<?= $g['id'] ?>'})" class="bg-red-50 text-red-600 p-2 rounded"><i class="fa-solid fa-trash"></i></button>
          </td>
        </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</main>
</div>
<?php require_once __DIR__ . '/common/footer.php'; ?>
