<?php
$servername = "localhost";
$username = "lotto";
$password = "12Qwaszx**";
$dbname = "lotto";

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

if ($conn->connect_error) {
    echo json_encode(['success' => false, 'message' => 'Error de conexión: ' . $conn->connect_error]);
    exit;
}

$table = $_POST['table'] ?? '';
$year = $_POST['year'] ?? '';
$month = $_POST['month'] ?? '';
$day = $_POST['day'] ?? '';
$numbers = $_POST['numbers'] ?? [];

if (!$table || !$year || !$month || !$day || count($numbers) !== 6) {
    echo json_encode(['success' => false, 'message' => 'Datos incompletos: ' . json_encode($_POST)]);
    exit;
}

$sql = "INSERT INTO `$table` (`año`, `mes`, `dia`, `01`, `02`, `03`, `04`, `05`, `06`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
$stmt = $conn->prepare($sql);

if ($stmt) {
    $stmt->bind_param(
        "issiiiiii",
        $year,
        $month,
        $day,
        $numbers[0],
        $numbers[1],
        $numbers[2],
        $numbers[3],
        $numbers[4],
        $numbers[5]
    );

    if ($stmt->execute()) {
        echo json_encode(['success' => true, 'message' => 'Resultados guardados exitosamente.']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Error al guardar: ' . $stmt->error]);
    }
    $stmt->close();
} else {
    echo json_encode(['success' => false, 'message' => 'Error en la preparación: ' . $conn->error]);
}

$conn->close();
?>
