<?php 
// Include session handling
try {
   include_once 'services/session.php';
} catch (Exception $e) {
   die("Error including session.php: " . $e->getMessage());
}

// Check if user is logged in
if (!isset($_SESSION['user']) || empty($_SESSION['user'])) {
   header('Location: auth-login.php?error=session_expired');
   exit();
}

// Get user details
$user_role = $_SESSION['role_name'] ?? 'Customer';
$user_id = $_SESSION['user_id'] ?? 0;
$user_name = $_SESSION['full_name'] ?? $_SESSION['user'];

// Only allow customers
if ($user_role !== 'Customer') {
   header('Location: auth-login.php?error=access_denied');
   exit();
}

// Include database connection
try {
   require_once 'layouts/dbconn.php';
} catch (Exception $e) {
   die("Error including database connection: " . $e->getMessage());
}

// Test database connection
if (!isset($conn) || $conn->connect_error) {
   die("Database connection failed: " . ($conn->connect_error ?? 'Connection object not found'));
}

// Function to safely execute queries
if (!function_exists('safeQuery')) {
   function safeQuery($conn, $query, $params = []) {
       try {
           $stmt = $conn->prepare($query);
           if (!$stmt) {
               throw new Exception("Prepare failed: " . $conn->error);
           }
           
           if (!empty($params)) {
               $types = str_repeat('s', count($params));
               $stmt->bind_param($types, ...$params);
           }
           
           $stmt->execute();
           $result = $stmt->get_result();
           $data = $result->fetch_all(MYSQLI_ASSOC);
           $stmt->close();
           
           return $data;
       } catch (Exception $e) {
           error_log("Query error: " . $e->getMessage());
           return [];
       }
   }
}

// Pagination
$page = $_GET['page'] ?? 1;
$limit = 10;
$offset = ($page - 1) * $limit;

// Filters
$status_filter = $_GET['status'] ?? '';
$date_from = $_GET['date_from'] ?? '';
$date_to = $_GET['date_to'] ?? '';

// Build WHERE clause for payments
$where_conditions = ["p.user_id = ?"];
$params = [$user_id];

if (!empty($status_filter)) {
   $where_conditions[] = "p.status = ?";
   $params[] = $status_filter;
}

if (!empty($date_from)) {
   $where_conditions[] = "DATE(p.created_at) >= ?";
   $params[] = $date_from;
}

if (!empty($date_to)) {
   $where_conditions[] = "DATE(p.created_at) <= ?";
   $params[] = $date_to;
}

$where_clause = implode(" AND ", $where_conditions);

