<?php
require '../includes/db.php';
require 'includes/admin_auth.php';

$admin_id = $_SESSION['admin_id'];

// All users list for dropdown
$users = $pdo->query("SELECT id, name, email FROM users ORDER BY name")->fetchAll();

$selected_user_id = isset($_POST['user_id']) ? intval($_POST['user_id']) : null;
$user_currencies = [];
$user_default_currency = '';
$user_rates = [];

// If user selected, fetch their currencies + default
if ($selected_user_id) {
    // Get user's default currency
    $stmt = $pdo->prepare("SELECT currency FROM users WHERE id = ?");
    $stmt->execute([$selected_user_id]);
    $user_default_currency = strtolower($stmt->fetchColumn());

    // Get user's enabled currencies with pay-in rates
    $stmt = $pdo->prepare("SELECT currency_code, payin_rate FROM user_currencies WHERE user_id = ?");
    $stmt->execute([$selected_user_id]);
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $code = strtolower($row['currency_code']);
        $user_currencies[] = $code;
        $user_rates[$code] = floatval($row['payin_rate']);
    }
}

// Handle Pay-In
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['amount'], $_POST['currency'])) {
    $user_id = intval($_POST['user_id']);
    $input_currency = strtolower(trim($_POST['currency']));
    $amount = floatval($_POST['amount']);
    $admin_note = trim($_POST['admin_note']);
    $user_note = trim($_POST['user_note']);

    // Get user's default currency and pay-in fee
    $stmt = $pdo->prepare("SELECT currency, payin_fee FROM users WHERE id = ?");
    $stmt->execute([$user_id]);
    $userData = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$userData) {
        $error = "User not found.";
    } else {
        $default_currency = strtolower($userData['currency']);
        $fee_percent = floatval($userData['payin_fee']);

        // Get pay-in rate
        $stmt = $pdo->prepare("SELECT payin_rate FROM user_currencies WHERE user_id = ? AND currency_code = ?");
        $stmt->execute([$user_id, $input_currency]);
        $rate = $stmt->fetchColumn();

        if (!$rate || $rate <= 0) {
            $error = "⚠️ Pay-In rate not configured for this currency.";
        } elseif ($amount <= 0) {
            $error = "Amount must be greater than zero.";
        } else {
            // Convert to default currency
            $converted_amount = round($amount * $rate, 2);

            // Apply fee
            $fee = round(($converted_amount * $fee_percent) / 100, 2);
            $net_amount = $converted_amount - $fee;

            if ($net_amount <= 0) {
                $error = "Invalid amount after fee deduction.";
            } else {
                $ref = 'TXN-' . strtoupper(uniqid());

                // Insert transaction
                $stmt = $pdo->prepare("
                    INSERT INTO transactions 
                    (user_id, type, amount, fee, currency, status, payment_gateway, reference, created_at, admin_id, user_note) 
                    VALUES (?, 'payin', ?, ?, ?, 'success', 'Manual', ?, NOW(), ?, ?)
                ");
                $stmt->execute([$user_id, $amount, $fee, $input_currency, $ref, $admin_id, $user_note]);

                // Update user balance in default currency
                $pdo->prepare("UPDATE users SET balance = balance + ? WHERE id = ?")->execute([$net_amount, $user_id]);

                // Audit log
                $log = "Admin #$admin_id credited $net_amount $default_currency to User #$user_id. Input: $amount $input_currency @ rate $rate (Fee $fee @{$fee_percent}%). Admin Note: $admin_note";
                $pdo->prepare("INSERT INTO audit_logs (admin_id, action) VALUES (?, ?)")->execute([$admin_id, $log]);

                $success = "✅ Pay-In successful. " . strtoupper($default_currency) . " " . number_format($net_amount, 2) . " added to user account.";
                // Reset selection
                $selected_user_id = null;
                $user_currencies = [];
            }
        }
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Manual Pay-In</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css" rel="stylesheet">
</head>
<body class="p-4 container">

    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2><i class="bi bi-person-plus"></i> Manual Pay-In</h2>
        <a href="dashboard.php" class="btn btn-secondary">Back to Dashboard</a>
    </div>

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

    <form method="POST" class="card p-4 shadow-sm bg-light">
        <div class="mb-3">
            <label class="form-label">Select User</label>
            <select name="user_id" class="form-select" required onchange="this.form.submit()">
                <option value="">-- Choose User --</option>
                <?php foreach ($users as $u): ?>
                    <option value="<?= $u['id'] ?>" <?= ($u['id'] == $selected_user_id) ? 'selected' : '' ?>>
                        <?= htmlspecialchars($u['name']) ?>
                    </option>
                <?php endforeach; ?>
            </select>
            <div class="form-text">Selecting a user will load their supported currencies.</div>
        </div>

        <?php if ($selected_user_id && $user_currencies): ?>
            <div class="alert alert-info">
                User Default Currency: <strong><?= strtoupper($user_default_currency) ?></strong>
            </div>

            <div class="mb-3">
                <label class="form-label">Input Currency (to convert)</label>
                <select name="currency" class="form-select" required>
                    <option value="">-- Select Currency --</option>
                    <?php foreach ($user_currencies as $cur): ?>
                        <option value="<?= htmlspecialchars($cur) ?>" <?= (isset($_POST['currency']) && $_POST['currency'] == $cur) ? 'selected' : '' ?>>
                            <?= strtoupper($cur) ?> (Rate: <?= $user_rates[$cur] ?>)
                        </option>
                    <?php endforeach; ?>
                </select>
                <small class="text-muted">This will convert to user's default currency (<?= strtoupper($user_default_currency) ?>) at configured rate.</small>
            </div>

            <div class="mb-3">
                <label class="form-label">Amount (in selected currency)</label>
                <input type="number" name="amount" step="0.01" min="0.01" class="form-control" required value="<?= htmlspecialchars($_POST['amount'] ?? '') ?>">
            </div>

            <div class="mb-3">
                <label class="form-label">Note for User</label>
                <textarea name="user_note" class="form-control" rows="2" placeholder="Visible to user (optional)"><?= htmlspecialchars($_POST['user_note'] ?? '') ?></textarea>
            </div>

            <div class="mb-3">
                <label class="form-label">Internal Admin Note</label>
                <textarea name="admin_note" class="form-control" rows="2" placeholder="Only for audit log (optional)"><?= htmlspecialchars($_POST['admin_note'] ?? '') ?></textarea>
            </div>

            <button class="btn btn-primary"><i class="bi bi-cash-stack"></i> Add Pay-In</button>
        <?php elseif ($selected_user_id): ?>
            <div class="alert alert-warning">⚠️ This user has no available currencies configured. Please update their currencies first.</div>
        <?php endif; ?>
    </form>

</body>
</html>
