<?php
/**
 * Payments List
 * LandSales Pro - View all subscription payments
 */
define('APP_RUNNING', true);
require_once '../../db_connect.php';
require_once '../../includes/auth.php';
require_once '../../includes/subscription.php';

initSecureSession();
requireRole(['super_admin', 'admin']);

// Check for success message
$successMessage = $_GET['success'] ?? null;

// Date filter
$dateFrom = $_GET['from'] ?? date('Y-m-01');
$dateTo = $_GET['to'] ?? date('Y-m-d');

// Pagination
$page = max(1, intval($_GET['page'] ?? 1));
$perPage = 20;
$offset = ($page - 1) * $perPage;

// Get payments
$sql = "SELECT sp.*, u.full_name, u.email, p.name as plan_name,
               admin.full_name as recorded_by_name
        FROM subscription_payments sp
        JOIN users u ON sp.user_id = u.id
        JOIN subscriptions s ON sp.subscription_id = s.id
        JOIN plans p ON s.plan_id = p.id
        LEFT JOIN users admin ON sp.recorded_by = admin.id
        WHERE sp.payment_date BETWEEN ? AND ?
        ORDER BY sp.payment_date DESC, sp.created_at DESC
        LIMIT {$perPage} OFFSET {$offset}";

$payments = db_fetch_all($sql, 'ss', [$dateFrom, $dateTo]);

$countSql = "SELECT COUNT(*) as total FROM subscription_payments WHERE payment_date BETWEEN ? AND ?";
$total = db_fetch_one($countSql, 'ss', [$dateFrom, $dateTo])['total'];
$totalPages = ceil($total / $perPage);