// Get payments with pagination
$payments = safeQuery($conn, "
   SELECT 
       p.payment_id,
       p.transaction_id,
       p.amount,
       p.currency,
       p.status,
       p.payment_method,
       p.created_at,
       p.updated_at,
       pr.name as product_name,
       pp.tier_name as plan_name,
       l.license_key
   FROM payments p
   LEFT JOIN licenses l ON p.license_id = l.license_id
   LEFT JOIN products pr ON l.product_id = pr.product_id
   LEFT JOIN product_pricing pp ON l.pricing_id = pp.pricing_id
   WHERE $where_clause
   ORDER BY p.created_at DESC
   LIMIT ? OFFSET ?
", array_merge($params, [$limit, $offset]));

// Get total count for pagination
$total_result = safeQuery($conn, "
   SELECT COUNT(*) as total
   FROM payments p
   WHERE " . str_replace("p.user_id = ?", "p.user_id = ?", implode(" AND ", array_slice($where_conditions, 0, 1))) . "
   " . (count($where_conditions) > 1 ? " AND " . implode(" AND ", array_slice($where_conditions, 1)) : ""),
   $params);
$total_payments = $total_result[0]['total'] ?? 0;
$total_pages = ceil($total_payments / $limit);

// Get payment statistics
$stats_result = safeQuery($conn, "
   SELECT 
       COUNT(*) as total_count,
       SUM(CASE WHEN status = 'completed' THEN amount ELSE 0 END) as total_amount,
       SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as completed_count,
       SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending_count,
       SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) as failed_count,
       SUM(CASE WHEN status = 'completed' AND MONTH(created_at) = MONTH(NOW()) AND YEAR(created_at) = YEAR(NOW()) THEN amount ELSE 0 END) as month_amount
   FROM payments 
   WHERE user_id = ?
", [$user_id]);

$paymentStats = $stats_result[0] ?? [
   'total_count' => 0,
   'total_amount' => 0,
   'completed_count' => 0,
   'pending_count' => 0,
   'failed_count' => 0,
   'month_amount' => 0
];
?>

<!DOCTYPE html>
<html lang="en">

<head>
   <?php 
   $title = "Payment History";
   if (file_exists('partials/title-meta.php')) {
       try {
           include_once 'partials/title-meta.php';
       } catch (Exception $e) {
           echo "<title>$title - ConnectPay</title>\n";
       }
   } else {
       echo "<title>$title - ConnectPay</title>\n";
   }
   ?>
   
   <?php 
   if (file_exists('partials/head-css.php')) {
       try {
           include_once 'partials/head-css.php';
       } catch (Exception $e) {
           echo '<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">' . "\n";
           echo '<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">' . "\n";
       }
   } else {
       echo '<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">' . "\n";
       echo '<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">' . "\n";
   }
   ?>
   
   <style>
       body {
           background-color: #f8f9fa;
       }
       
       .stats-card {
           border: 1px solid #e2e8f0;
           border-radius: 8px;
           background: white;
           transition: transform 0.2s ease;
       }
       
       .stats-card:hover {
           transform: translateY(-2px);
           box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
       }
       
       .status-badge {
           padding: 0.25rem 0.75rem;
           border-radius: 9999px;
           font-size: 0.75rem;
           font-weight: 500;
           text-transform: uppercase;
       }
       
       .status-completed {
           background-color: #dcfce7;
           color: #166534;
       }
       
       .status-pending {
           background-color: #fef3c7;
           color: #92400e;
       }
       
       .status-failed {
           background-color: #fef2f2;
           color: #dc2626;
       }
       
       .status-refunded {
           background-color: #f0f9ff;
           color: #1e40af;
       }
       
       .form-control, .form-select {
           border: 1px solid #d1d5db;
           border-radius: 6px;
           padding: 0.5rem 0.75rem;
           transition: border-color 0.2s ease;
       }
       
       .form-control:focus, .form-select:focus {
           border-color: #3b82f6;
           box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
           outline: none;
       }
       
       .btn-primary {
           background-color: #3b82f6;
           border-color: #3b82f6;
           border-radius: 6px;
           font-weight: 500;
       }
       
       .btn-primary:hover {
           background-color: #2563eb;
           border-color: #2563eb;
       }
       
       .btn-outline-secondary {
           border: 1px solid #d1d5db;
           color: #6b7280;
           border-radius: 6px;
       }
       
       .btn-outline-secondary:hover {
           background-color: #f9fafb;
           border-color: #9ca3af;
           color: #374151;
       }
       
       .table {
           border-collapse: separate;
           border-spacing: 0;
       }
       
       .table th {
           border-bottom: 1px solid #e5e7eb;
           font-weight: 600;
           color: #374151;
           padding: 0.75rem;
       }
       
       .table td {
           border-bottom: 1px solid #f3f4f6;
           padding: 1rem 0.75rem;
           vertical-align: middle;
       }
       
       .pagination .page-link {
           border: 1px solid #d1d5db;
           color: #6b7280;
           padding: 0.5rem 0.75rem;
           border-radius: 6px;
           margin: 0 0.125rem;
       }
       
       .pagination .page-link:hover {
           background-color: #f9fafb;
           border-color: #9ca3af;
           color: #374151;
       }
       
       .pagination .page-item.active .page-link {
           background-color: #3b82f6;
           border-color: #3b82f6;
           color: white;
       }
       
       .payment-header {
           background: white;
           border-radius: 15px;
           padding: 2rem;
           margin-bottom: 2rem;
           border: 1px solid #e2e8f0;
       }
       
       .filter-card {
           background: white;
           border-radius: 8px;
           border: 1px solid #e2e8f0;
           margin-bottom: 1.5rem;
       }
       
       .transaction-row {
           transition: background-color 0.2s ease;
       }
       
       .transaction-row:hover {
           background-color: #f8fafc;
       }
   </style>
</head>

<body>

<div id="wrapper">
   <?php 
   $pagetitle = "Payment History"; 
   if (file_exists('partials/menu.php')) {
       try {
           include_once 'partials/menu.php';
       } catch (Exception $e) {
           echo '<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
                   <div class="container">
                       <a class="navbar-brand" href="customer-dashboard.php">ConnectPay</a>
                       <span class="navbar-text">Welcome, ' . htmlspecialchars($user_name) . '</span>
                   </div>
                 </nav>';
       }
   }
   ?>

   <div class="content-page">
       <div class="content">
           <div class="container-fluid">
               
               <!-- Payment Header -->
               <div class="row">
                   <div class="col-12">
                       <div class="payment-header">
                           <div class="row align-items-center">
                               <div class="col-md-8">
                                   <h2 class="mb-3">
                                       <i class="fas fa-credit-card me-2"></i>
                                       Payment History
                                   </h2>
                                   <p class="mb-0 text-muted">
                                       Track your payment transactions and download receipts
                                   </p>
                               </div>
                               <div class="col-md-4">
                                   <nav aria-label="breadcrumb">
                                       <ol class="breadcrumb justify-content-end mb-0">
                                           <li class="breadcrumb-item"><a href="customer-dashboard.php">Dashboard</a></li>
                                           <li class="breadcrumb-item"><a href="#">Wallet</a></li>
                                           <li class="breadcrumb-item active">Payment History</li>
                                       </ol>
                                   </nav>
                               </div>
                           </div>
                       </div>
                   </div>
               </div>
               
               <!-- Payment Statistics -->
               <div class="row mb-4">
                   <div class="col-xl-3 col-md-6 mb-3">
                       <div class="stats-card p-4">
                           <div class="d-flex align-items-center">
                               <div class="flex-shrink-0">
                                   <div class="rounded-circle bg-success bg-opacity-10 p-3">
                                       <i class="fas fa-dollar-sign text-success" style="font-size: 1.5rem;"></i>
                                   </div>
                               </div>
                               <div class="flex-grow-1 ms-3">
                                   <h6 class="text-muted mb-1">Total Spent</h6>
                                   <h4 class="mb-0">$<?php echo number_format($paymentStats['total_amount'], 2); ?></h4>
                                   <small class="text-muted">All time</small>
                               </div>
                           </div>
                       </div>
                   </div>
                   <div class="col-xl-3 col-md-6 mb-3">
                       <div class="stats-card p-4">
                           <div class="d-flex align-items-center">
                               <div class="flex-shrink-0">
                                   <div class="rounded-circle bg-primary bg-opacity-10 p-3">
                                       <i class="fas fa-check-circle text-primary" style="font-size: 1.5rem;"></i>
                                   </div>
                               </div>
                               <div class="flex-grow-1 ms-3">
                                   <h6 class="text-muted mb-1">Successful Payments</h6>
                                   <h4 class="mb-0"><?php echo $paymentStats['completed_count']; ?></h4>
                                   <small class="text-muted">Completed</small>
                               </div>
                           </div>
                       </div>
                   </div>
                   <div class="col-xl-3 col-md-6 mb-3">
                       <div class="stats-card p-4">
                           <div class="d-flex align-items-center">
                               <div class="flex-shrink-0">
                                   <div class="rounded-circle bg-warning bg-opacity-10 p-3">
                                       <i class="fas fa-clock text-warning" style="font-size: 1.5rem;"></i>
                                   </div>
                               </div>
                               <div class="flex-grow-1 ms-3">
                                   <h6 class="text-muted mb-1">Pending</h6>
                                   <h4 class="mb-0"><?php echo $paymentStats['pending_count']; ?></h4>
                                   <small class="text-muted">Processing</small>
                               </div>
                           </div>
                       </div>
                   </div>
                   <div class="col-xl-3 col-md-6 mb-3">
                       <div class="stats-card p-4">
                           <div class="d-flex align-items-center">
                               <div class="flex-shrink-0">
                                   <div class="rounded-circle bg-info bg-opacity-10 p-3">
                                       <i class="fas fa-calendar-alt text-info" style="font-size: 1.5rem;"></i>
                                   </div>
                               </div>
                               <div class="flex-grow-1 ms-3">
                                   <h6 class="text-muted mb-1">This Month</h6>
                                   <h4 class="mb-0">$<?php echo number_format($paymentStats['month_amount'], 2); ?></h4>
                                   <small class="text-muted"><?php echo date('F Y'); ?></small>
                               </div>
                           </div>
                       </div>
                   </div>
               </div>
               
               <!-- Filters -->
               <div class="row mb-4">
                   <div class="col-12">
                       <div class="filter-card">
                           <div class="card-header border-bottom bg-light">
                               <h5 class="card-title mb-0">
                                   <i class="fas fa-filter me-2"></i>
                                   Filter Payments
                               </h5>
                           </div>
                           <div class="card-body">
                               <form method="GET" action="">
                                   <div class="row g-3">
                                       <div class="col-md-3">
                                           <label class="form-label fw-semibold">Status</label>
                                           <select name="status" class="form-select">
                                               <option value="">All Statuses</option>
                                               <option value="completed" <?php echo $status_filter === 'completed' ? 'selected' : ''; ?>>Completed</option>
                                               <option value="pending" <?php echo $status_filter === 'pending' ? 'selected' : ''; ?>>Pending</option>
                                               <option value="failed" <?php echo $status_filter === 'failed' ? 'selected' : ''; ?>>Failed</option>
                                               <option value="refunded" <?php echo $status_filter === 'refunded' ? 'selected' : ''; ?>>Refunded</option>
                                           </select>
                                       </div>
                                       <div class="col-md-3">
                                           <label class="form-label fw-semibold">From Date</label>
                                           <input type="date" name="date_from" class="form-control" value="<?php echo htmlspecialchars($date_from); ?>">
                                       </div>
                                       <div class="col-md-3">
                                           <label class="form-label fw-semibold">To Date</label>
                                           <input type="date" name="date_to" class="form-control" value="<?php echo htmlspecialchars($date_to); ?>">
                                       </div>
                                       <div class="col-md-3">
                                           <label class="form-label">&nbsp;</label>
                                           <div class="d-grid gap-2">
                                               <button type="submit" class="btn btn-primary">
                                                   <i class="fas fa-search me-2"></i>
                                                   Apply Filters
                                               </button>
                                           </div>
                                       </div>
                                   </div>
                                   <?php if ($status_filter || $date_from || $date_to): ?>
                                   <div class="mt-3">
                                       <a href="payment-history.php" class="btn btn-outline-secondary btn-sm">
                                           <i class="fas fa-times me-2"></i>
                                           Clear All Filters
                                       </a>
                                       <span class="text-muted ms-2">
                                           <?php 
                                           $filters = [];
                                           if ($status_filter) $filters[] = "Status: " . ucfirst($status_filter);
                                           if ($date_from) $filters[] = "From: " . date('M j, Y', strtotime($date_from));
                                           if ($date_to) $filters[] = "To: " . date('M j, Y', strtotime($date_to));
                                           echo implode(' • ', $filters);
                                           ?>
                                       </span>
                                   </div>
                                   <?php endif; ?>
                               </form>
                           </div>
                       </div>
                   </div>
               </div>
               
               <!-- Payment History -->
               <div class="row">
                   <div class="col-12">
                       <div class="card">
                           <div class="card-header border-bottom bg-light d-flex justify-content-between align-items-center">
                               <h5 class="card-title mb-0">
                                   <i class="fas fa-history me-2"></i>
                                   Payment Transactions
                               </h5>
                               <div class="text-muted">
                                   <i class="fas fa-info-circle me-1"></i>
                                   Showing <?php echo count($payments); ?> of <?php echo $total_payments; ?> transactions
                               </div>
                           </div>
                           <div class="card-body p-0">
                               <?php if (empty($payments)): ?>
                               <div class="text-center py-5">
                                   <div class="mb-4">
                                       <i class="fas fa-credit-card fa-4x text-muted"></i>
                                   </div>
                                   <h5 class="text-muted">No Payment History Found</h5>
                                   <p class="text-muted mb-4">
                                       <?php if ($status_filter || $date_from || $date_to): ?>
                                       No payments match your current filters. Try adjusting your search criteria.
                                       <?php else: ?>
                                       You haven't made any payments yet. Start browsing our plugin marketplace.
                                       <?php endif; ?>
                                   </p>
                                   <div class="d-flex gap-2 justify-content-center">
                                       <a href="browse-plugins.php" class="btn btn-primary">
                                           <i class="fas fa-shopping-cart me-2"></i>
                                           Browse Plugins
                                       </a>
                                       <?php if ($status_filter || $date_from || $date_to): ?>
                                       <a href="payment-history.php" class="btn btn-outline-secondary">
                                           <i class="fas fa-times me-2"></i>
                                           Clear Filters
                                       </a>
                                       <?php endif; ?>
                                   </div>
                               </div>
                               <?php else: ?>
                               <div class="table-responsive">
                                   <table class="table table-hover mb-0">
                                       <thead class="table-light">
                                           <tr>
                                               <th class="ps-4">Transaction Details</th>
                                               <th>Product</th>
                                               <th>Amount</th>
                                               <th>Payment Method</th>
                                               <th>Status</th>
                                               <th class="pe-4 text-center">Actions</th>
                                           </tr>
                                       </thead>
                                       <tbody>
                                           <?php foreach ($payments as $payment): ?>
                                           <tr class="transaction-row">
                                               <td class="ps-4">
                                                   <div class="d-flex align-items-center">
                                                       <div class="flex-shrink-0">
                                                           <div class="rounded-circle bg-primary bg-opacity-10 p-2">
                                                               <i class="fas fa-receipt text-primary"></i>
                                                           </div>
                                                       </div>
                                                       <div class="ms-3">
                                                           <h6 class="mb-1 fw-semibold"><?php echo htmlspecialchars($payment['transaction_id']); ?></h6>
                                                           <small class="text-muted">
                                                               <i class="fas fa-calendar me-1"></i>
                                                               <?php echo date('M j, Y \a\t g:i A', strtotime($payment['created_at'])); ?>
                                                           </small>
                                                       </div>
                                                   </div>
                                               </td>
                                               <td>
                                                   <div class="d-flex align-items-center">
                                                       <i class="fas fa-puzzle-piece me-2 text-success"></i>
                                                       <div>
                                                           <h6 class="mb-0"><?php echo htmlspecialchars($payment['product_name'] ?? 'Product Purchase'); ?></h6>
                                                           <small class="text-muted">
                                                               <?php echo htmlspecialchars($payment['plan_name'] ?? 'Standard License'); ?>
                                                           </small>
                                                       </div>
                                                   </div>
                                               </td>
                                               <td>
                                                   <div>
                                                       <h6 class="mb-0 fw-bold">
                                                           $<?php echo number_format($payment['amount'], 2); ?>
                                                       </h6>
                                                       <small class="text-muted">
                                                           <?php echo strtoupper($payment['currency']); ?>
                                                       </small>
                                                   </div>
                                               </td>
                                               <td>
                                                   <div class="d-flex align-items-center">
                                                       <i class="fas fa-mobile-alt me-2 text-info"></i>
                                                       <span class="fw-medium"><?php echo htmlspecialchars($payment['payment_method'] ?? 'Mobile Money'); ?></span>
                                                   </div>
                                               </td>
                                               <td>
                                                   <?php
                                                   $status = $payment['status'];
                                                   $badgeClass = 'status-' . $status;
                                                   $statusIcon = [
                                                       'completed' => 'check-circle',
                                                       'pending' => 'clock',
                                                       'failed' => 'times-circle',
                                                       'refunded' => 'undo'
                                                   ][$status] ?? 'question-circle';
                                                   ?>
                                                   <span class="status-badge <?php echo $badgeClass; ?>">
                                                       <i class="fas fa-<?php echo $statusIcon; ?> me-1"></i>
                                                       <?php echo ucfirst($status); ?>
                                                   </span>
                                               </td>
                                               <td class="pe-4">
                                                   <div class="btn-group btn-group-sm" role="group">
                                                       <a href="transaction-receipts.php?id=<?php echo $payment['payment_id']; ?>" 
                                                          class="btn btn-outline-primary" 
                                                          title="View Receipt">
                                                           <i class="fas fa-receipt"></i>
                                                       </a>
                                                       <?php if ($payment['status'] === 'completed'): ?>
                                                       <a href="download-invoice.php?payment=<?php echo $payment['payment_id']; ?>" 
                                                          class="btn btn-outline-secondary" 
                                                          title="Download Invoice">
                                                           <i class="fas fa-download"></i>
                                                       </a>
                                                       <?php endif; ?>
                                                       <?php if ($payment['status'] === 'failed'): ?>
                                                       <a href="retry-payment.php?id=<?php echo $payment['payment_id']; ?>" 
                                                          class="btn btn-outline-warning" 
                                                          title="Retry Payment">
                                                           <i class="fas fa-refresh"></i>
                                                       </a>
                                                       <?php endif; ?>
                                                   </div>
                                               </td>
                                           </tr>
                                           <?php endforeach; ?>
                                       </tbody>
                                   </table>
                               </div>
                               
                               <!-- Pagination -->
                               <?php if ($total_pages > 1): ?>
                               <div class="card-footer border-top bg-light">
                                   <div class="row align-items-center">
                                       <div class="col-md-6">
                                           <small class="text-muted">
                                               Showing <?php echo $offset + 1; ?>-<?php echo min($offset + $limit, $total_payments); ?> 
                                               of <?php echo $total_payments; ?> transactions
                                           </small>
                                       </div>
                                       <div class="col-md-6">
                                           <nav aria-label="Payment history pagination">
                                               <ul class="pagination pagination-rounded justify-content-end mb-0">
                                                   <?php if ($page > 1): ?>
                                                   <li class="page-item">
                                                       <a class="page-link" href="?page=<?php echo $page - 1; ?>&status=<?php echo $status_filter; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>">
                                                           <i class="fas fa-chevron-left"></i> Previous
                                                       </a>
                                                   </li>
                                                   <?php endif; ?>
                                                   
                                                   <?php for ($i = max(1, $page - 2); $i <= min($total_pages, $page + 2); $i++): ?>
                                                   <li class="page-item <?php echo $i == $page ? 'active' : ''; ?>">
                                                       <a class="page-link" href="?page=<?php echo $i; ?>&status=<?php echo $status_filter; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>">
                                                           <?php echo $i; ?>
                                                       </a>
                                                   </li>
                                                   <?php endfor; ?>
                                                   
                                                   <?php if ($page < $total_pages): ?>
                                                   <li class="page-item">
                                                       <a class="page-link" href="?page=<?php echo $page + 1; ?>&status=<?php echo $status_filter; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>">
                                                           Next <i class="fas fa-chevron-right"></i>
                                                      </a>
                                                   </li>
                                                   <?php endif; ?>
                                               </ul>
                                           </nav>
                                       </div>
                                   </div>
                               </div>
                               <?php endif; ?>
                               <?php endif; ?>
                           </div>
                       </div>
                   </div>
               </div>
               
               <!-- Quick Actions -->
               <div class="row mt-4">
                   <div class="col-12">
                       <div class="card">
                           <div class="card-header border-bottom bg-light">
                               <h5 class="card-title mb-0">
                                   <i class="fas fa-bolt me-2"></i>
                                   Quick Actions
                               </h5>
                           </div>
                           <div class="card-body">
                               <div class="row g-3">
                                   <div class="col-md-3">
                                       <a href="browse-plugins.php" class="btn btn-outline-primary w-100 d-flex align-items-center justify-content-center py-3">
                                           <div class="text-center">
                                               <i class="fas fa-shopping-cart fa-lg d-block mb-2"></i>
                                               <strong>Browse Plugins</strong>
                                               <small class="d-block text-muted">Discover new plugins</small>
                                           </div>
                                       </a>
                                   </div>
                                   <div class="col-md-3">
                                       <a href="wallet-topup.php" class="btn btn-outline-success w-100 d-flex align-items-center justify-content-center py-3">
                                           <div class="text-center">
                                               <i class="fas fa-wallet fa-lg d-block mb-2"></i>
                                               <strong>Top Up Wallet</strong>
                                               <small class="d-block text-muted">Add funds to wallet</small>
                                           </div>
                                       </a>
                                   </div>
                                   <div class="col-md-3">
                                       <a href="download-plugins.php" class="btn btn-outline-info w-100 d-flex align-items-center justify-content-center py-3">
                                           <div class="text-center">
                                               <i class="fas fa-download fa-lg d-block mb-2"></i>
                                               <strong>Download Plugins</strong>
                                               <small class="d-block text-muted">Get your purchases</small>
                                           </div>
                                       </a>
                                   </div>
                                   <div class="col-md-3">
                                       <a href="create-ticket.php" class="btn btn-outline-secondary w-100 d-flex align-items-center justify-content-center py-3">
                                           <div class="text-center">
                                               <i class="fas fa-question-circle fa-lg d-block mb-2"></i>
                                               <strong>Get Support</strong>
                                               <small class="d-block text-muted">Contact our team</small>
                                           </div>
                                       </a>
                                   </div>
                               </div>
                           </div>
                       </div>
                   </div>
               </div>
               
               <!-- Export Options -->
               <?php if (!empty($payments)): ?>
               <div class="row mt-4">
                   <div class="col-12">
                       <div class="card border-dashed">
                           <div class="card-body text-center py-4">
                               <h6 class="mb-3">
                                   <i class="fas fa-file-export me-2"></i>
                                   Export Payment History
                               </h6>
                               <div class="d-flex gap-2 justify-content-center">
                                   <a href="export-payments.php?format=csv&<?php echo http_build_query(['status' => $status_filter, 'date_from' => $date_from, 'date_to' => $date_to]); ?>" 
                                      class="btn btn-outline-success btn-sm">
                                       <i class="fas fa-file-csv me-1"></i>
                                       Export as CSV
                                   </a>
                                   <a href="export-payments.php?format=pdf&<?php echo http_build_query(['status' => $status_filter, 'date_from' => $date_from, 'date_to' => $date_to]); ?>" 
                                      class="btn btn-outline-danger btn-sm">
                                       <i class="fas fa-file-pdf me-1"></i>
                                       Export as PDF
                                   </a>
                                   <button onclick="window.print()" class="btn btn-outline-secondary btn-sm">
                                       <i class="fas fa-print me-1"></i>
                                       Print Report
                                   </button>
                               </div>
                               <small class="text-muted d-block mt-2">
                                   Export includes all transactions matching your current filters
                               </small>
                           </div>
                       </div>
                   </div>
               </div>
               <?php endif; ?>
               
           </div>
       </div>
   </div>
</div>

<?php 
if (file_exists('partials/footer.php')) {
   try {
       include_once 'partials/footer.php';
   } catch (Exception $e) {
       echo '<footer class="bg-light text-center py-3 mt-5">
               <div class="container">
                   <p class="mb-0">&copy; 2024 ConnectPay Platform. All rights reserved.</p>
               </div>
             </footer>';
   }
}
?>

<?php 
if (file_exists('partials/footer-scripts.php')) {
   try {
       include_once 'partials/footer-scripts.php';
   } catch (Exception $e) {
       echo '<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>' . "\n";
   }
}
?>

<script>
document.addEventListener('DOMContentLoaded', function() {
   // Auto-submit form when status changes
   const statusSelect = document.querySelector('select[name="status"]');
   if (statusSelect) {
       statusSelect.addEventListener('change', function() {
           // Add a small delay to allow user to see the selection
           setTimeout(() => {
               this.form.submit();
           }, 150);
       });
   }
   
   // Copy transaction ID to clipboard
   document.querySelectorAll('.transaction-row h6').forEach(element => {
       if (element.textContent.match(/^[A-Z0-9]{8,}/)) {
           element.style.cursor = 'pointer';
           element.title = 'Click to copy transaction ID';
           
           element.addEventListener('click', function(e) {
               e.preventDefault();
               const transactionId = this.textContent.trim();
               
               navigator.clipboard.writeText(transactionId).then(() => {
                   // Show success feedback
                   const original = this.innerHTML;
                   this.innerHTML = '<i class="fas fa-check text-success me-1"></i>Copied!';
                   this.className = 'mb-1 fw-semibold text-success';
                   
                   setTimeout(() => {
                       this.innerHTML = original;
                       this.className = 'mb-1 fw-semibold';
                   }, 2000);
               }).catch(err => {
                   console.error('Failed to copy: ', err);
                   // Fallback for older browsers
                   const textArea = document.createElement('textarea');
                   textArea.value = transactionId;
                   document.body.appendChild(textArea);
                   textArea.select();
                   document.execCommand('copy');
                   document.body.removeChild(textArea);
                   
                   // Show feedback
                   const original = this.innerHTML;
                   this.innerHTML = '<i class="fas fa-check text-success me-1"></i>Copied!';
                   setTimeout(() => {
                       this.innerHTML = original;
                   }, 2000);
               });
           });
       }
   });
   
   // Enhanced table row interactions
   document.querySelectorAll('.transaction-row').forEach(row => {
       row.addEventListener('click', function(e) {
           // Only trigger if not clicking on action buttons
           if (!e.target.closest('.btn-group')) {
               const receiptLink = this.querySelector('a[href*="transaction-receipts"]');
               if (receiptLink) {
                   window.location.href = receiptLink.href;
               }
           }
       });
   });
   
   // Tooltip initialization for action buttons
   const tooltipTriggerList = [].slice.call(document.querySelectorAll('[title]'));
   tooltipTriggerList.map(function (tooltipTriggerEl) {
       return new bootstrap.Tooltip(tooltipTriggerEl);
   });
   
   // Real-time filter updates
   const dateInputs = document.querySelectorAll('input[type="date"]');
   dateInputs.forEach(input => {
       input.addEventListener('change', function() {
           // Auto-submit if both dates are filled
           const dateFrom = document.querySelector('input[name="date_from"]').value;
           const dateTo = document.querySelector('input[name="date_to"]').value;
           
           if (dateFrom && dateTo && dateFrom <= dateTo) {
               setTimeout(() => {
                   this.form.submit();
               }, 500);
           }
       });
   });
   
   // Smooth scroll to top after pagination
   if (window.location.search.includes('page=')) {
       document.querySelector('.payment-header').scrollIntoView({ 
           behavior: 'smooth',
           block: 'start'
       });
   }
   
   // Print styles enhancement
   window.addEventListener('beforeprint', function() {
       document.body.classList.add('printing');
   });
   
   window.addEventListener('afterprint', function() {
       document.body.classList.remove('printing');
   });
});

// Function to show toast notifications
function showToast(message, type = 'info') {
   const toastContainer = document.getElementById('toast-container') || createToastContainer();
   
   const toast = document.createElement('div');
   toast.className = `toast align-items-center text-white bg-${type} border-0`;
   toast.setAttribute('role', 'alert');
   toast.innerHTML = `
       <div class="d-flex">
           <div class="toast-body">
               <i class="fas fa-${type === 'success' ? 'check' : 'info'}-circle me-2"></i>
               ${message}
           </div>
           <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
       </div>
   `;
   
   toastContainer.appendChild(toast);
   
   const bsToast = new bootstrap.Toast(toast);
   bsToast.show();
   
   // Remove toast element after it's hidden
   toast.addEventListener('hidden.bs.toast', function() {
       toast.remove();
   });
}

function createToastContainer() {
   const container = document.createElement('div');
   container.id = 'toast-container';
   container.className = 'toast-container position-fixed top-0 end-0 p-3';
   container.style.zIndex = '9999';
   document.body.appendChild(container);
   return container;
}

// Enhanced export functionality
function exportPayments(format) {
   const currentFilters = new URLSearchParams(window.location.search);
   const exportUrl = `export-payments.php?format=${format}&${currentFilters.toString()}`;
   
   // Show loading state
   showToast('Preparing export...', 'info');
   
   // Create hidden iframe for download
   const iframe = document.createElement('iframe');
   iframe.style.display = 'none';
   iframe.src = exportUrl;
   document.body.appendChild(iframe);
   
   // Clean up iframe after download
   setTimeout(() => {
       document.body.removeChild(iframe);
       showToast('Export completed!', 'success');
   }, 3000);
}
</script>

<style>
/* Additional print styles */
@media print {
   .no-print, .btn, .pagination, .card-footer {
       display: none !important;
   }
   
   .card {
       border: 1px solid #000 !important;
       box-shadow: none !important;
   }
   
   .table th {
       background-color: #f8f9fa !important;
       -webkit-print-color-adjust: exact;
   }
   
   .status-badge {
       border: 1px solid #000 !important;
       -webkit-print-color-adjust: exact;
   }
}

/* Enhanced hover effects */
.transaction-row {
   cursor: pointer;
   transition: all 0.2s ease;
}

.transaction-row:hover {
   background-color: #f8fafc !important;
   transform: translateX(2px);
}

/* Loading states */
.btn.loading {
   opacity: 0.7;
   cursor: not-allowed;
}

.btn.loading::after {
   content: '';
   display: inline-block;
   width: 12px;
   height: 12px;
   margin-left: 8px;
   border: 2px solid transparent;
   border-top: 2px solid currentColor;
   border-radius: 50%;
   animation: spin 1s linear infinite;
}

@keyframes spin {
   to {
       transform: rotate(360deg);
   }
}

/* Border dashed utility */
.border-dashed {
   border: 2px dashed #e2e8f0 !important;
}

.border-dashed:hover {
   border-color: #3b82f6 !important;
   background-color: #f8fafc;
}

/* Enhanced responsive design */
@media (max-width: 768px) {
   .stats-card {
       margin-bottom: 1rem;
   }
   
   .table-responsive {
       font-size: 0.875rem;
   }
   
   .btn-group-sm .btn {
       padding: 0.375rem 0.5rem;
   }
   
   .payment-header {
       padding: 1.5rem;
       text-align: center;
   }
   
   .breadcrumb {
       justify-content: center !important;
       margin-top: 1rem;
   }
}

/* Dark mode support (if needed) */
@media (prefers-color-scheme: dark) {
   .stats-card {
       background-color: #1f2937;
       border-color: #374151;
       color: #f9fafb;
   }
   
   .filter-card {
       background-color: #1f2937;
       border-color: #374151;
   }
}
</style>

</body>
</html>       