<?php
session_start();

// Incluir el archivo de configuración para la base de datos
include('config.php');

// Si el usuario no está autenticado, redirigir al login
if (!isset($_SESSION['user_id'])) {
    header("Location: login.html");
    exit();
}

// Obtener el saldo del usuario
$stmt = $pdo->prepare("SELECT balance FROM users WHERE id = :id");
$stmt->execute(['id' => $_SESSION['user_id']]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

// Procesar las transacciones
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['deposit'])) {
        // Depósito
        $amount = $_POST['amount'];
        $stmt = $pdo->prepare("UPDATE users SET balance = balance + :amount WHERE id = :id");
        $stmt->execute(['amount' => $amount, 'id' => $_SESSION['user_id']]);
        header("Location: dashboard.php");
        exit();
    } elseif (isset($_POST['withdraw'])) {
        // Retiro
        $amount = $_POST['amount'];
        if ($amount <= $user['balance']) {
            $stmt = $pdo->prepare("UPDATE users SET balance = balance - :amount WHERE id = :id");
            $stmt->execute(['amount' => $amount, 'id' => $_SESSION['user_id']]);
            header("Location: dashboard.php");
            exit();
        } else {
            echo "No tienes suficiente saldo.";
        }
    }
}
?>

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="dashboard-container">
        <h2>Bienvenido, <?php echo htmlspecialchars($_SESSION['email']); ?></h2>
        <p>Saldo disponible: $<?php echo number_format($user['balance'], 2); ?></p>

        <h3>Realizar Transacciones</h3>

        <!-- Depósito -->
        <form action="dashboard.php" method="POST">
            <label for="deposit">Depósito</label>
            <input type="number" id="deposit" name="amount" required>
            <button type="submit" name="deposit">Depositar</button>
        </form>

        <!-- Retiro -->
        <form action="dashboard.php" method="POST">
            <label for="withdraw">Retiro</label>
            <input type="number" id="withdraw" name="amount" required>
            <button type="submit" name="withdraw">Retirar</button>
        </form>
    </div>
</body>
</html>
