<?php
declare(strict_types=1);
ini_set('display_errors', '1');
error_reporting(E_ALL);

date_default_timezone_set('UTC');

require_once 'config.php';

// 2) اکشن‌ها: افزودن، تغییر وضعیت، حذف
$flash = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'add') {
    $team_id   = (int)($_POST['team_id'] ?? 0);
    $team_name = trim($_POST['team_name'] ?? '');
    $league_id = (int)($_POST['league_id'] ?? 0);
    if ($team_id && $league_id && $team_name !== '') {
        $stmt = $db->prepare("INSERT IGNORE INTO featured_teams (team_id, team_name, league_id) VALUES (?, ?, ?)");
        $stmt->execute([$team_id, $team_name, $league_id]);
        $flash = '✅ تیم اضافه شد (یا از قبل وجود داشت).';
    } else {
        $flash = '❌ اطلاعات ورودی ناقص است.';
    }
}

if (isset($_GET['action'], $_GET['id']) && $_GET['action'] === 'toggle') {
    $id = (int)$_GET['id'];
    $db->exec("UPDATE featured_teams SET is_active = 1 - is_active WHERE id = {$id} LIMIT 1");
    header('Location: featured_teams.php'); exit;
}

if (isset($_GET['action'], $_GET['id']) && $_GET['action'] === 'delete') {
    $id = (int)$_GET['id'];
    $stmt = $db->prepare("DELETE FROM featured_teams WHERE id = ? LIMIT 1");
    $stmt->execute([$id]);
    header('Location: featured_teams.php'); exit;
}

// 3) جستجو اختیاری
$search = trim($_GET['q'] ?? '');
$params = [];
$sql = "SELECT id, team_id, team_name, league_id, is_active, created_at, updated_at
        FROM featured_teams";
if ($search !== '') {
    $sql .= " WHERE team_name LIKE :q OR team_id = :tid OR league_id = :lid";
    $params[':q'] = "%{$search}%";
    if (ctype_digit($search)) {
        $params[':tid'] = (int)$search;
        $params[':lid'] = (int)$search;
    } else {
        $params[':tid'] = -1;
        $params[':lid'] = -1;
    }
}
$sql .= " ORDER BY is_active DESC, league_id ASC, team_name ASC";

$stmt = $db->prepare($sql);
$stmt->execute($params);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

// 4) Helper: شمارش فعال/غیرفعال
$activeCount = 0; $inactiveCount = 0;
foreach ($rows as $r) { $r['is_active'] ? $activeCount++ : $inactiveCount++; }

function isFeaturedTeam(PDO $db, int $teamId): bool {
    $stmt = $db->prepare("SELECT 1 FROM featured_teams WHERE team_id = ? AND is_active = 1 LIMIT 1");
    $stmt->execute([$teamId]);
    return (bool)$stmt->fetchColumn();
}

