<?php
require_once 'includes/auth_check.php';
$page = 'transactions'; // Set the active page for the sidebar
require_once '../config/database.php';
require_once '../includes/functions.php';

$database = new Database();
$db = $database->getConnection();

// --- Filtering and Searching Logic ---
$search = $_GET['search'] ?? '';
$status = $_GET['status'] ?? '';
$type = $_GET['type'] ?? '';
$start_date = $_GET['start_date'] ?? '';
$end_date = $_GET['end_date'] ?? '';

// Base query
$query = "SELECT t.*, u.first_name, u.last_name, u.email 
          FROM transactions t 
          JOIN users u ON t.user_id = u.id";
$conditions = [];
$params = [];

// Add conditions based on filters
if (!empty($search)) {
    $conditions[] = "(u.first_name LIKE :search OR u.last_name LIKE :search OR u.email LIKE :search OR t.description LIKE :search OR t.reference LIKE :search)";
    $params[':search'] = "%$search%";
}
if (!empty($status)) {
    $conditions[] = "t.status = :status";
    $params[':status'] = $status;
}
if (!empty($type)) {
    $conditions[] = "t.type = :type";
    $params[':type'] = $type;
}
if (!empty($start_date)) {
    $conditions[] = "t.created_at >= :start_date";
    $params[':start_date'] = $start_date . ' 00:00:00';
}
if (!empty($end_date)) {
    $conditions[] = "t.created_at <= :end_date";
    $params[':end_date'] = $end_date . ' 23:59:59';
}

if (count($conditions) > 0) {
    $query .= " WHERE " . implode(' AND ', $conditions);
}

// --- Pagination Logic ---
$page_num = isset($_GET['page_num']) ? (int)$_GET['page_num'] : 1;
$records_per_page = 20;
$offset = ($page_num - 1) * $records_per_page;

// Get total number of records for pagination
$count_query = preg_replace('/SELECT t\.\*, u\.first_name, u\.last_name, u\.email/', 'SELECT COUNT(t.id)', $query);
$total_rows_stmt = $db->prepare($count_query);
$total_rows_stmt->execute($params);
$total_rows = $total_rows_stmt->fetchColumn();
$total_pages = ceil($total_rows / $records_per_page);

// Add sorting and limit to the final query
$query .= " ORDER BY t.created_at DESC LIMIT :limit OFFSET :offset";

$stmt = $db->prepare($query);
$stmt->bindValue(':limit', $records_per_page, PDO::PARAM_INT);
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
foreach ($params as $key => &$val) {
    $stmt->bindParam($key, $val);
}
$stmt->execute();
$transactions = $stmt->fetchAll(PDO::FETCH_ASSOC);

include 'includes/header.php';
?>

