<?php
require_once '../functions.php';
requireAdminAuth();

$admin = getCurrentAdmin();
$db = getDB();

// Update transaction status
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_status'])) {
    $txId = intval($_POST['tx_id']);
    $newStatus = $_POST['status'];
    $adminNotes = trim($_POST['admin_notes'] ?? '');
    
   $stmt = $db->prepare("UPDATE transactions SET status = ?, admin_note = ? WHERE id = ?");
    $stmt->bind_param('ssi', $newStatus, $adminNotes, $txId);
    if ($stmt->execute()) {
        setFlash('Transaction status updated!', 'success');
        header('Location: transactions.php');
        exit();
    }
}

// Pagination
$page = max(1, intval($_GET['page'] ?? 1));
$limit = 25;
$offset = ($page - 1) * $limit;

// Get all transactions with user info
$stmt = $db->prepare("SELECT t.*, u.first_name, u.last_name, u.email FROM transactions t JOIN users u ON t.user_id = u.id ORDER BY t.created_at DESC LIMIT ? OFFSET ?");
$stmt->bind_param('ii', $limit, $offset);
$stmt->execute();
$transactions = $stmt->get_result();

$totalRecords = getTransactionCount();
$totalPages = ceil($totalRecords / $limit);

$flash = getFlash();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Transactions - <?php echo SITE_NAME; ?></title>
    <link rel="stylesheet" href="../assets/css/style.css">