function getFeaturedTeams(PDO $db): array {
    $stmt = $db->query("SELECT team_id, team_name, league_id FROM featured_teams WHERE is_active = 1");
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

?>
<!doctype html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>مدیریت تیم‌های منتخب</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css">
<style> body{background:#111;color:#eee} .card{background:#1a1b1e;border-radius:16px; box-shadow:0 10px 30px rgba(0,0,0,.3)} input,select{color:#111} a.btn{padding:.35rem .6rem;border-radius:.5rem;background:#2a2b2f} a.btn:hover{background:#34363b} </style>
</head>
<body class="p-4">
  <div class="max-w-5xl mx-auto">

    <h1 class="text-2xl font-bold mb-4">⚙️ Featured Teams Management</h1>

    <?php if ($flash): ?>
      <div class="mb-4 p-3 rounded bg-green-700 text-white"><?= htmlspecialchars($flash) ?></div>
    <?php endif; ?>

    <!-- نوار جستجو و آمار -->
    <div class="card p-4 mb-4">
      <form method="get" class="flex flex-col md:flex-row gap-3 items-center">
        <input name="q" value="<?= htmlspecialchars($search) ?>" class="px-3 py-2 rounded w-full md:w-1/2" placeholder="Search by Team Name or Team/League ID">
        <button class="px-4 py-2 rounded bg-blue-600 text-white">Search</button>
        <a href="featured_teams.php" class="ml-2 text-sm underline">Clear Filter</a>
        <div class="ml-auto text-sm opacity-80">Active: <?= $activeCount ?> | Inactive: <?= $inactiveCount ?></div>      </form>
    </div>

    <!-- فرم افزودن -->
    <div class="card p-4 mb-6">
      <h2 class="text-lg font-semibold mb-3">➕ Add New Featured Team</h2>
      <form method="post" class="grid grid-cols-1 md:grid-cols-4 gap-3">
        <input type="hidden" name="action" value="add">
        <div>
          <label class="text-sm opacity-80">Team ID</label>
          <input name="team_id" type="number" class="px-3 py-2 rounded w-full" required>
        </div>
        <div>
          <label class="text-sm opacity-80">Team Name</label>
          <input name="team_name" type="text" class="px-3 py-2 rounded w-full" required>
        </div>
        <div>
          <label class="text-sm opacity-80">League ID</label>
          <input name="league_id" type="number" class="px-3 py-2 rounded w-full" required>
        </div>
        <div class="flex items-end">
          <button class="w-full px-4 py-2 rounded bg-green-600 text-white">Add</button>
        </div>
      </form>
        <p class="text-xs mt-2 opacity-60">* If team_id already exists, insertion will be ignored.</p>
    </div>

    <!-- جدول -->
    <div class="card p-0 overflow-hidden">
      <div class="overflow-x-auto">
        <table class="min-w-full text-sm">
          <thead class="bg-gray-800">
            <tr>
              <th class="py-3 px-3 text-right">#</th>
              <th class="py-3 px-3 text-right">Team</th>
              <th class="py-3 px-3 text-right">Team ID</th>
              <th class="py-3 px-3 text-right">League ID</th>
              <th class="py-3 px-3 text-right">Status</th>
              <th class="py-3 px-3 text-right">Actions</th>
            </tr>
          </thead>
          <tbody>
            <?php if (!$rows): ?>
              <tr><td colspan="6" class="py-6 px-3 text-center opacity-70">List not Available.</td></tr>
            <?php else: foreach ($rows as $r): ?>
              <tr class="border-b border-gray-800">
                <td class="py-2 px-3"><?= (int)$r['id'] ?></td>
                <td class="py-2 px-3 font-semibold"><?= htmlspecialchars($r['team_name']) ?></td>
                <td class="py-2 px-3"><?= (int)$r['team_id'] ?></td>
                <td class="py-2 px-3"><?= (int)$r['league_id'] ?></td>
                <td class="py-2 px-3">
                  <?php if ($r['is_active']): ?>
                    <span class="px-2 py-1 rounded bg-green-700">Active</span>
                  <?php else: ?>
                    <span class="px-2 py-1 rounded bg-gray-600">Inactive</span>
                  <?php endif; ?>
                </td>
                <td class="py-2 px-3 space-x-2 space-x-reverse">
                  <a class="btn" href="featured_teams.php?action=toggle&id=<?= (int)$r['id'] ?>">Toggle Status</a>
                  <a class="btn" href="featured_teams.php?action=delete&id=<?= (int)$r['id'] ?>" onclick="return confirm('حذف شود؟')">Clear</a>
                </td>
              </tr>
            <?php endforeach; endif; ?>
          </tbody>
        </table>
      </div>
    </div>

    <!-- لینک برگشت به داشبورد -->
    <div class="mt-4">
        <a href="dashboard.php" class="text-blue-600 hover:text-blue-800 font-medium">⬅️ Back to Dashboard</a>    </div>
  </div>
</body>
</html>
