<?php
session_start();
if (!defined('BASE_PATH')) { define('BASE_PATH', dirname(dirname(__DIR__))); }
require_once BASE_PATH . '/database/config.php';
require_once BASE_PATH . '/database/connection.php';
require_once BASE_PATH . '/modules/shared/helpers.php';
if (!isset($_SESSION['client_id'])) { header('Location: ' . module_url('client_portal/login.php')); exit(); }
if (!isset($_SESSION['pending_deposit'])) { header('Location: ' . module_url('client_portal/deposit.php')); exit(); }

$page_title = 'Pago con Big4pay';
$module = 'transactions';
$action = 'payment';

$clientId = (int)$_SESSION['client_id'];
$pendingDeposit = $_SESSION['pending_deposit'];
$db = Database::getInstance();
$pdo = $db->getConnection();

// Obtener información de la cuenta
$stmtAcc = $pdo->prepare("SELECT account_number, currency, account_type FROM client_accounts WHERE id = ? AND client_id = ? LIMIT 1");
$stmtAcc->execute([$pendingDeposit['account_id'], $clientId]);
$account = $stmtAcc->fetch();

$message = null; $error = null;

// Procesar confirmación de pago
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['confirm_payment'])) {
    try {
        $pdo->beginTransaction();
        
        // Registrar transacción
        $stmtTx = $pdo->prepare("INSERT INTO client_transactions (client_id, type, amount, currency, reference, notes, created_at) VALUES (?,?,?,?,?, ?, NOW())");
        $stmtTx->execute([
            $clientId, 
            'deposit', 
            $pendingDeposit['amount'], 
            $account['currency'], 
            uniqid('B4P-'), 
            'Pago procesado con Big4pay'
        ]);

        // Actualizar balance de la cuenta (CRM)
        $stmtUp = $pdo->prepare("UPDATE client_accounts SET balance = balance + ? WHERE id = ?");
        $stmtUp->execute([$pendingDeposit['amount'], $pendingDeposit['account_id']]);

        // Sincronizar saldo con la cuenta de trading correspondiente (WebTrader)
        if (!empty($account['account_number'])) {
            $stmtTa = $pdo->prepare("UPDATE trading_accounts SET balance = balance + ?, equity = equity + ?, free_margin = free_margin + ?, updated_at = NOW() WHERE client_id = ? AND account_number = ?");
            $stmtTa->execute([$pendingDeposit['amount'], $pendingDeposit['amount'], $pendingDeposit['amount'], $clientId, $account['account_number']]);
        }

        $pdo->commit();
        
        // Limpiar sesión
        unset($_SESSION['pending_deposit']);
        
        $message = 'Pago procesado exitosamente con Big4pay.';
        
        // Redirigir al dashboard después de 3 segundos
        header('refresh:3;url=' . module_url('client_portal/dashboard.php'));
        
    } catch (Throwable $e) {
        $pdo->rollBack();
        $error = 'Error procesando el pago: ' . $e->getMessage();
    }
}

// Procesar cancelación
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['cancel_payment'])) {
    unset($_SESSION['pending_deposit']);
    header('Location: ' . module_url('client_portal/deposit.php'));
    exit();
}

ob_start();
?>
    <div class="section-header">
        <h2 class="section-title"><i class="fas fa-credit-card"></i> Pago con Big4pay</h2>
    </div>

    <?php if ($message): ?>
        <div class="alert alert-success">
            <?php echo htmlspecialchars($message); ?>
            <br><small>Serás redirigido al dashboard en unos segundos...</small>
        </div>
    <?php elseif ($error): ?>
        <div class="alert alert-error"><?php echo htmlspecialchars($error); ?></div>
    <?php endif; ?>

    <section class="support-card">
        <div class="payment-summary">
            <h3><i class="fas fa-info-circle"></i> Resumen del Pago</h3>
            <div class="payment-details">
                <div class="detail-row">
                    <span class="label">Cuenta:</span>
                    <span class="value"><?php echo htmlspecialchars($account['account_number']); ?> (<?php echo ucfirst($account['account_type']); ?>)</span>
                </div>
                <div class="detail-row">
                    <span class="label">Monto:</span>
                    <span class="value amount"><?php echo number_format($pendingDeposit['amount'], 2); ?> <?php echo strtoupper($account['currency']); ?></span>
                </div>
                <div class="detail-row">
                    <span class="label">Método:</span>
                    <span class="value">Big4pay</span>
                </div>
                <div class="detail-row">
                    <span class="label">Token:</span>
                    <span class="value token"><?php echo substr($pendingDeposit['access_token'], 0, 20); ?>...</span>
                </div>
            </div>
        </div>

        <?php if (!$message && !$error): ?>
        <div class="payment-simulation">
            <div class="alert alert-info">
                <i class="fas fa-info-circle"></i>
                <strong>Simulación de Big4pay</strong><br>
                Esta es una simulación del proceso de pago. En un entorno real, aquí se mostraría la interfaz de Big4pay para completar el pago.
            </div>
            
            <form method="post" class="payment-form">
                <div class="form-actions">
                    <button class="client-action-btn deposit" type="submit" name="confirm_payment">
                        <i class="fas fa-check"></i> Confirmar Pago
                    </button>
                    <button class="client-action-btn secondary" type="submit" name="cancel_payment">
                        <i class="fas fa-times"></i> Cancelar
                    </button>
                </div>
            </form>
        </div>
        <?php endif; ?>
    </section>

    <style>
    .payment-summary {
        background: #f8f9fa;
        border: 1px solid #e9ecef;
        border-radius: 8px;
        padding: 1.5rem;
        margin-bottom: 1.5rem;
    }
    
    .payment-summary h3 {
        margin: 0 0 1rem 0;
        color: #495057;
        font-size: 1.1rem;
    }
    
    .payment-details {
        display: flex;
        flex-direction: column;
        gap: 0.75rem;
    }
    
    .detail-row {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0.5rem 0;
        border-bottom: 1px solid #e9ecef;
    }
    
    .detail-row:last-child {
        border-bottom: none;
    }
    
    .detail-row .label {
        font-weight: 600;
        color: #6c757d;
    }
    
    .detail-row .value {
        font-weight: 500;
    }
    
    .detail-row .value.amount {
        color: #28a745;
        font-size: 1.1rem;
        font-weight: 700;
    }
    
    .detail-row .value.token {
        font-family: monospace;
        font-size: 0.9rem;
        color: #6c757d;
    }
    
    .payment-simulation {
        text-align: center;
    }
    
    .payment-form .form-actions {
        display: flex;
        gap: 1rem;
        justify-content: center;
        margin-top: 1.5rem;
    }
    </style>
<?php
$content = ob_get_clean();
include __DIR__ . '/layout.php';
?>