</head>
<body>
    <?php include 'includes/admin-sidebar.php'; ?>
    
    <div class="main-content">
        <?php include 'includes/admin-header.php'; ?>
        
        <div class="page-content">
            <?php if ($flash): ?>
                <div class="alert alert-<?php echo $flash['type']; ?> fade-in">
                    <span><?php echo $flash['type'] === 'success' ? '✓' : '⚠'; ?></span> <?php echo e($flash['message']); ?>
                </div>
            <?php endif; ?>
            
            <div class="card">
                <div class="card-body" style="padding: 0;">
                    <div class="table-container">
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>Reference</th>
                                    <th>User</th>
                                    <th>Type</th>
                                    <th>Description</th>
                                    <th>Beneficiary</th>
                                    <th>Amount</th>
                                    <th>Status</th>
                                    <th>Date</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if ($transactions->num_rows > 0): ?>
                                    <?php while ($tx = $transactions->fetch_assoc()): ?>
                                        <tr>
                                            <td><code style="font-size: 11px;"><?php echo e($tx['reference_number']); ?></code></td>
                                            <td>
                                                <div style="font-weight: 600; font-size: 13px;"><?php echo e($tx['first_name'] . ' ' . $tx['last_name']); ?></div>
                                                <div style="font-size: 11px; color: var(--gray);"><?php echo e($tx['email']); ?></div>
                                            </td>
                                            <td>
                                                <span class="status-badge <?php echo $tx['transaction_type'] === 'credit' ? 'success' : ($tx['transaction_type'] === 'debit' ? 'danger' : ($tx['transaction_type'] === 'fee' ? 'warning' : 'info')); ?>" style="font-size: 11px;">
                                                    <?php echo ucfirst(e($tx['transaction_type'])); ?>
                                                </span>
                                            </td>
                                            <td style="font-size: 13px;"><?php echo e($tx['description'] ?? '-'); ?></td>
                                            <td style="font-size: 13px;"><?php echo e($tx['beneficiary_name'] ?? '-'); ?></td>
                                            <td style="font-weight: 700;"><?php echo formatCurrency($tx['amount']); ?></td>
                                            <td><span class="status-badge <?php echo e($tx['status']); ?>"><?php echo ucfirst(e($tx['status'])); ?></span></td>
                                            <td style="font-size: 12px;"><?php echo formatDateShort($tx['created_at']); ?></td>
                                            <td>
                                                <button class="btn btn-sm btn-outline-primary" onclick="openModal('modal-tx-<?php echo $tx['id']; ?>')">Manage</button>
                                            </td>
                                        </tr>
                                    <?php endwhile; ?>
                                <?php else: ?>
                                    <tr><td colspan="9" class="text-center" style="padding: 40px; color: var(--gray);">No transactions found</td></tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                    
                    <?php if ($totalPages > 1): ?>
                    <div style="padding: 16px 24px;">
                        <div class="pagination">
                            <?php for ($i = max(1, $page - 2); $i <= min($totalPages, $page + 2); $i++): ?>
                                <?php if ($i === $page): ?>
                                    <span><?php echo $i; ?></span>
                                <?php else: ?>
                                    <a href="?page=<?php echo $i; ?>"><?php echo $i; ?></a>
                                <?php endif; ?>
                            <?php endfor; ?>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
    
    <?php $transactions->data_seek(0); while ($tx = $transactions->fetch_assoc()): ?>
    <div class="modal-overlay" id="modal-tx-<?php echo $tx['id']; ?>">
        <div class="modal">
            <div class="modal-header">
                <span class="modal-title">Manage Transaction</span>
                <button class="modal-close" onclick="closeModal('modal-tx-<?php echo $tx['id']; ?>')">✕</button>
            </div>
            <div class="modal-body">
                <div style="background: var(--gray-50); border-radius: var(--border-radius); padding: 16px; margin-bottom: 20px;">
                    <div style="font-size: 13px; margin-bottom: 8px;"><strong>Reference:</strong> <?php echo e($tx['reference_number']); ?></div>
                    <div style="font-size: 13px; margin-bottom: 8px;"><strong>User:</strong> <?php echo e($tx['first_name'] . ' ' . $tx['last_name']); ?></div>
                    <div style="font-size: 13px; margin-bottom: 8px;"><strong>Amount:</strong> <?php echo formatCurrency($tx['amount']); ?></div>
                    <div style="font-size: 13px;"><strong>Current Status:</strong> <span class="status-badge <?php echo e($tx['status']); ?>" style="font-size: 11px;"><?php echo ucfirst(e($tx['status'])); ?></span></div>
                </div>
                
                <form method="POST" action="">
                    <input type="hidden" name="tx_id" value="<?php echo $tx['id']; ?>">
                    <input type="hidden" name="update_status" value="1">
                    <textarea name="admin_notes" class="form-control" rows="3" placeholder="Add notes about this transaction"><?php echo e($tx['admin_note'] ?? ''); ?></textarea>
                    <div class="form-group">
                        <label class="form-label">Status</label>
                        <select name="status" class="form-control">
                            <option value="pending" <?php echo $tx['status'] === 'pending' ? 'selected' : ''; ?>>Pending</option>
                            <option value="completed" <?php echo $tx['status'] === 'completed' ? 'selected' : ''; ?>>Completed</option>
                            <option value="failed" <?php echo $tx['status'] === 'failed' ? 'selected' : ''; ?>>Failed</option>
                            <option value="cancelled" <?php echo $tx['status'] === 'cancelled' ? 'selected' : ''; ?>>Cancelled</option>
                            <option value="on_hold" <?php echo $tx['status'] === 'on_hold' ? 'selected' : ''; ?>>On Hold</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Admin Notes</label>
                        <textarea name="admin_notes" class="form-control" rows="3" placeholder="Add notes about this transaction"><?php echo e($tx['admin_notes'] ?? ''); ?></textarea>
                    </div>
                    
                    <div class="modal-footer" style="padding: 16px 0 0 0; border: none;">
                        <button type="button" class="btn btn-secondary" onclick="closeModal('modal-tx-<?php echo $tx['id']; ?>')">Cancel</button>
                        <button type="submit" class="btn btn-primary">Update Status</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <?php endwhile; ?>
    
    <script src="../assets/js/main.js"></script>
</body>
</html>
