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

session_start();

if (!isset($_SESSION['admin_id'])) {
    header("Location: admin-login.php");
    exit;
}

if (!isset($_GET['uid']) || !is_numeric($_GET['uid']) || (int)$_GET['uid'] <= 0) {
    die("<div class='alert alert-danger text-center p-4'>Error: Invalid or missing user ID</div>");
}

$uid = (int)$_GET['uid'];

// Fetch current user data
$result = mysqli_query($conn, "SELECT account_balance, full_name FROM users WHERE id = $uid LIMIT 1");
if (mysqli_num_rows($result) !== 1) {
    die("<div class='alert alert-danger text-center p-4'>Error: User ID #$uid not found</div>");
}
$user = mysqli_fetch_assoc($result);

// ────────────────────────────────────────────────
// HANDLE POST - Add new transaction
$message = '';
$message_type = 'success'; // success / danger / warning

if (isset($_POST['post_transaction'])) {
    $transaction_type = $_POST['transaction_type'] ?? '';
    $amount = floatval($_POST['amount'] ?? 0);
    $description = trim($_POST['description'] ?? '');

    $valid_types = ['Transfer','Airtime','Data','Electricity','Water','Utility'];

    if ($amount <= 0) {
        $message = "Amount must be greater than 0";
        $message_type = 'danger';
    } elseif (!in_array($transaction_type, $valid_types)) {
        $message = "Invalid transaction type";
        $message_type = 'danger';
    } else {
        $is_debit = in_array($transaction_type, ['Transfer']);
        $reference = 'TXN' . time() . rand(1000,9999);

        $stmt = $conn->prepare("
            INSERT INTO transactions 
            (user_id, transaction_type, amount, description, reference, status)
            VALUES (?, ?, ?, ?, ?, 'Success')
        ");
        $stmt->bind_param("isdss", $uid, $transaction_type, $amount, $description, $reference);

        if ($stmt->execute()) {
            if ($is_debit) {
                $new_balance = $user['account_balance'] - $amount;
                if ($new_balance < 0) {
                    $message = "Insufficient balance for this transaction";
                    $message_type = 'danger';
                }
            } else {
                $new_balance = $user['account_balance'] + $amount;
            }

            if ($message_type !== 'danger') {
                $stmt2 = $conn->prepare("UPDATE users SET account_balance = ? WHERE id = ?");
                $stmt2->bind_param("di", $new_balance, $uid);
                $stmt2->execute();
                $stmt2->close();

                $message = "Transaction posted successfully!<br>New balance: AED " . number_format($new_balance, 2);
                $message_type = 'success';
            }
        } else {
            $message = "Insert failed: " . $stmt->error;
            $message_type = 'danger';
        }
        $stmt->close();
    }
}

// ────────────────────────────────────────────────
// (DELETE and EDIT handling remains the same - omitted here for brevity)


// Load recent transactions
$transactions = mysqli_query($conn, "
    SELECT id, transaction_type, amount, description, reference, created_at 
    FROM transactions 
    WHERE user_id = $uid 
    ORDER BY created_at DESC 
    LIMIT 10
");
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add / Manage Transactions</title>

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons/font/bootstrap-icons.css" rel="stylesheet">

    <!-- Use the same CSS file as edit user -->
    <link rel="stylesheet" href="assets/admin-post-transaction.css">
    <!-- If you want to share exact same styles, you can rename or include admin-edit-user.css instead -->
</head>
<body>

<div class="app">

    <!-- TOP HEADER - same dark style -->
    <div class="top-header">
        <a href="admin_view_user.php?uid=<?= $uid ?>" class="back-icon">
            <i class="bi bi-arrow-left"></i>
        </a>
        <div>
            <small>Admin Panel</small>
            <h4>Add Transaction</h4>
        </div>
        <i class="bi bi-plus-circle"></i>
    </div>

    <!-- MESSAGE ALERT (appears above card) -->
    <?php if ($message): ?>
    <div class="container mt-3 px-4">
        <div class="alert alert-<?= $message_type ?> alert-dismissible fade show" role="alert">
            <?= $message ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    </div>
    <?php endif; ?>

    <!-- MAIN FORM CARD -->
    <div class="card form-card">
        <form method="POST">
            <div class="form-group">
                <label>Transaction Type</label>
                <select name="transaction_type" required>
                    <option value="" disabled selected>Select type</option>
                    <option value="Transfer">Transfer</option>
                    <option value="Airtime">Airtime</option>
                    <option value="Data">Data</option>
                    <option value="Electricity">Electricity</option>
                    <option value="Water">Water</option>
                    <option value="Utility">Utility</option>
                </select>
            </div>

            <div class="form-group">
                <label>Amount (AED)</label>
                <input type="number" name="amount" step="0.01" min="0.01" required>
            </div>

            <div class="form-group">
                <label>Description</label>
                <input type="text" name="description" required>
            </div>

            <button type="submit" name="post_transaction" class="btn-save">
                <i class="bi bi-send"></i> Post Transaction
            </button>
        </form>
    </div>

    <!-- TRANSACTIONS SECTION -->
    <div class="card form-card mt-4">
        <h5 style="margin-bottom: 16px; color: #1f2937;">Recent Transactions</h5>

        <?php if (mysqli_num_rows($transactions) > 0): ?>
            <div class="table-responsive">
                <table class="table table-hover" style="font-size: 14px;">
                    <thead>
                        <tr>
                            <th>Type</th>
                            <th>Amount</th>
                            <th>Description</th>
                            <th>Ref</th>
                            <th>Date</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php while ($txn = mysqli_fetch_assoc($transactions)): ?>
                        <tr>
                            <td><?= htmlspecialchars($txn['transaction_type']) ?></td>
                            <td>AED <?= number_format($txn['amount'], 2) ?></td>
                            <td><?= htmlspecialchars($txn['description'] ?: '—') ?></td>
                            <td><?= htmlspecialchars($txn['reference']) ?></td>
                            <td><?= date('d M Y H:i', strtotime($txn['created_at'])) ?></td>
                            <td>
                                <button class="btn btn-sm btn-outline-primary me-1" 
                                        data-bs-toggle="modal" 
                                        data-bs-target="#editModal<?= $txn['id'] ?>">
                                    <i class="bi bi-pencil"></i>
                                </button>
                                <a href="?uid=<?= $uid ?>&delete_txn=<?= $txn['id'] ?>" 
                                   class="btn btn-sm btn-outline-danger"
                                   onclick="return confirm('Delete this transaction? Balance will be reversed.')">
                                    <i class="bi bi-trash"></i>
                                </a>
                            </td>
                        </tr>

                        <!-- Edit Modal (kept but can be styled further if needed) -->
                        <div class="modal fade" id="editModal<?= $txn['id'] ?>" tabindex="-1">
                            <div class="modal-dialog">
                                <div class="modal-content">
                                    <form method="POST">
                                        <div class="modal-header">
                                            <h5 class="modal-title">Edit #<?= $txn['id'] ?></h5>
                                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                        </div>
                                        <div class="modal-body">
                                            <input type="hidden" name="txn_id" value="<?= $txn['id'] ?>">
                                            <!-- ... rest of edit form fields ... -->
                                        </div>
                                        <div class="modal-footer">
                                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                                            <button type="submit" name="edit_transaction" class="btn btn-primary">Save</button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    <?php endwhile; ?>
                    </tbody>
                </table>
            </div>
        <?php else: ?>
            <p class="text-center text-muted py-4">No transactions found yet.</p>
        <?php endif; ?>
    </div>

</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>