<?php
// manage_categories.php
// Create / hide / show / delete categories that the bot uses in /start.
//
// NOTE: Make sure your `categories` table has:
//   slug VARCHAR, title VARCHAR, sort_order INT, is_hidden TINYINT(1) DEFAULT 0

session_start();
if (!isset($_SESSION['admin'])) { header('Location: index.php'); exit; }

require __DIR__ . '/../db.php';
$config = require __DIR__ . '/../config.php';

$msg = '';
$err = '';

// CSRF-lite token
if (!isset($_SESSION['mc_token'])) $_SESSION['mc_token'] = bin2hex(random_bytes(8));
$token = $_SESSION['mc_token'];

/* ONE-CLICK remover (separate small form, NOT nested inside add form) */
if ($_SERVER['REQUEST_METHOD'] === 'POST'
    && isset($_POST['remove_defaults'])
    && isset($_POST['token']) && $_POST['token'] === $token) {

    try {
        // backup before delete
        $pdo->exec("DROP TABLE IF EXISTS backup_accounts_defaults");
        $pdo->exec("CREATE TABLE backup_accounts_defaults AS
            SELECT a.* FROM accounts a
            JOIN categories c ON a.category_id = c.id
            WHERE c.slug IN ('fresh','silver','gold')");
        $pdo->exec("DROP TABLE IF EXISTS backup_orders_defaults");
        $pdo->exec("CREATE TABLE backup_orders_defaults AS
            SELECT o.* FROM orders o
            JOIN accounts a ON o.account_id = a.id
            JOIN categories c ON a.category_id = c.id
            WHERE c.slug IN ('fresh','silver','gold')");
        $pdo->exec("DROP TABLE IF EXISTS backup_categories_defaults");
        $pdo->exec("CREATE TABLE backup_categories_defaults AS
            SELECT * FROM categories WHERE slug IN ('fresh','silver','gold')");

        $pdo->beginTransaction();
        $delOrders = $pdo->prepare("DELETE o FROM orders o
            JOIN accounts a ON o.account_id = a.id
            JOIN categories c ON a.category_id = c.id
            WHERE c.slug IN ('fresh','silver','gold')");
        $delOrders->execute();

        $delAccounts = $pdo->prepare("DELETE a FROM accounts a
            JOIN categories c ON a.category_id = c.id
            WHERE c.slug IN ('fresh','silver','gold')");
        $delAccounts->execute();

        $delCats = $pdo->prepare("DELETE FROM categories WHERE slug IN ('fresh','silver','gold')");
        $delCats->execute();

        $pdo->commit();
        $msg = "✅ Defaults removed and backups saved (backup_*_defaults tables created).";
    } catch (PDOException $e) {
        if ($pdo->inTransaction()) $pdo->rollBack();
        $err = "❌ Failed to remove defaults: " . $e->getMessage();
    }
}

/* ADD category */
if ($_SERVER['REQUEST_METHOD'] === 'POST'
    && isset($_POST['action']) && $_POST['action'] === 'add'
    && isset($_POST['token']) && $_POST['token'] === $token) {

    $slug = trim($_POST['slug'] ?? '');
    $title = trim($_POST['title'] ?? '');
    $order = (int)($_POST['sort_order'] ?? 0);

    if ($slug === '' || $title === '') {
        $err = "⚠️ Slug and title are required.";
    } elseif (!preg_match('/^[a-z0-9_\-]+$/i', $slug)) {
        $err = "⚠️ Slug can only contain letters, numbers, hyphens and underscores.";
    } else {
        try {
            $stmt = $pdo->prepare("INSERT INTO categories (slug, title, sort_order, is_hidden) VALUES (?, ?, ?, 0)");
            $stmt->execute([$slug, $title, $order]);
            $msg = "✅ Category added.";
        } catch (PDOException $e) {
            $err = "❌ DB Error: " . $e->getMessage();
        }
    }
}

/* HIDE category */
if (isset($_GET['hide']) && isset($_GET['token']) && $_GET['token'] === $token) {
    $id = (int)$_GET['hide'];
    try {
        $stmt = $pdo->prepare("UPDATE categories SET is_hidden = 1 WHERE id = ?");
        $stmt->execute([$id]);
        $msg = "🙈 Category hidden from bot.";
        header('Location: manage_categories.php'); exit;
    } catch (PDOException $e) {
        $err = "❌ DB Error: " . $e->getMessage();
    }
}

/* SHOW category */
if (isset($_GET['show']) && isset($_GET['token']) && $_GET['token'] === $token) {
    $id = (int)$_GET['show'];
    try {
        $stmt = $pdo->prepare("UPDATE categories SET is_hidden = 0 WHERE id = ?");
        $stmt->execute([$id]);
        $msg = "✅ Category shown in bot.";
        header('Location: manage_categories.php'); exit;
    } catch (PDOException $e) {
        $err = "❌ DB Error: " . $e->getMessage();
    }
}

/* Delete (keep accounts) */
if (isset($_GET['delete']) && isset($_GET['token']) && $_GET['token'] === $token) {
    $id = (int)$_GET['delete'];
    try {
        $stmt = $pdo->prepare("SELECT slug, title FROM categories WHERE id = ?");
        $stmt->execute([$id]);
        $cat = $stmt->fetch();
        if (!$cat) {
            $err = "❌ Category not found.";
        } else {
            try {
                $u = $pdo->prepare("UPDATE accounts SET category_id = NULL WHERE category_id = ?");
                $u->execute([$id]);
            } catch (PDOException $e) {
                $err = "⚠️ Couldn't unlink accounts automatically. Check accounts.category_id FK. DB says: " . $e->getMessage();
            }
            $stmt2 = $pdo->prepare("DELETE FROM categories WHERE id = ?");
            $stmt2->execute([$id]);
            $msg = "🗂️ Category '" . htmlspecialchars($cat['title']) . "' deleted. Accounts were kept.";
            header('Location: manage_categories.php'); exit;
        }
    } catch (PDOException $e) {
        $err = "❌ DB Error: " . $e->getMessage();
    }
}

/* Force delete (category + its accounts + their orders) */
if (isset($_GET['force_delete']) && isset($_GET['token']) && $_GET['token'] === $token) {
    $id = (int)$_GET['force_delete'];
    if (!isset($_GET['confirm']) || $_GET['confirm'] !== 'yes') {
        $err = "⚠️ Force delete needs confirmation. Click Force Delete → Confirm.";
    } else {
        try {
            $pdo->beginTransaction();
            $delOrders = $pdo->prepare("DELETE o FROM orders o JOIN accounts a ON o.account_id = a.id WHERE a.category_id = ?");
            $delOrders->execute([$id]);
            $delAccounts = $pdo->prepare("DELETE FROM accounts WHERE category_id = ?");
            $delAccounts->execute([$id]);
            $delCat = $pdo->prepare("DELETE FROM categories WHERE id = ?");
            $delCat->execute([$id]);
            $pdo->commit();
            $msg = "🧨 Force delete completed: category, its accounts and related orders were removed.";
            header('Location: manage_categories.php'); exit;
        } catch (PDOException $e) {
            $pdo->rollBack();
            $err = "❌ Force delete failed: " . $e->getMessage();
        }
    }
}

/* Fetch visible + hidden categories */
try {
    $cats = $pdo->query("
        SELECT c.*, (SELECT COUNT(*) FROM accounts a WHERE a.category_id = c.id) AS accounts_count
        FROM categories c
        WHERE c.is_hidden = 0
        ORDER BY c.sort_order, c.id
    ")->fetchAll();

    $hidden = $pdo->query("
        SELECT c.*, (SELECT COUNT(*) FROM accounts a WHERE a.category_id = c.id) AS accounts_count
        FROM categories c
        WHERE c.is_hidden = 1
        ORDER BY c.sort_order, c.id
    ")->fetchAll();
} catch (PDOException $e) {
    $cats = $hidden = [];
    $err = "❌ DB Error fetching categories: " . $e->getMessage();
}

?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Manage Categories — Admin</title>
<meta name="viewport" content="width=device-width,initial-scale=1">

<style>
  :root{
    --bg:#050510;
    --card:#111119;
    --card-soft:#171724;
    --accent:#6c5ce7;
    --accent-soft:#a29bfe;
    --danger:#ff7675;
    --text-main:#ffffff;
    --text-muted:#a4a7b3;
    --border-soft:rgba(255,255,255,0.08);
  }
  *{box-sizing:border-box}
  body{
    margin:0;
    font-family:system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;
    background:radial-gradient(circle at top,#1b1b33 0,#050510 55%);
    color:var(--text-main);
  }
  .shell{
    max-width:960px;
    margin:0 auto;
    padding:18px 14px 40px;
  }
  .top-bar{
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:12px;
    margin-bottom:16px;
  }
  .title-wrap h1{
    margin:0;
    font-size:22px;
    letter-spacing:.02em;
  }
  .subtitle{
    margin-top:4px;
    font-size:13px;
    color:var(--text-muted);
  }

  /* top-right pill container + buttons */
  .nav{
    display:inline-flex;
    align-items:center;
    gap:8px;
    padding:4px;
    border-radius:999px;
    background:rgba(0,0,0,0.55);
    backdrop-filter:blur(12px);
  }
  .nav a{
    text-decoration:none;
    padding:8px 14px;
    border-radius:999px;
    font-size:13px;
    font-weight:600;
    display:inline-flex;
    align-items:center;
    gap:6px;
    background:linear-gradient(135deg,#ffffff,#f3f1ff);
    color:#181820;
    box-shadow:0 6px 18px rgba(0,0,0,0.32);
    border:1px solid rgba(255,255,255,0.85);
    transition:transform .12s ease, box-shadow .12s ease, background .12s ease;
  }
  .nav a:hover{
    transform:translateY(-1px);
    box-shadow:0 10px 26px rgba(0,0,0,0.38);
  }
  .nav a:active{
    transform:translateY(0);
    box-shadow:0 3px 10px rgba(0,0,0,0.25);
  }

  .card{
    background:rgba(15,15,28,0.96);
    border-radius:18px;
    padding:18px 16px 20px;
    border:1px solid var(--border-soft);
    box-shadow:0 18px 50px rgba(0,0,0,0.5);
  }
  .section-title{
    margin:0 0 8px;
    font-size:15px;
  }
  .muted{color:var(--text-muted);font-size:13px}

  .notice{padding:10px 12px;border-radius:10px;font-size:13px;margin-bottom:10px}
  .notice.ok{background:rgba(46,213,115,0.12);border:1px solid rgba(46,213,115,0.6);color:#b7ffce}
  .notice.err{background:rgba(255,71,87,0.12);border:1px solid rgba(255,71,87,0.7);color:#ffd4d8}

  .add-box{
    background:var(--card-soft);
    border-radius:14px;
    padding:14px 12px 14px;
    border:1px solid var(--border-soft);
    margin-bottom:16px;
  }
  .add-form{
    display:flex;
    flex-direction:column;
    gap:10px;
    margin-top:8px;
  }
  label{font-size:13px;color:#d8d8e6;margin-bottom:4px;display:block}
  .input{
    width:100%;
    padding:9px 10px;
    border-radius:10px;
    border:1px solid rgba(255,255,255,0.06);
    background:#0d0d18;
    color:var(--text-main);
    font-size:14px;
  }
  .input:focus{outline:none;border-color:var(--accent);box-shadow:0 0 0 1px rgba(108,92,231,0.6);}
  .row{
    display:flex;
    flex-wrap:wrap;
    gap:10px;
  }
  .row > div{flex:1 1 150px}

  .btn{
    border:none;
    border-radius:999px;
    padding:9px 14px;
    font-size:14px;
    font-weight:600;
    cursor:pointer;
    display:inline-flex;
    align-items:center;
    gap:6px;
    text-decoration:none;
  }
  .btn-primary{
    background:linear-gradient(120deg,var(--accent),var(--accent-soft));
    color:white;
    box-shadow:0 8px 22px rgba(108,92,231,0.55);
  }
  .btn-danger{
    background:linear-gradient(120deg,#ff7675,#ff9675);
    color:white;
    box-shadow:0 8px 22px rgba(255,118,117,0.45);
  }
  .btn-soft{
    background:rgba(255,255,255,0.06);
    color:var(--text-main);
    border:1px solid rgba(255,255,255,0.12);
  }

  .table-wrap{
    margin-top:6px;
    border-radius:14px;
    overflow:auto;
    border:1px solid var(--border-soft);
    background:rgba(10,10,20,0.95);
  }
  table{width:100%;border-collapse:collapse;min-width:640px}
  thead{background:rgba(15,15,28,1);}
  th,td{padding:9px 12px;font-size:13px;text-align:left;color:#f5f5ff}
  tbody tr:nth-child(odd){background:rgba(20,20,35,0.9);}
  tbody tr:nth-child(even){background:rgba(16,16,30,0.9);}
  .pill{
    display:inline-flex;
    padding:3px 9px;
    border-radius:999px;
    font-size:12px;
    background:rgba(255,255,255,0.06);
    color:#e0e0ff;
  }
  .title-cell{max-width:240px;word-break:break-word}
  .actions-cell{min-width:160px}
  .actions{
    display:flex;
    flex-wrap:wrap;
    gap:6px;
    justify-content:flex-end;
  }
  .tiny{font-size:12px}

  @media (max-width:720px){
    .top-bar{flex-direction:column;align-items:flex-start}
    .nav{align-self:flex-end}
  }
</style>
</head>
<body>
<div class="shell">
  <div class="top-bar">
    <div class="title-wrap">
      <h1>Manage Categories</h1>
      <div class="subtitle">Create multiple categories. Users will see all visible ones in the bot.</div>
    </div>
    <div class="nav">
      <a href="accounts_list.php">📂 Accounts</a>
      <a href="upload_account.php">📤 Upload</a>
    </div>
  </div>

  <div class="card">
    <?php if ($msg): ?>
      <div class="notice ok"><?= htmlspecialchars($msg) ?></div>
    <?php endif; ?>
    <?php if ($err): ?>
      <div class="notice err"><?= htmlspecialchars($err) ?></div>
    <?php endif; ?>

    <!-- ADD CATEGORY -->
    <div class="add-box">
      <h2 class="section-title">➕ Add Category</h2>
      <p class="muted tiny">Slug is internal. Title is what users see in Telegram.</p>

      <form method="post" class="add-form">
        <input type="hidden" name="action" value="add">
        <input type="hidden" name="token" value="<?= htmlspecialchars($token) ?>">

        <div class="row">
          <div>
            <label>Slug</label>
            <input class="input" type="text" name="slug" placeholder="e.g. gold_accounts" required>
          </div>
          <div>
            <label>Title</label>
            <input class="input" type="text" name="title" placeholder="e.g. Gold Accounts" required>
          </div>
          <div style="max-width:140px">
            <label>Sort order (lower = shown first)</label>
            <input class="input" type="number" name="sort_order" value="0">
          </div>
        </div>

        <div style="margin-top:8px;display:flex;flex-wrap:wrap;gap:8px;align-items:center">
          <button class="btn btn-primary" type="submit">Save Category</button>
          <a href="accounts_list.php" class="btn btn-soft tiny">Manage accounts</a>
        </div>
      </form>
    </div>

    <!-- REMOVE DEFAULTS SMALL FORM -->
    <form method="post" style="margin-bottom:14px">
      <input type="hidden" name="token" value="<?= htmlspecialchars($token) ?>">
      <input type="hidden" name="remove_defaults" value="1">
      <button class="btn btn-danger tiny" type="submit"
        onclick="return confirm('Backup + remove default categories fresh/silver/gold and their accounts/orders?');">
        💣 Remove default categories (fresh / silver / gold)
      </button>
    </form>

    <!-- VISIBLE CATEGORIES -->
    <div style="margin-top:10px">
      <h2 class="section-title">Visible Categories</h2>
      <?php if (empty($cats)): ?>
        <p class="muted tiny">No visible categories. Add one above.</p>
      <?php else: ?>
        <div class="table-wrap">
          <table>
            <thead>
              <tr>
                <th>#</th>
                <th>Slug</th>
                <th>Title</th>
                <th>Sort</th>
                <th>Accounts</th>
                <th class="actions-cell">Actions</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($cats as $c): ?>
                <tr>
                  <td><?= (int)$c['id'] ?></td>
                  <td><span class="pill"><?= htmlspecialchars($c['slug']) ?></span></td>
                  <td class="title-cell"><?= htmlspecialchars($c['title']) ?></td>
                  <td><?= (int)$c['sort_order'] ?></td>
                  <td><?= (int)$c['accounts_count'] ?></td>
                  <td class="actions-cell">
                    <div class="actions">
                      <a class="btn btn-soft tiny"
                         href="?hide=<?= (int)$c['id'] ?>&token=<?= htmlspecialchars($token) ?>"
                         onclick="return confirm('Hide <?= addslashes($c['title']) ?> from bot?');">🙈 Hide</a>

                      <a class="btn btn-soft tiny"
                         href="?delete=<?= (int)$c['id'] ?>&token=<?= htmlspecialchars($token) ?>"
                         onclick="return confirm('Delete category <?= addslashes($c['title']) ?>? Accounts will stay but without category.');">🗑️ Delete</a>

                      <a class="btn btn-danger tiny"
                         href="?force_delete=<?= (int)$c['id'] ?>&confirm=yes&token=<?= htmlspecialchars($token) ?>"
                         onclick="return confirm('FORCE delete <?= addslashes($c['title']) ?> and ALL its accounts & orders? This cannot be undone.');">💥 Force Delete</a>
                    </div>
                  </td>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      <?php endif; ?>
    </div>

    <!-- HIDDEN CATEGORIES -->
    <div style="margin-top:16px">
      <h2 class="section-title">Hidden Categories</h2>
      <?php if (empty($hidden)): ?>
        <p class="muted tiny">No hidden categories.</p>
      <?php else: ?>
        <div class="table-wrap">
          <table>
            <thead>
              <tr>
                <th>#</th>
                <th>Slug</th>
                <th>Title</th>
                <th>Accounts</th>
                <th class="actions-cell">Actions</th>
              </tr>
            </thead>
            <tbody>
            <?php foreach ($hidden as $h): ?>
              <tr>
                <td><?= (int)$h['id'] ?></td>
                <td><span class="pill"><?= htmlspecialchars($h['slug']) ?></span></td>
                <td class="title-cell"><?= htmlspecialchars($h['title']) ?></td>
                <td><?= (int)$h['accounts_count'] ?></td>
                <td class="actions-cell">
                  <div class="actions">
                    <a class="btn btn-primary tiny"
                       href="?show=<?= (int)$h['id'] ?>&token=<?= htmlspecialchars($token) ?>"
                       onclick="return confirm('Show <?= addslashes($h['title']) ?> in bot again?');">👁️ Show</a>

                    <a class="btn btn-soft tiny"
                       href="?delete=<?= (int)$h['id'] ?>&token=<?= htmlspecialchars($token) ?>"
                       onclick="return confirm('Delete category <?= addslashes($h['title']) ?>? Accounts will stay but without category.');">🗑️ Delete</a>

                    <a class="btn btn-danger tiny"
                       href="?force_delete=<?= (int)$h['id'] ?>&confirm=yes&token=<?= htmlspecialchars($token) ?>"
                       onclick="return confirm('FORCE delete <?= addslashes($h['title']) ?> and ALL its accounts & orders? This cannot be undone.');">💥 Force Delete</a>
                  </div>
                </td>
              </tr>
            <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      <?php endif; ?>
    </div>

    <p class="muted tiny" style="margin-top:10px">
      Tip: Hidden categories are not shown to users, but their accounts still exist. Use “Show” to bring them back into the bot.
    </p>
  </div>
</div>
</body>
</html>