<div class="container-fluid">
    <h1 class="h3 mb-4 text-gray-800">All Transactions</h1>

    <!-- Filter Card -->
    <div class="card shadow mb-4">
        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold text-primary">Filter Transactions</h6>
        </div>
        <div class="card-body">
            <form method="GET" action="manage_transactions.php">
                <div class="row g-3">
                    <div class="col-md-4">
                        <label for="search" class="form-label">Search</label>
                        <input type="text" class="form-control" id="search" name="search" placeholder="User, email, description..." value="<?php echo htmlspecialchars($search); ?>">
                    </div>
                    <div class="col-md-2">
                        <label for="type" class="form-label">Type</label>
                        <select class="form-select" id="type" name="type">
                            <option value="">All</option>
                            <option value="credit" <?php if ($type == 'credit') echo 'selected'; ?>>Credit</option>
                            <option value="debit" <?php if ($type == 'debit') echo 'selected'; ?>>Debit</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label for="status" class="form-label">Status</label>
                        <select class="form-select" id="status" name="status">
                            <option value="">All</option>
                            <option value="completed" <?php if ($status == 'completed') echo 'selected'; ?>>Completed</option>
                            <option value="pending" <?php if ($status == 'pending') echo 'selected'; ?>>Pending</option>
                            <option value="failed" <?php if ($status == 'failed') echo 'selected'; ?>>Failed</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label for="start_date" class="form-label">Start Date</label>
                        <input type="date" class="form-control" id="start_date" name="start_date" value="<?php echo htmlspecialchars($start_date); ?>">
                    </div>
                    <div class="col-md-2">
                        <label for="end_date" class="form-label">End Date</label>
                        <input type="date" class="form-control" id="end_date" name="end_date" value="<?php echo htmlspecialchars($end_date); ?>">
                    </div>
                </div>
                <div class="row mt-3">
                    <div class="col">
                        <button type="submit" class="btn btn-primary">Apply Filters</button>
                        <a href="manage_transactions.php" class="btn btn-secondary">Reset</a>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- Transactions Table -->
    <div class="card shadow mb-4">
        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold text-primary">Transaction Log</h6>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-hover" width="100%">
                    <thead class="table-light">
                        <tr>
                            <th>Date</th>
                            <th>User</th>
                            <th>Description</th>
                            <th>Type</th>
                            <th>Amount</th>
                            <th>Status</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($transactions)): ?>
                            <tr><td colspan="6" class="text-center text-muted py-4">No transactions found matching your criteria.</td></tr>
                        <?php else: ?>
                            <?php foreach ($transactions as $tx): ?>
                                <tr>
                                    <td><?php echo date('d M Y, H:i', strtotime($tx['created_at'])); ?></td>
                                    <td>
                                        <a href="view_user.php?id=<?php echo $tx['user_id']; ?>">
                                            <?php echo htmlspecialchars($tx['first_name'] . ' ' . $tx['last_name']); ?>
                                        </a>
                                    </td>
                                    <td><?php echo htmlspecialchars($tx['description']); ?></td>
                                    <td><span class="badge text-bg-<?php echo $tx['type'] == 'credit' ? 'success' : 'danger'; ?>"><?php echo ucfirst($tx['type']); ?></span></td>
                                    <td class="fw-bold <?php echo $tx['type'] == 'credit' ? 'text-success' : 'text-danger'; ?>">
                                        <?php echo htmlspecialchars($tx['currency']); ?> <?php echo number_format($tx['amount'], 2); ?>
                                    </td>
                                    <td><span class="badge rounded-pill text-bg-<?php echo $tx['status'] == 'completed' ? 'success' : ($tx['status'] == 'pending' ? 'warning' : 'danger'); ?>"><?php echo ucfirst($tx['status']); ?></span></td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>

            <!-- Pagination Controls -->
            <?php if ($total_pages > 1): ?>
            <nav class="mt-4">
                <ul class="pagination justify-content-center">
                    <?php
                    // Build query string for pagination links
                    $queryParams = $_GET;
                    unset($queryParams['page_num']);
                    $queryString = http_build_query($queryParams);
                    ?>
                    <li class="page-item <?php if($page_num <= 1){ echo 'disabled'; } ?>">
                        <a class="page-link" href="?page_num=<?php echo $page_num - 1; ?>&<?php echo $queryString; ?>">Previous</a>
                    </li>
                    <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                    <li class="page-item <?php if($page_num == $i) {echo 'active'; } ?>">
                        <a class="page-link" href="?page_num=<?php echo $i; ?>&<?php echo $queryString; ?>"><?php echo $i; ?></a>
                    </li>
                    <?php endfor; ?>
                    <li class="page-item <?php if($page_num >= $total_pages) {echo 'disabled'; } ?>">
                        <a class="page-link" href="?page_num=<?php echo $page_num + 1; ?>&<?php echo $queryString; ?>">Next</a>
                    </li>
                </ul>
            </nav>
            <?php endif; ?>
        </div>
    </div>
</div>

<?php include 'includes/footer.php'; ?>
