<?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(); }

$page_title = 'Retiro';
$module = 'transactions';
$action = 'withdraw';

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

$stmtAcc = $pdo->prepare("SELECT id, account_number, currency, account_type, balance FROM client_accounts WHERE client_id = ? AND status = 'active' ORDER BY created_at ASC");
$stmtAcc->execute([$clientId]);
$accounts = $stmtAcc->fetchAll();

$message = null; $error = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $accountId = (int)($_POST['account_id'] ?? 0);
    $amount = (float)($_POST['amount'] ?? 0);
    $method = trim($_POST['method'] ?? 'bank');

    if ($accountId <= 0 || $amount <= 0) {
        $error = 'Selecciona una cuenta y un monto válido.';
    } else {
        $stmtOne = $pdo->prepare("SELECT id, account_number, currency, balance FROM client_accounts WHERE id = ? AND client_id = ? LIMIT 1");
        $stmtOne->execute([$accountId, $clientId]);
        $acc = $stmtOne->fetch();
        if (!$acc) { $error = 'Cuenta no encontrada.'; }
        else {
            $currency = $acc['currency'] ?? 'USD';
            $currentBalance = (float)$acc['balance'];
            if ($amount > $currentBalance) {
                $error = 'Saldo insuficiente para realizar el retiro.';
            } else {
                $pdo->beginTransaction();
                try {
                    $stmtTx = $pdo->prepare("INSERT INTO client_transactions (client_id, type, amount, currency, reference, notes, created_at) VALUES (?,?,?,?,?, ?, NOW())");
                    $stmtTx->execute([$clientId, 'withdrawal', $amount, $currency, uniqid('WD-'), $method]);

                    $stmtUp = $pdo->prepare("UPDATE client_accounts SET balance = balance - ? WHERE id = ?");
                    $stmtUp->execute([$amount, $accountId]);

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

                    $pdo->commit();
                    $message = 'Retiro registrado correctamente.';
                } catch (Throwable $e) {
                    $pdo->rollBack();
                    $error = 'Error registrando el retiro.';
                }
            }
        }
    }
}

ob_start();
?>
    <div class="section-header">
        <h2 class="section-title"><i class="fas fa-arrow-up"></i> Nuevo Retiro</h2>
    </div>

    <?php if ($message): ?>
        <div class="alert alert-success"><?php echo htmlspecialchars($message); ?></div>
    <?php elseif ($error): ?>
        <div class="alert alert-error"><?php echo htmlspecialchars($error); ?></div>
    <?php endif; ?>

    <section class="support-card">
        <form method="post" class="ticket-form">
            <div class="form-grid">
                <div class="form-group">
                    <label for="account_id">Cuenta</label>
                    <select id="account_id" name="account_id" required>
                        <option value="">Selecciona una cuenta</option>
                        <?php foreach ($accounts as $a): ?>
                            <option value="<?php echo (int)$a['id']; ?>" <?php echo ((int)($_GET['account_id'] ?? 0) === (int)$a['id']) ? 'selected' : ''; ?>>
                                <?php echo strtoupper($a['currency']) . ' · #' . htmlspecialchars($a['account_number']) . ' · ' . ucfirst($a['account_type']) . ' · Saldo: ' . number_format((float)$a['balance'], 2); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label for="amount">Monto</label>
                    <input type="number" id="amount" name="amount" step="0.01" min="0.01" required />
                </div>
                <div class="form-group">
                    <label for="method">Método</label>
                    <select id="method" name="method" required>
                        <option value="bank">Transferencia bancaria</option>
                        <option value="card">Tarjeta</option>
                        <option value="crypto">Cripto</option>
                    </select>
                </div>
            </div>
            <div class="form-actions">
                <button class="client-action-btn withdraw" type="submit"><i class="fas fa-arrow-up"></i> Retirar</button>
                <a class="client-action-btn secondary" href="<?php echo module_url('client_portal/dashboard.php'); ?>">Cancelar</a>
            </div>
        </form>
    </section>
<?php
$content = ob_get_clean();
include __DIR__ . '/layout.php';
?>
