<?php
require_once 'db/config.php';

session_start();

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}

$user_id = $_SESSION['user_id'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['competition_id'])) {
        $competition_id = $_POST['competition_id'];

        $pdo = db();
        $stmt = $pdo->prepare('INSERT IGNORE INTO competition_participants (user_id, competition_id) VALUES (?, ?)');
        $stmt->execute([$user_id, $competition_id]);

        $_SESSION['success_message'] = 'You have successfully registered for the competition!';
        header('Location: competition.php?id=' . $competition_id);
        exit();
    } else {
        header('Location: competitions.php');
        exit();
    }
} else {
    header('Location: competitions.php');
    exit();
}
