<?php
require_once __DIR__ . "/../includes/admin_auth.php"; // Admin must be logged in
require_once __DIR__ . '/../includes/db.php';

// ==========================
// Handle "Mark Complete" action
// ==========================
if (isset($_GET['mark_complete'])) {
    $txn_id = intval($_GET['mark_complete']);
    $stmt = $conn->prepare("UPDATE transactions SET status='completed' WHERE id=?");
    $stmt->bind_param("i", $txn_id);
    $stmt->execute();

    // Update user balance if it's a credit
    $stmt2 = $conn->prepare("
        UPDATE users u
        JOIN transactions t ON t.account_id = u.id
        SET u.balance = u.balance + t.amount
        WHERE t.id = ? AND t.type='credit'
    ");
    $stmt2->bind_param("i", $txn_id);
    $stmt2->execute();

    header("Location: transactions.php");
    exit;
}

// ==========================
// Filters
// ==========================
$type = $_GET['type'] ?? '';
$status = $_GET['status'] ?? '';
$where = "WHERE 1=1";

if (!empty($type)) {
    $where .= " AND t.type='" . $conn->real_escape_string($type) . "'";
}
if (!empty($status)) {
    $where .= " AND t.status='" . $conn->real_escape_string($status) . "'";
}

// ==========================
// Fetch Transactions
// ==========================
$sql = "
    SELECT 
        t.*, 
        CONCAT(u.first_name, ' ', u.last_name) AS full_name,
        u.currency
    FROM transactions t
    LEFT JOIN users u ON t.account_id = u.id
    $where
    ORDER BY t.created_at DESC
";

$result = $conn->query($sql);
if (!$result) {
    die("SQL Error: " . $conn->error);
}

// ==========================
// Page Output
// ==========================
ob_start();
?>

<div class="main-content">
    <h2 class="page-title">Transactions</h2>

    <!-- FILTER -->
    <div class="panel">
        <form method="GET" class="filter-form">
            <select name="type">
                <option value="">All Types</option>
                <option value="credit" <?= $type=='credit'?'selected':'' ?>>Credit</option>
                <option value="debit" <?= $type=='debit'?'selected':'' ?>>Debit</option>
                <option value="transfer" <?= $type=='transfer'?'selected':'' ?>>Transfer</option>
            </select>

            <select name="status">
                <option value="">All Status</option>
                <option value="pending" <?= $status=='pending'?'selected':'' ?>>Pending</option>
                <option value="completed" <?= $status=='completed'?'selected':'' ?>>Completed</option>
                <option value="cancelled" <?= $status=='cancelled'?'selected':'' ?>>Cancelled</option>
            </select>

            <button type="submit" class="btn-small">Filter</button>
        </form>
    </div>

    <!-- TABLE -->
    <div class="panel">
        <table class="table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>User</th>
                    <th>Account #</th>
                    <th>Type</th>
                    <th>Amount</th>
                    <th>Description</th>
                    <th>Status</th>
                    <th>Date</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
                <?php if ($result->num_rows > 0): ?>
                    <?php while ($row = $result->fetch_assoc()): ?>
                        <tr>
                            <td><?= $row['id'] ?></td>
                            <td><?= htmlspecialchars($row['full_name'] ?? 'Admin Credit') ?></td>
                            <td><?= 'N/A' ?></td>
                            <td><?= ucfirst($row['type']) ?></td>
                            <td><?= ($row['currency'] ?? 'USD') . " " . number_format($row['amount'], 2) ?></td>
                            <td><?= htmlspecialchars($row['description'] ?? 'Transfer') ?></td>
                            <td><?= ucfirst($row['status']) ?></td>
                            <td><?= date("d M Y, H:i", strtotime($row['created_at'])) ?></td>
                            <td>
                                <?php if ($row['type']=='credit' && $row['status']=='pending'): ?>
                                    <a href="?mark_complete=<?= $row['id'] ?>">Mark Complete</a>
                                <?php else: ?>
                                    &mdash;
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endwhile; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="9">No transactions found.</td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<?php
$content = ob_get_clean();
$page_title = "Transactions";
include '../components/admin_layout.php';
?>