<?php
session_start();
require_once 'includes/auth_check.php';

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

function generateTransactionId($reference) {
    if (empty($reference)) return 'TXN00000000';
    $numeric = substr(abs(crc32($reference)), 0, 8);
    return 'TXN' . str_pad($numeric, 8, '0', STR_PAD_LEFT);
}

// --- Filtering and Pagination Logic (No changes needed here) ---
$filters = ['start_date' => $_GET['start_date'] ?? '', 'end_date' => $_GET['end_date'] ?? '', 'type' => $_GET['type'] ?? '', 'status' => $_GET['status'] ?? ''];
$whereClauses = [];
$params = [':user_id' => $_SESSION['user_id']];
if (!empty($filters['start_date'])) { $whereClauses[] = "created_at >= :start_date"; $params[':start_date'] = $filters['start_date'] . ' 00:00:00'; }
if (!empty($filters['end_date'])) { $whereClauses[] = "created_at <= :end_date"; $params[':end_date'] = $filters['end_date'] . ' 23:59:59'; }
if (!empty($filters['type'])) { $whereClauses[] = "type = :type"; $params[':type'] = $filters['type']; }
if (!empty($filters['status'])) { $whereClauses[] = "status = :status"; $params[':status'] = $filters['status']; }
$whereSql = !empty($whereClauses) ? ' AND ' . implode(' AND ', $whereClauses) : '';
$page_number = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$items_per_page = 15;
$countQuery = "SELECT COUNT(*) FROM transactions WHERE user_id = :user_id" . $whereSql;
$countStmt = $db->prepare($countQuery);
$countStmt->execute($params);
$total_records = $countStmt->fetchColumn();
$total_pages = ceil($total_records / $items_per_page);
$offset = ($page_number - 1) * $items_per_page;
$query = "SELECT * FROM transactions WHERE user_id = :user_id" . $whereSql . " ORDER BY created_at DESC LIMIT :limit OFFSET :offset";
$stmt = $db->prepare($query);
foreach ($params as $key => &$val) { $stmt->bindParam($key, $val); }
$stmt->bindParam(':limit', $items_per_page, PDO::PARAM_INT);
$stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();
$transactions = $stmt->fetchAll(PDO::FETCH_ASSOC);

include 'includes/header.php';
include 'includes/sidebar.php';
?>

