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

header("Content-Type: application/json; charset=UTF-8");

$data = json_decode(file_get_contents("php://input"), true);

$userId = intval($data['user_id'] ?? 0);
$pitch = trim($data['pitch'] ?? '');

if ($userId <= 0 || empty($pitch)) {
    http_response_code(400);
    echo json_encode(["status" => "error", "message" => "All fields are required."]);
    exit();
}

try {
    $db = getDBConnection();
    
    // Check if user already applied
    $stmt = $db->prepare("SELECT id FROM contestants WHERE user_id = ?");
    $stmt->execute([$userId]);
    if ($stmt->fetch()) {
        echo json_encode(["status" => "success", "message" => "Application already submitted."]);
        exit();
    }

    $stmt = $db->prepare("INSERT INTO contestants (user_id, pitch, status) VALUES (?, ?, 'pending')");
    $stmt->execute([$userId, $pitch]);

    echo json_encode(["status" => "success", "message" => "Contestant application submitted successfully."]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(["status" => "error", "message" => $e->getMessage()]);
}
