<?php
// checkout_dummy.php
session_start();
require_once '../../config.php';

// 1. Validar parámetros iniciales
if (!isset($_POST['invoice_id']) || !isset($_POST['gateway'])) {
    $_SESSION['alert_message'] = ['type' => 'danger', 'message' => 'Parámetros de pago no válidos.'];
    header("Location: index.php");
    exit();
}

$invoice_id = intval($_POST['invoice_id']);
$gateway    = $_POST['gateway'];

//$routeValue = ($gateway === 'mercadopago') ? 'MercadoPago' : 'PayU';
// Tomar el valor real de la pasarela seleccionada
$routeValue = isset($_POST['gateway']) ? $_POST['gateway'] : 'desconocido';
// 2. Consultar factura
$sql = "SELECT i.*, t.name AS ticketname, t.expire_days, t.occasions
        FROM invoices i 
        LEFT JOIN tickets t ON i.ticket_id = t.id
        WHERE i.id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $invoice_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    $_SESSION['alert_message'] = ['type' => 'danger', 'message' => 'Factura no encontrada.'];
    header("Location: index.php");
    exit();
}
$invoice = $result->fetch_assoc();
$stmt->close();

// 3. Validar estado
if ($invoice['status'] !== 'unpaid') {
    $_SESSION['alert_message'] = ['type' => 'warning', 'message' => 'La factura ya fue pagada o no está disponible.'];
    header("Location: index.php");
    exit();
}

// 4. Procesar acción
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action']) && $_POST['action'] === 'pay') {

        // 🔹 Marcar factura como pagada
        $update = $conn->prepare("UPDATE invoices SET status = 'paid', route = ? WHERE id = ?");
        $update->bind_param("si", $routeValue, $invoice_id);
        $update->execute();
        $update->close();

        // 🔹 Diferenciar: Ticket vs Productos
        if (!empty($invoice['ticket_id'])) {
            // ===== Caso 1: Ticket =====
            $ticketname = $invoice['ticketname'];
            $expiredate = date('Y-m-d', strtotime("+{$invoice['expire_days']} days"));
            $insert = $conn->prepare("INSERT INTO current_tickets (userid, ticketname, expiredate, opportunities, invoice_id) 
                                      VALUES (?, ?, ?, ?, ?)");
            $insert->bind_param("issii", $invoice['userid'], $ticketname, $expiredate, $invoice['occasions'], $invoice_id);
            $insert->execute();
            $insert->close();

            // 3. Actualizar balance del usuario con el precio del plan
            $updateBalance = $conn->prepare("UPDATE users SET profile_balance = profile_balance + ? WHERE userid = ?");
            $updateBalance->bind_param("di", $invoice['price'], $invoice['userid']);
            $updateBalance->execute();
            $updateBalance->close();

            echo "<p>DEBUG: Plan pagado correctamente, balance actualizado (+{$invoice['price']}).</p>";

        } else {
            // ===== Caso 2: Productos =====
            // 🔹 Migrar productos desde temp_cart → invoice_items
           // Si es factura de productos (no ticket_id)
    
            $sqlC = "SELECT tc.product_id, tc.quantity, p.price 
                    FROM temp_cart tc 
                    INNER JOIN products p ON tc.product_id = p.id
                    WHERE tc.user_id = ?";
            $stmtC = $conn->prepare($sqlC);
            $stmtC->bind_param("i", $invoice['userid']);
            $stmtC->execute();
            $cartItems = $stmtC->get_result();

            while ($item = $cartItems->fetch_assoc()) {
                $subtotal = $item['price'] * $item['quantity'];

                // Insertar detalle en invoice_items
                $insItem = $conn->prepare("INSERT INTO invoice_items (invoice_id, product_id, quantity, price) 
                                        VALUES (?, ?, ?, ?)");
                $insItem->bind_param("iiid", $invoice_id, $item['product_id'], $item['quantity'], $item['price']);
                $insItem->execute();
                $insItem->close();

                // Actualizar stock
                $updStock = $conn->prepare("UPDATE products SET stock = stock - ? WHERE id = ?");
                $updStock->bind_param("ii", $item['quantity'], $item['product_id']);
                $updStock->execute();
                $updStock->close();
            }
            $stmtC->close();

            // Vaciar carrito del usuario
            $delCart = $conn->prepare("DELETE FROM temp_cart WHERE user_id = ?");
            $delCart->bind_param("i", $invoice['user_id']);
            $delCart->execute();
            $delCart->close();
        }

        $_SESSION['alert_message'] = ['type' => 'success', 'message' => 'Pago realizado con éxito usando ' . $routeValue];
        header("Location: index.php");
        exit();
    }

    if (isset($_POST['action']) && $_POST['action'] === 'cancel') {
        $_SESSION['alert_message'] = ['type' => 'info', 'message' => 'El pago fue cancelado.'];
        header("Location: index.php");
        exit();
    }
}

// 5. Vista previa
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Confirmar Pago</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light">
<div class="container py-5">
    <div class="card shadow">
        <div class="card-header bg-primary text-white">
            <h4 class="mb-0">Confirmación de Pago</h4>
        </div>
        <div class="card-body">
            <p><strong>Factura #:</strong> <?php echo htmlspecialchars($invoice['id']); ?></p>
            <p><strong>Descripción:</strong> <?php echo htmlspecialchars($invoice['name']); ?></p>
            <p><strong>Monto:</strong> <?php echo htmlspecialchars($invoice['price']); ?> <?php echo htmlspecialchars($currency); ?></p>
            <p><strong>Método de Pago Seleccionado:</strong> <?php echo htmlspecialchars($routeValue); ?></p>

            <form method="POST">
                <input type="hidden" name="invoice_id" value="<?php echo htmlspecialchars($invoice_id); ?>">
                <input type="hidden" name="gateway" value="<?php echo htmlspecialchars($gateway); ?>">
                <div class="d-flex gap-3 mt-3">
                    <button type="submit" name="action" value="pay" class="btn btn-success">Pagar</button>
                    <button type="submit" name="action" value="cancel" class="btn btn-danger">Cancelar</button>
                </div>
            </form>
        </div>
    </div>
</div>
</body>
</html>