<style>
/* Transactions Page Styles */
:root {
    --primary-color: #4f46e5; --primary-light: #eef2ff;
    --success-color: #10b981; --success-light: #ecfdf5;
    --danger-color: #ef4444; --danger-light: #fef2f2;
    --warning-color: #f59e0b; --warning-light: #fffbeb;
    --info-color: #3b82f6; --info-light: #eff6ff;
    --border-color: #e2e8f0;
}
.main-content { background-color: #f8fafc; }
.card { border: 1px solid var(--border-color); border-radius: 1rem; box-shadow: 0 1px 3px 0 rgba(0,0,0,0.05); }
.table-hover tbody tr:hover { background-color: #f9fafb; }

/* --- CSS-ONLY TOGGLE MECHANISM --- */
.transaction-details-row {
    display: none; /* Hide details by default */
}
.transaction-details-row:target {
    display: table-row; /* Show the row when its ID is targeted in the URL */
}
/* --- END OF TOGGLE MECHANISM --- */

.transaction-details-cell { background-color: #f9fafb; padding: 1.5rem !important; border-top: 2px solid var(--primary-color) !important; }
.transaction-id { font-family: 'Courier New', monospace; font-weight: 700; color: var(--primary-color); background-color: var(--primary-light); padding: 0.25rem 0.75rem; border-radius: 0.5rem; display: inline-block; }
.badge-status { padding: 0.35em 0.75em; font-size: 0.75em; font-weight: 600; border-radius: 9999px; }
.badge-status.completed { background-color: var(--success-light); color: var(--success-color); }
.badge-status.pending { background-color: var(--warning-light); color: var(--warning-color); }
.badge-status.rejected, .badge-status.failed { background-color: var(--danger-light); color: var(--danger-color); }
/* *** NEW STYLE FOR TRANSACTION TYPE BADGE *** */
.badge-type { padding: 0.35em 0.75em; font-size: 0.75em; font-weight: 500; border-radius: 9999px; border: 1px solid; }
.badge-type.credit { border-color: var(--success-color); color: var(--success-color); }
.badge-type.debit { border-color: var(--danger-color); color: var(--danger-color); }
.badge-type.wire_transfer { border-color: var(--info-color); color: var(--info-color); }
.badge-type.refund { border-color: var(--warning-color); color: var(--warning-color); }

.pagination .page-link { border-radius: 0.5rem !important; margin: 0 2px; }
.pagination .page-item.active .page-link { background-color: var(--primary-color); border-color: var(--primary-color); }
</style>

<div class="main-content">
    <h1 class="h3 mb-4">Transaction History</h1>

    <!-- Filter Card -->
    <div class="card mb-4">
        <div class="card-header bg-white"><h5 class="card-title mb-0"><i class='bx bx-filter-alt me-2'></i>Filter Transactions</h5></div>
        <div class="card-body">
            <form method="GET" action="transactions.php">
                <div class="row g-3 align-items-end">
                    <div class="col-md-3"><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($filters['start_date']); ?>"></div>
                    <div class="col-md-3"><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($filters['end_date']); ?>"></div>
                    <div class="col-md-2"><label for="type" class="form-label">Type</label><select name="type" id="type" class="form-select"><option value="">All</option><option value="credit" <?php echo ($filters['type'] == 'credit') ? 'selected' : ''; ?>>Credit</option><option value="debit" <?php echo ($filters['type'] == 'debit') ? 'selected' : ''; ?>>Debit</option></select></div>
                    <div class="col-md-2"><label for="status" class="form-label">Status</label><select name="status" id="status" class="form-select"><option value="">All</option><option value="completed" <?php echo ($filters['status'] == 'completed') ? 'selected' : ''; ?>>Completed</option><option value="pending" <?php echo ($filters['status'] == 'pending') ? 'selected' : ''; ?>>Pending</option><option value="failed" <?php echo ($filters['status'] == 'failed') ? 'selected' : ''; ?>>Failed</option></select></div>
                    <div class="col-md-2"><button type="submit" class="btn btn-primary w-100">Filter</button></div>
                </div>
            </form>
        </div>
    </div>

    <!-- Transactions Table Card -->
    <div class="card">
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover mb-0">
                    <thead class="table-light">
                        <tr>
                            <th>Date</th>
                            <th>Description</th>
                            <!-- *** MODIFICATION: ADDED "TYPE" COLUMN HEADER *** -->
                            <th class="text-center">Type</th>
                            <th class="text-end">Amount</th>
                            <th class="text-center">Status</th>
                            <th class="text-center">Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($transactions)): ?>
                            <tr><td colspan="6" class="text-center py-5 text-muted">No transactions found.</td></tr>
                        <?php else: ?>
                            <?php foreach ($transactions as $index => $tx): ?>
                                <tr>
                                    <td><?php echo date('M d, Y', strtotime($tx['created_at'])); ?></td>
                                    <td><?php echo htmlspecialchars($tx['description']); ?></td>
                                    <!-- *** MODIFICATION: ADDED "TYPE" COLUMN DATA *** -->
                                    <td class="text-center">
                                        <?php 
                                            $type_text = ucfirst(str_replace('_', ' ', $tx['transaction_type'] ?: $tx['type']));
                                            $type_class = strtolower($tx['transaction_type'] ?: $tx['type']);
                                        ?>
                                        <span class="badge-type <?php echo $type_class; ?>">
                                            <?php echo htmlspecialchars($type_text); ?>
                                        </span>
                                    </td>
                                    <td class="text-end fw-bold text-<?php echo $tx['type'] == 'credit' ? 'success' : 'danger'; ?>">
                                        <?php echo $tx['type'] == 'credit' ? '+' : '-'; ?><?php echo htmlspecialchars($tx['currency']); ?> <?php echo number_format($tx['amount'], 2); ?>
                                    </td>
                                    <td class="text-center"><span class="badge-status <?php echo strtolower($tx['status']); ?>"><?php echo ucfirst($tx['status']); ?></span></td>
                                    <td class="text-center">
                                        <a href="#details-row-<?php echo $index; ?>" class="btn btn-sm btn-outline-primary">
                                            <i class='bx bx-info-circle me-1'></i>Details
                                        </a>
                                    </td>
                                </tr>
                                <tr class="transaction-details-row" id="details-row-<?php echo $index; ?>">
                                    <!-- *** MODIFICATION: Colspan is now 6 *** -->
                                    <td colspan="6" class="transaction-details-cell">
                                        <div class="d-flex justify-content-between align-items-start">
                                            <div class="row w-100">
                                                <div class="col-md-6">
                                                    <p class="mb-2"><small class="text-muted d-block">Transaction ID</small><span class="transaction-id"><?php echo generateTransactionId($tx['reference']); ?></span></p>
                                                    <p class="mb-0"><small class="text-muted d-block">Full Reference</small><span class="font-monospace"><?php echo htmlspecialchars($tx['reference']); ?></span></p>
                                                </div>
                                                <div class="col-md-6 mt-3 mt-md-0">
                                                    <p class="mb-2"><small class="text-muted d-block">Date & Time</small><span><?php echo date('F j, Y, g:i A', strtotime($tx['created_at'])); ?></span></p>
                                                </div>
                                            </div>
                                            <a href="#" class="btn-close ms-3" aria-label="Close"></a>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
        <?php if ($total_pages > 1): ?>
        <div class="card-footer bg-white">
            <nav aria-label="Page navigation">
                <ul class="pagination justify-content-center mb-0">
                    <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                        <li class="page-item <?php echo $page_number == $i ? 'active' : ''; ?>">
                            <a class="page-link" href="?page=<?php echo $i; ?>&<?php echo http_build_query(array_filter($filters)); ?>"><?php echo $i; ?></a>
                        </li>
                    <?php endfor; ?>
                </ul>
            </nav>
        </div>
        <?php endif; ?>
    </div>
</div>

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

<!-- NO JAVASCRIPT IS NEEDED FOR THE TOGGLE TO WORK -->