// Total for period
$totalAmount = db_fetch_one("SELECT COALESCE(SUM(amount), 0) as total FROM subscription_payments WHERE payment_date BETWEEN ? AND ? AND status = 'confirmed'", 'ss', [$dateFrom, $dateTo])['total'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Payments - <?php echo APP_NAME; ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="<?php echo SITE_URL; ?>/assets/font-awesome/css/all.min.css">
</head>
<body>
    <?php include '../includes/sidebar.php'; ?>

    <div class="main-content">
        <div class="top-header">
            <button class="menu-toggle" onclick="toggleSidebar()">
                <i class="fas fa-bars"></i>
            </button>
            <h1 class="page-title">Payments</h1>
            <div class="header-actions">
                <a href="record-payment.php" class="btn btn-primary">
                    <i class="fas fa-plus"></i> Record Payment
                </a>
            </div>
        </div>

        <div class="content-wrapper">
            <?php if ($successMessage): ?>
            <div class="alert alert-success">
                <i class="fas fa-check-circle"></i>
                Payment recorded successfully!
            </div>
            <?php endif; ?>

            <!-- Summary -->
            <div class="summary-card">
                <div class="summary-icon">
                    <i class="fas fa-money-bill-wave"></i>
                </div>
                <div class="summary-content">
                    <div class="summary-label">Total Revenue (<?php echo date('M j', strtotime($dateFrom)); ?> - <?php echo date('M j, Y', strtotime($dateTo)); ?>)</div>
                    <div class="summary-value">TZS <?php echo number_format($totalAmount); ?></div>
                </div>
            </div>

            <!-- Filters -->
            <div class="filters-card">
                <form class="filters-form" method="GET">
                    <div class="filter-group">
                        <label>From</label>
                        <input type="date" name="from" class="form-control" value="<?php echo $dateFrom; ?>">
                    </div>
                    <div class="filter-group">
                        <label>To</label>
                        <input type="date" name="to" class="form-control" value="<?php echo $dateTo; ?>">
                    </div>
                    <button type="submit" class="btn btn-primary btn-sm">Filter</button>
                    <a href="?from=<?php echo date('Y-m-01'); ?>&to=<?php echo date('Y-m-d'); ?>" class="btn btn-outline btn-sm">This Month</a>
                </form>
            </div>

            <!-- Table -->
            <div class="card">
                <div class="table-responsive">
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th>Receipt</th>
                                <th>Subscriber</th>
                                <th>Plan</th>
                                <th>Amount</th>
                                <th>Method</th>
                                <th>Date</th>
                                <th>Recorded By</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($payments)): ?>
                            <tr>
                                <td colspan="7" class="empty-row">
                                    <div class="empty-state">
                                        <i class="fas fa-receipt"></i>
                                        <p>No payments found for this period</p>
                                    </div>
                                </td>
                            </tr>
                            <?php else: ?>
                            <?php foreach ($payments as $payment): ?>
                            <tr>
                                <td>
                                    <span class="receipt-number"><?php echo $payment['receipt_number']; ?></span>
                                </td>
                                <td>
                                    <div class="user-cell">
                                        <div class="user-avatar">
                                            <?php echo strtoupper(substr($payment['full_name'], 0, 1)); ?>
                                        </div>
                                        <div>
                                            <div class="user-name"><?php echo htmlspecialchars($payment['full_name']); ?></div>
                                            <div class="user-email"><?php echo htmlspecialchars($payment['email']); ?></div>
                                        </div>
                                    </div>
                                </td>
                                <td><?php echo $payment['plan_name']; ?></td>
                                <td>
                                    <span class="amount">TZS <?php echo number_format($payment['amount']); ?></span>
                                </td>
                                <td>
                                    <span class="method-badge method-<?php echo $payment['payment_method']; ?>">
                                        <?php echo ucfirst(str_replace('_', ' ', $payment['payment_method'])); ?>
                                    </span>
                                    <?php if ($payment['reference_number']): ?>
                                    <div class="reference"><?php echo $payment['reference_number']; ?></div>
                                    <?php endif; ?>
                                </td>
                                <td><?php echo date('M j, Y', strtotime($payment['payment_date'])); ?></td>
                                <td>
                                    <span class="recorded-by"><?php echo htmlspecialchars($payment['recorded_by_name'] ?? 'System'); ?></span>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>

                <?php if ($totalPages > 1): ?>
                <div class="pagination-wrapper">
                    <div class="pagination">
                        <?php if ($page > 1): ?>
                        <a href="?page=<?php echo $page - 1; ?>&from=<?php echo $dateFrom; ?>&to=<?php echo $dateTo; ?>" class="page-link">
                            <i class="fas fa-chevron-left"></i>
                        </a>
                        <?php endif; ?>

                        <?php for ($i = max(1, $page - 2); $i <= min($totalPages, $page + 2); $i++): ?>
                        <a href="?page=<?php echo $i; ?>&from=<?php echo $dateFrom; ?>&to=<?php echo $dateTo; ?>"
                           class="page-link <?php echo $i === $page ? 'active' : ''; ?>">
                            <?php echo $i; ?>
                        </a>
                        <?php endfor; ?>

                        <?php if ($page < $totalPages): ?>
                        <a href="?page=<?php echo $page + 1; ?>&from=<?php echo $dateFrom; ?>&to=<?php echo $dateTo; ?>" class="page-link">
                            <i class="fas fa-chevron-right"></i>
                        </a>
                        <?php endif; ?>
                    </div>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <style>
        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
            margin: 0;
            background: #f1f5f9;
        }

        .header-actions { display: flex; gap: 0.75rem; }

        .btn {
            padding: 0.625rem 1.25rem;
            border-radius: 8px;
            font-weight: 500;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            transition: all 0.2s;
            border: none;
            cursor: pointer;
            font-size: 0.875rem;
        }

        .btn-sm { padding: 0.5rem 1rem; }

        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .btn-outline {
            border: 1px solid #e2e8f0;
            background: white;
            color: #64748b;
        }

        .alert {
            padding: 1rem 1.5rem;
            border-radius: 10px;
            margin-bottom: 1.5rem;
            display: flex;
            align-items: center;
            gap: 0.75rem;
        }

        .alert-success {
            background: #dcfce7;
            color: #166534;
            border: 1px solid #bbf7d0;
        }

        .summary-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 16px;
            padding: 1.5rem 2rem;
            color: white;
            display: flex;
            align-items: center;
            gap: 1.5rem;
            margin-bottom: 1.5rem;
        }

        .summary-icon {
            width: 60px;
            height: 60px;
            background: rgba(255,255,255,0.2);
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.5rem;
        }

        .summary-label {
            font-size: 0.9rem;
            opacity: 0.9;
            margin-bottom: 0.25rem;
        }

        .summary-value {
            font-size: 2rem;
            font-weight: 700;
        }

        .filters-card {
            background: white;
            border-radius: 12px;
            padding: 1rem 1.5rem;
            margin-bottom: 1.5rem;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
        }

        .filters-form {
            display: flex;
            gap: 1rem;
            align-items: flex-end;
        }

        .filter-group label {
            display: block;
            font-size: 0.8rem;
            font-weight: 500;
            color: #64748b;
            margin-bottom: 0.25rem;
        }

        .form-control {
            padding: 0.5rem 0.75rem;
            border: 1px solid #e2e8f0;
            border-radius: 6px;
            font-size: 0.875rem;
        }

        .card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
            overflow: hidden;
        }

        .table-responsive { overflow-x: auto; }

        .data-table {
            width: 100%;
            border-collapse: collapse;
        }

        .data-table th, .data-table td {
            padding: 1rem;
            text-align: left;
            border-bottom: 1px solid #f1f5f9;
        }

        .data-table th {
            background: #f8fafc;
            font-weight: 600;
            font-size: 0.75rem;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            color: #64748b;
        }

        .data-table tbody tr:hover { background: #f8fafc; }

        .receipt-number {
            font-family: monospace;
            font-weight: 600;
            color: #667eea;
        }

        .user-cell {
            display: flex;
            align-items: center;
            gap: 0.75rem;
        }

        .user-avatar {
            width: 36px;
            height: 36px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 8px;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            font-size: 0.8rem;
        }

        .user-name { font-weight: 500; color: #1e293b; }
        .user-email { font-size: 0.8rem; color: #64748b; }

        .amount {
            font-weight: 600;
            color: #16a34a;
        }

        .method-badge {
            padding: 0.25rem 0.5rem;
            border-radius: 4px;
            font-size: 0.75rem;
            font-weight: 500;
            background: #f1f5f9;
            color: #64748b;
        }

        .method-mpesa { background: #dcfce7; color: #16a34a; }
        .method-tigopesa { background: #dbeafe; color: #2563eb; }
        .method-airtel { background: #fee2e2; color: #dc2626; }
        .method-bank_transfer { background: #f3e8ff; color: #7c3aed; }
        .method-cash { background: #fef3c7; color: #d97706; }

        .reference {
            font-size: 0.75rem;
            color: #94a3b8;
            margin-top: 0.25rem;
        }

        .recorded-by {
            font-size: 0.85rem;
            color: #64748b;
        }

        .empty-row td { padding: 3rem; }
        .empty-state { text-align: center; color: #94a3b8; }
        .empty-state i { font-size: 2.5rem; margin-bottom: 0.75rem; }

        .pagination-wrapper {
            padding: 1rem 1.5rem;
            border-top: 1px solid #f1f5f9;
            display: flex;
            justify-content: center;
        }

        .pagination { display: flex; gap: 0.25rem; }

        .page-link {
            padding: 0.5rem 0.75rem;
            border-radius: 6px;
            text-decoration: none;
            color: #64748b;
            font-weight: 500;
            font-size: 0.875rem;
        }

        .page-link:hover { background: #f1f5f9; }
        .page-link.active { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; }

        @media (max-width: 768px) {
            .filters-form { flex-wrap: wrap; }
            .summary-card { flex-direction: column; text-align: center; }
        }
    </style>
</body>
</html>
