<?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);
}

// Function to clean up admin-related descriptions for customer view
function cleanTransactionDescription($description) {
    $adminPrefixes = [
        'Admin Action: ',
        'Balance adjustment: ',
        'Admin adjustment: ',
        'Manual adjustment: ',
        'Account adjustment: '
    ];
    
    foreach ($adminPrefixes as $prefix) {
        if (stripos($description, $prefix) === 0) {
            return substr($description, strlen($prefix));
        }
    }
    
    return $description;
}

// --- 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); }
.badge-type.adjustment { border-color: var(--info-color); color: var(--info-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); }

/* Description text styles */
.transaction-description {
    max-width: 300px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

tr:hover .transaction-description {
    white-space: normal;
    overflow: visible;
}
</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 class="transaction-description">
                                        <?php 
                                        // Clean up admin-related descriptions
                                        echo htmlspecialchars(cleanTransactionDescription($tx['description'])); 
                                        ?>
                                    </td>
                                    <!-- *** MODIFICATION: ADDED "TYPE" COLUMN DATA *** -->
                                    <td class="text-center">
                                        <?php 
                                            // Determine the transaction type display text and class
                                            $transaction_type = $tx['transaction_type'] ?: $tx['type'];
                                            
                                            // Map transaction types to user-friendly display names
                                            $type_display_map = [
                                                'credit' => 'Credit',
                                                'debit' => 'Debit',
                                                'transfer' => 'Transfer',
                                                'wire_transfer' => 'Wire Transfer',
                                                'international' => 'International',
                                                'refund' => 'Refund',
                                                'adjustment' => 'Adjustment'
                                            ];
                                            
                                            $type_text = $type_display_map[$transaction_type] ?? ucfirst(str_replace('_', ' ', $transaction_type));
                                            $type_class = strtolower($transaction_type);
                                            
                                            // If it's an admin adjustment, show a more user-friendly type
                                            if (stripos($tx['description'], 'Admin Action:') === 0 || 
                                                stripos($tx['description'], 'Balance adjustment:') === 0 ||
                                                $transaction_type === 'adjustment') {
                                                $type_text = $tx['type'] === 'credit' ? 'Deposit' : 'Withdrawal';
                                                $type_class = $tx['type']; // Use credit/debit for the color
                                            }
                                        ?>
                                        <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 
                                        // Dynamic decimal places for amount
                                        $decimal_places = (strtoupper($tx['currency']) === 'BTC') ? 8 : 2;
                                        $formatted_amount = number_format($tx['amount'], $decimal_places);
                                        ?>
                                        <?php echo $tx['type'] == 'credit' ? '+' : '-'; ?><?php echo htmlspecialchars($tx['currency']); ?> <?php echo $formatted_amount; ?>
                                    </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>
                                                    <p class="mb-0"><small class="text-muted d-block">Description</small><span><?php echo htmlspecialchars(cleanTransactionDescription($tx['description'])); ?></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 -->
