<?php
header('Content-Type: application/json');

$servername = "localhost";
$username = "jardtqtg_souteze";
$password = "souteze+2025";
$dbname = "jardtqtg_souteze";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die(json_encode(["error" => "Connection failed: " . $conn->connect_error]));
}

// Create table if not exists
$tableQuery = "CREATE TABLE IF NOT EXISTS competitions (
    id INT AUTO_INCREMENT PRIMARY KEY,
    store VARCHAR(255),
    productName VARCHAR(255),
    endDate VARCHAR(255),
    products VARCHAR(255),
    minPayment FLOAT,
    firstPrize VARCHAR(255),
    secondPrize VARCHAR(255),
    thirdPrize VARCHAR(255),
    link VARCHAR(255)
)";
$conn->query($tableQuery);

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $sql = "SELECT * FROM competitions";
    $result = $conn->query($sql);
    $competitions = [];
    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
            $competitions[] = $row;
        }
    }
    echo json_encode($competitions);
} elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = json_decode(file_get_contents('php://input'), true);
    $store = $conn->real_escape_string($data['store']);
    $productName = $conn->real_escape_string($data['productName']);
    $endDate = $conn->real_escape_string($data['endDate']);
    $products = $conn->real_escape_string($data['products']);
    $minPayment = $data['minPayment'];
    $firstPrize = $conn->real_escape_string($data['firstPrize']);
    $secondPrize = $conn->real_escape_string($data['secondPrize']);
    $thirdPrize = $conn->real_escape_string($data['thirdPrize']);
    $link = $conn->real_escape_string($data['link']);

    $sql = "INSERT INTO competitions (store, productName, endDate, products, minPayment, firstPrize, secondPrize, thirdPrize, link) VALUES ('$store', '$productName', '$endDate', '$products', $minPayment, '$firstPrize', '$secondPrize', '$thirdPrize', '$link')";
    if ($conn->query($sql) === TRUE) {
        echo json_encode(["message" => "Competition saved"]);
    } else {
        echo json_encode(["error" => "Error: " . $sql . "<br>" . $conn->error]);
    }
}

$conn->close();
?>