<?php
// competitions.php
// Ensure DB config loaded BEFORE using db()
require_once __DIR__ . '/db/config.php';

// Start session if not already (header will also try, but safe to ensure)
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// get PDO connection via helper
$pdo = db();

// fetch competitions - prepared statement, safe
try {
    $stmt = $pdo->prepare("SELECT id, title, description, start_date, end_date, registration_link FROM competitions ORDER BY start_date DESC");
    $stmt->execute();
    $competitions = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    // If query fails, show friendly message (we enabled display_errors during debug)
    die("Database query failed: " . htmlspecialchars($e->getMessage()));
}

// include header (will not start a new session because header uses safe check)
include __DIR__ . '/includes/header.php';
?>

<h2>Competitions</h2>

<?php if (empty($competitions)): ?>
  <p>No competitions right now. Check back later.</p>
<?php else: ?>
  <table style="width:100%; border-collapse:collapse;" border="1" cellpadding="8">
    <thead style="background:#0b8c9f; color:#fff;">
      <tr>
        <th style="text-align:left; width:30%;">Title</th>
        <th style="text-align:left; width:40%;">Description</th>
        <th style="text-align:center; width:15%;">Start</th>
        <th style="text-align:center; width:15%;">End</th>
      </tr>
    </thead>
    <tbody>
      <?php foreach ($competitions as $c): ?>
        <tr>
          <td><?php echo htmlspecialchars($c['title']); ?></td>
          <td><?php echo nl2br(htmlspecialchars($c['description'])); ?></td>
          <td style="text-align:center;"><?php echo htmlspecialchars(date('Y-m-d', strtotime($c['start_date']))); ?></td>
          <td style="text-align:center;"><?php echo htmlspecialchars(date('Y-m-d', strtotime($c['end_date']))); ?></td>
        </tr>
      <?php endforeach; ?>
    </tbody>
  </table>
<?php endif; ?>

<?php
// optional footer close (if you want to keep layout)
echo "</div></body></html>";
