<?php
// 1. INCLUDE THE LOGIC-ONLY FILE
require_once 'admin-logic.php';

// --- Page-Specific Logic Starts Here ---

// 2. BUILD DYNAMIC WHERE CLAUSE & PARAMS FOR FILTERING
$where_clauses = [];
$params = [];
$types = '';

// Search term
$search_term = $_GET['search'] ?? '';
if (!empty($search_term)) {
    $where_clauses[] = "(u.full_name LIKE ? OR t.id = ? OR t.payment_ref LIKE ?)";
    $like_term = "%{$search_term}%";
    array_push($params, $like_term, $search_term, $like_term);
    $types .= 'sss';
}

// Filter by transaction type
$type_filter = $_GET['type'] ?? '';
if (!empty($type_filter)) { $where_clauses[] = "t.transaction_type = ?"; $params[] = $type_filter; $types .= 's'; }

// Filter by status
$status_filter = $_GET['status'] ?? '';
if (!empty($status_filter)) { $where_clauses[] = "t.status = ?"; $params[] = $status_filter; $types .= 's'; }

// Filter by date range
$start_date = $_GET['start_date'] ?? '';
$end_date = $_GET['end_date'] ?? '';
if (!empty($start_date) && !empty($end_date)) {
    $where_clauses[] = "DATE(t.created_at) BETWEEN ? AND ?";
    array_push($params, $start_date, $end_date);
    $types .= 'ss';
}

$where_sql = count($where_clauses) > 0 ? "WHERE " . implode(' AND ', $where_clauses) : '';

// 3. HANDLE CSV EXPORT ACTION
if (isset($_GET['action']) && $_GET['action'] === 'export') {
    $export_sql = "SELECT t.id, t.created_at, u.full_name, t.transaction_type, t.description, t.amount, t.status 
                   FROM transactions t 
                   JOIN users u ON t.user_id = u.id $where_sql ORDER BY t.created_at DESC";
    $stmt_export = $conn->prepare($export_sql);
    if (count($params) > 0) { $stmt_export->bind_param($types, ...$params); }
    $stmt_export->execute();
    $result = $stmt_export->get_result();

    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="transactions_export_'.date('Y-m-d').'.csv"');
    $output = fopen('php://output', 'w');
    fputcsv($output, ['Transaction ID', 'Date', 'User', 'Type', 'Description', 'Amount', 'Status']);
    
    while ($row = $result->fetch_assoc()) {
        fputcsv($output, $row);
    }
    fclose($output);
    exit();
}


// 4. FETCH TRANSACTIONS FOR DISPLAY (WITH PAGINATION)
$records_per_page = 20;
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $records_per_page;

$base_query = "FROM transactions t JOIN users u ON t.user_id = u.id $where_sql";

$count_sql = "SELECT COUNT(t.id) as total $base_query";
$stmt_count = $conn->prepare($count_sql);
if (count($params) > 0) { $stmt_count->bind_param($types, ...$params); }
$stmt_count->execute();
$total_records = $stmt_count->get_result()->fetch_assoc()['total'];
$total_pages = ceil($total_records / $records_per_page);
$stmt_count->close();

$fetch_sql = "SELECT t.*, u.full_name $base_query ORDER BY t.created_at DESC LIMIT ? OFFSET ?";
$params[] = $records_per_page; $params[] = $offset; $types .= 'ii';
$stmt_fetch = $conn->prepare($fetch_sql);
if (count($params) > 0) { $stmt_fetch->bind_param($types, ...$params); }
$stmt_fetch->execute();
$transactions_result = $stmt_fetch->get_result();


// 5. INCLUDE THE HTML HEADER
include 'admin-header.php';
?>

