<?php
require __DIR__ . '/connection.php';

$fileId = $_POST['file_id'] ?? '';
if (!$fileId) {
    echo json_encode(['ok'=>false,'error'=>"No se recibió file_id"]);
    exit;
}

$tableFinal = $fileId . "_corregido";

if (!preg_match('/^[a-zA-Z0-9_\-]+$/', $tableFinal)) {
    echo json_encode(['ok'=>false,'error'=>"Nombre de tabla inválido"]);
    exit;
}

$res = $conn->query("SELECT COUNT(*) AS total FROM `$tableFinal`");
if (!$res) {
    echo json_encode(['ok'=>false,'error'=>"Error consultando tabla: " . $conn->error]);
    exit;
}
$row = $res->fetch_assoc();
$totalUsuarios = intval($row['total']);

$amount_cents = $totalUsuarios * 5;

$stmt = $conn->prepare("
    INSERT INTO mp_payments (file_id, user_count, amount_cents, status)
    VALUES (?, ?, ?, 'pending')
    ON DUPLICATE KEY UPDATE
        user_count = VALUES(user_count),
        amount_cents = VALUES(amount_cents)
");
if (!$stmt) {
    echo json_encode(['ok'=>false,'error'=>"Error prepare: ".$conn->error]);
    exit;
}
$stmt->bind_param("sii", $fileId, $totalUsuarios, $amount_cents);
$stmt->execute();

echo json_encode(['ok'=>true, 'total'=>$totalUsuarios, 'amount_cents'=>$amount_cents]);
$conn->close();
?>