<?php if (isset($_SESSION['success_message'])): ?>
<div class="alert alert-success alert-dismissible fade show" role="alert"><?php echo $_SESSION['success_message']; unset($_SESSION['success_message']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
<?php endif; ?>
<?php if (isset($_SESSION['error_message'])): ?>
<div class="alert alert-danger alert-dismissible fade show" role="alert"><?php echo $_SESSION['error_message']; unset($_SESSION['error_message']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
<?php endif; ?>

<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h1 class="h2">Transaction History</h1>
    <?php 
        $export_query = $_GET;
        $export_query['action'] = 'export';
    ?>
    <a href="?<?php echo http_build_query($export_query); ?>" class="btn btn-outline-success">
        <i class="bi bi-download me-1"></i> Download CSV
    </a>
</div>

<div class="card mb-4 shadow-sm">
    <div class="card-header"><i class="bi bi-filter me-1"></i> Filter Transactions</div>
    <div class="card-body">
         <form action="transactions.php" method="GET">
            <div class="row g-3 align-items-center">
                <div class="col-xl-3"><input type="text" name="search" class="form-control" placeholder="Search User, Ref#, or ID..." value="<?php echo htmlspecialchars($search_term); ?>"></div>
                <div class="col-xl-2 col-md-6"><select name="type" class="form-select"><option value="">All Types</option><option value="Top-up" <?php if($type_filter == 'Top-up') echo 'selected'; ?>>Top-up</option><option value="Booking Payment" <?php if($type_filter == 'Booking Payment') echo 'selected'; ?>>Booking Payment</option><option value="Withdrawal" <?php if($type_filter == 'Withdrawal') echo 'selected'; ?>>Withdrawal</option><option value="Refund" <?php if($type_filter == 'Refund') echo 'selected'; ?>>Refund</option></select></div>
                <div class="col-xl-2 col-md-6"><select name="status" class="form-select"><option value="">All Statuses</option><option value="Completed" <?php if($status_filter == 'Completed') echo 'selected'; ?>>Completed</option><option value="Pending" <?php if($status_filter == 'Pending') echo 'selected'; ?>>Pending</option><option value="Rejected" <?php if($status_filter == 'Rejected') echo 'selected'; ?>>Rejected</option></select></div>
                <div class="col-xl-3 col-md-6">
                    <div class="input-group"><span class="input-group-text">Date</span><input type="date" name="start_date" class="form-control" value="<?php echo htmlspecialchars($start_date); ?>"><span class="input-group-text">to</span><input type="date" name="end_date" class="form-control" value="<?php echo htmlspecialchars($end_date); ?>"></div>
                </div>
                <div class="col-xl-2 d-grid d-md-flex gap-2"><button type="submit" class="btn btn-primary flex-grow-1">Filter</button><a href="transactions.php" class="btn btn-secondary flex-grow-1">Clear</a></div>
            </div>
        </form>
    </div>
</div>

<div class="table-responsive">
    <table class="table table-striped table-hover">
        <thead class="table-dark align-middle">
            <tr><th>ID</th><th>Date</th><th>User</th><th>Type</th><th>Details</th><th class="text-end">Amount</th><th class="text-center">Status</th></tr>
        </thead>
        <tbody>
            <?php if ($transactions_result->num_rows > 0): while ($transaction = $transactions_result->fetch_assoc()): ?>
            <?php
                // Determine color and prefix for the amount
                $is_credit = in_array($transaction['transaction_type'], ['Top-up', 'Booking Payment', 'Refund', 'Admin Credit']);
                $amount_class = $is_credit ? 'text-success' : 'text-danger';
                $amount_prefix = $is_credit ? '+ ' : '- ';
            ?>
            <tr>
                <td><strong>#<?php echo $transaction['id']; ?></strong></td>
                <td><?php echo date('M d, Y h:i A', strtotime($transaction['created_at'])); ?></td>
                <td><?php echo htmlspecialchars($transaction['full_name']); ?></td>
                <td><?php echo htmlspecialchars($transaction['transaction_type']); ?></td>
                <td><small><?php echo htmlspecialchars($transaction['description']); ?></small></td>
                <td class="text-end fw-bold <?php echo $amount_class; ?>"><?php echo $amount_prefix; ?>₱<?php echo number_format($transaction['amount'], 2); ?></td>
                <td class="text-center">
                    <?php $status_badge = ['Pending' => 'warning', 'Completed' => 'success', 'Rejected' => 'danger']; ?>
                    <span class="badge bg-<?php echo $status_badge[$transaction['status']] ?? 'secondary'; ?>"><?php echo htmlspecialchars($transaction['status']); ?></span>
                </td>
            </tr>
            <?php endwhile; else: ?>
            <tr><td colspan="7" class="text-center p-4">No transactions found matching your criteria.</td></tr>
            <?php endif; ?>
        </tbody>
    </table>
</div>

<?php if($total_pages > 1): ?>
<nav><ul class="pagination justify-content-center mt-4">
    <?php $query_params = $_GET; for ($i = 1; $i <= $total_pages; $i++): $query_params['page'] = $i; ?>
        <li class="page-item <?php echo ($i == $page) ? 'active' : ''; ?>"><a class="page-link" href="?<?php echo http_build_query($query_params); ?>"><?php echo $i; ?></a></li>
    <?php endfor; ?>
</ul></nav>
<?php endif; ?>

<?php include 'admin-footer.php'; ?>
