<?php
session_start();
require_once 'config.php';

// Check if user is Super Admin
if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true || $_SESSION["role"] !== 0) {
    header("location: login.php");
    exit;
}

$user_id = $_SESSION["id"];
$username = htmlspecialchars($_SESSION["username"]);
$phone_number = $photo = "";

// Fetch user details
if (isset($conn) && $conn instanceof mysqli) {
    $sql = "SELECT phone_number, photo FROM users WHERE id = ?";
    if ($stmt = $conn->prepare($sql)) {
        $stmt->bind_param("i", $user_id);
        if ($stmt->execute()) {
            $stmt->bind_result($phone_number_db, $photo_db);
            $stmt->fetch();
            $phone_number = htmlspecialchars($phone_number_db ?? 'N/A');
            $photo = !empty($photo_db) ? htmlspecialchars($photo_db) : 'data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" width="80" height="80"%3E%3Crect width="80" height="80" fill="%234f46e5"/%3E%3Ctext x="50%25" y="50%25" dominant-baseline="middle" text-anchor="middle" font-family="Arial, sans-serif" font-size="32" font-weight="bold" fill="white"%3ESA%3C/text%3E%3C/svg%3E';
        }
        $stmt->close();
    }
}

// Fetch payment statistics
$totalPayments = $pendingPayments = $completedPayments = $totalRevenue = 0;
$paymentsList = [];

if (isset($conn) && $conn instanceof mysqli) {
    // Total payments count
    $sql = "SELECT COUNT(*) as count FROM invoices";
    if ($result = $conn->query($sql)) {
        $row = $result->fetch_assoc();
        $totalPayments = $row['count'];
        $result->free();
    }
    
    // Pending payments
    $sql = "SELECT COUNT(*) as count FROM invoices WHERE status = 'pending'";
    if ($result = $conn->query($sql)) {
        $row = $result->fetch_assoc();
        $pendingPayments = $row['count'];
        $result->free();
    }
    
    // Completed payments
    $sql = "SELECT COUNT(*) as count FROM invoices WHERE status = 'paid'";
    if ($result = $conn->query($sql)) {
        $row = $result->fetch_assoc();
        $completedPayments = $row['count'];
        $result->free();
    }
    
    // Total revenue
    $sql = "SELECT SUM(amount) as total FROM invoices WHERE status = 'paid'";
    if ($result = $conn->query($sql)) {
        $row = $result->fetch_assoc();
        $totalRevenue = $row['total'] ?? 0;
        $result->free();
    }
    
    // Fetch all payments with school details
    $filter = $_GET['filter'] ?? 'all';
    $whereSql = "";
    if ($filter === 'pending') {
        $whereSql = "WHERE i.status = 'pending'";
    } elseif ($filter === 'paid') {
        $whereSql = "WHERE i.status = 'paid'";
    } elseif ($filter === 'overdue') {
        $whereSql = "WHERE i.status = 'pending' AND i.due_date < CURDATE()";
    }
    
    $sql = "SELECT i.*, s.school_name 
            FROM invoices i 
            LEFT JOIN schools s ON i.school_id = s.school_id 
            $whereSql
            ORDER BY i.created_at DESC 
            LIMIT 100";
    if ($result = $conn->query($sql)) {
        while ($row = $result->fetch_assoc()) {
            $paymentsList[] = $row;
        }
        $result->free();
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Payments - Super Admin</title>
    <link rel="stylesheet" href="super_admin_layout.css">
    <link rel="icon" href="images/logo.png" type="image/png">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        .payments-container {
            max-width: 1400px;
            margin: 0 auto;
        }

        .payment-stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .stat-card {
            background: white;
            padding: 25px;
            border-radius: 12px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            text-align: center;
        }

        .stat-card.total { background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%); color: white; }
        .stat-card.pending { background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%); color: white; }
        .stat-card.completed { background: linear-gradient(135deg, #10b981 0%, #059669 100%); color: white; }
        .stat-card.revenue { background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%); color: white; }

        .stat-card i {
            font-size: 2.5em;
            margin-bottom: 15px;
            opacity: 0.9;
        }

        .stat-card h3 {
            font-size: 2.5em;
            margin: 10px 0;
        }

        .stat-card p {
            opacity: 0.9;
            font-size: 1.1em;
        }

        .filter-tabs {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }

        .filter-tab {
            padding: 12px 24px;
            border: 2px solid #e5e7eb;
            background: white;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s;
            text-decoration: none;
            color: #333;
            font-weight: 500;
        }

        .filter-tab:hover {
            border-color: #4f46e5;
            background: #f0f0ff;
        }

        .filter-tab.active {
            background: #4f46e5;
            color: white;
            border-color: #4f46e5;
        }

        .payments-table-card {
            background: white;
            padding: 30px;
            border-radius: 12px;
            box-shadow: 0 6px 15px rgba(0, 0, 0, 0.08);
        }

        .payments-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }

        .payments-table th,
        .payments-table td {
            border: 1px solid #eee;
            padding: 12px;
            text-align: left;
        }

        .payments-table th {
            background-color: #f8f9fa;
            font-weight: 600;
            color: #555;
        }

        .payments-table tbody tr:hover {
            background-color: #f9fafb;
        }

        .status-badge {
            padding: 6px 14px;
            border-radius: 12px;
            font-size: 0.85em;
            font-weight: 600;
        }

        .status-paid { background-color: #d1fae5; color: #065f46; }
        .status-pending { background-color: #fef3c7; color: #92400e; }
        .status-overdue { background-color: #fee2e2; color: #991b1b; }

        .btn {
            padding: 6px 12px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 0.85em;
            transition: all 0.2s ease;
        }

        .btn-info {
            background-color: #3b82f6;
            color: white;
        }

        .btn-info:hover {
            background-color: #2563eb;
        }

        /* Modal Styles */
        .modal {
            display: none;
            position: fixed;
            z-index: 9999;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0, 0, 0, 0.5);
            animation: fadeIn 0.3s;
        }

        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }

        .modal-content {
            background-color: #fefefe;
            margin: 5% auto;
            padding: 30px;
            border: 1px solid #888;
            border-radius: 12px;
            width: 90%;
            max-width: 600px;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3);
            animation: slideDown 0.3s;
        }

        @keyframes slideDown {
            from {
                transform: translateY(-50px);
                opacity: 0;
            }
            to {
                transform: translateY(0);
                opacity: 1;
            }
        }

        .modal-header {
            display: flex;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 2px solid #e5e7eb;
        }

        .modal-header i {
            font-size: 2.5em;
            margin-right: 15px;
            color: #4f46e5;
        }

        .modal-header h3 {
            margin: 0;
            color: #333;
        }

        .modal-body {
            margin-bottom: 25px;
            color: #666;
            line-height: 1.6;
        }

        .detail-row {
            display: flex;
            justify-content: space-between;
            padding: 12px 0;
            border-bottom: 1px solid #f0f0f0;
        }

        .detail-row:last-child {
            border-bottom: none;
        }

        .detail-label {
            font-weight: 600;
            color: #555;
        }

        .detail-value {
            color: #333;
        }

        .modal-footer {
            display: flex;
            gap: 10px;
            justify-content: flex-end;
            padding-top: 15px;
            border-top: 2px solid #e5e7eb;
        }

        .btn-modal {
            padding: 10px 24px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 15px;
            font-weight: 600;
            transition: all 0.2s;
        }

        .btn-close {
            background-color: #4f46e5;
            color: white;
        }

        .btn-close:hover {
            background-color: #4338ca;
        }
    </style>
</head>
<body>
    <div class="dashboard-container" id="dashboardContainer">
        <?php include 'includes/super_admin_sidebar.php'; ?>
        
        <div class="main-content">
            <?php include 'includes/super_admin_header.php'; ?>
            
            <div class="dashboard-content">
                <div class="payments-container">
                    <h2><i class="fas fa-credit-card"></i> Payment Management</h2>

                    <!-- Payment Statistics -->
                    <div class="payment-stats">
                        <div class="stat-card total">
                            <i class="fas fa-file-invoice-dollar"></i>
                            <h3><?php echo $totalPayments; ?></h3>
                            <p>Total Invoices</p>
                        </div>
                        <div class="stat-card pending">
                            <i class="fas fa-clock"></i>
                            <h3><?php echo $pendingPayments; ?></h3>
                            <p>Pending Payments</p>
                        </div>
                        <div class="stat-card completed">
                            <i class="fas fa-check-circle"></i>
                            <h3><?php echo $completedPayments; ?></h3>
                            <p>Completed Payments</p>
                        </div>
                        <div class="stat-card revenue">
                            <i class="fas fa-money-bill-wave"></i>
                            <h3>UGX <?php echo number_format($totalRevenue); ?></h3>
                            <p>Total Revenue</p>
                        </div>
                    </div>

                    <!-- Filter Tabs -->
                    <div class="filter-tabs">
                        <a href="?filter=all" class="filter-tab <?php echo (!isset($_GET['filter']) || $_GET['filter'] === 'all') ? 'active' : ''; ?>">
                            <i class="fas fa-list"></i> All Payments
                        </a>
                        <a href="?filter=pending" class="filter-tab <?php echo (isset($_GET['filter']) && $_GET['filter'] === 'pending') ? 'active' : ''; ?>">
                            <i class="fas fa-clock"></i> Pending
                        </a>
                        <a href="?filter=paid" class="filter-tab <?php echo (isset($_GET['filter']) && $_GET['filter'] === 'paid') ? 'active' : ''; ?>">
                            <i class="fas fa-check"></i> Paid
                        </a>
                        <a href="?filter=overdue" class="filter-tab <?php echo (isset($_GET['filter']) && $_GET['filter'] === 'overdue') ? 'active' : ''; ?>">
                            <i class="fas fa-exclamation-triangle"></i> Overdue
                        </a>
                    </div>

                    <!-- Payments Table -->
                    <div class="payments-table-card">
                        <h3><i class="fas fa-table"></i> Payment Records</h3>
                        <div style="overflow-x: auto;">
                            <table class="payments-table">
                                <thead>
                                    <tr>
                                        <th>Invoice #</th>
                                        <th>School</th>
                                        <th>Amount</th>
                                        <th>Due Date</th>
                                        <th>Created</th>
                                        <th>Status</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if (empty($paymentsList)): ?>
                                        <tr>
                                            <td colspan="7" style="text-align: center; padding: 40px; color: #999;">
                                                <i class="fas fa-inbox" style="font-size: 3em; display: block; margin-bottom: 15px;"></i>
                                                No payments found.
                                            </td>
                                        </tr>
                                    <?php else: ?>
                                        <?php foreach ($paymentsList as $payment): 
                                            $isOverdue = ($payment['status'] === 'pending' && strtotime($payment['due_date']) < time());
                                            $statusClass = $payment['status'] === 'paid' ? 'status-paid' : ($isOverdue ? 'status-overdue' : 'status-pending');
                                            $statusText = $payment['status'] === 'paid' ? 'Paid' : ($isOverdue ? 'Overdue' : 'Pending');
                                        ?>
                                        <tr>
                                            <td><strong>#<?php echo str_pad($payment['invoice_id'], 5, '0', STR_PAD_LEFT); ?></strong></td>
                                            <td><?php echo htmlspecialchars($payment['school_name'] ?? 'N/A'); ?></td>
                                            <td><strong>UGX <?php echo number_format($payment['amount']); ?></strong></td>
                                            <td><?php echo date('M d, Y', strtotime($payment['due_date'])); ?></td>
                                            <td><?php echo date('M d, Y', strtotime($payment['created_at'])); ?></td>
                                            <td><span class="status-badge <?php echo $statusClass; ?>"><?php echo $statusText; ?></span></td>
                                            <td>
                                                <button class="btn btn-info" 
                                                    data-invoice="<?php echo str_pad($payment['invoice_id'], 5, '0', STR_PAD_LEFT); ?>"
                                                    data-school="<?php echo htmlspecialchars($payment['school_name'] ?? 'N/A', ENT_QUOTES); ?>"
                                                    data-amount="<?php echo number_format($payment['amount']); ?>"
                                                    data-due="<?php echo date('M d, Y', strtotime($payment['due_date'])); ?>"
                                                    data-created="<?php echo date('M d, Y', strtotime($payment['created_at'])); ?>"
                                                    data-status="<?php echo $statusText; ?>"
                                                    onclick="viewPaymentDetails(this)" 
                                                    title="View Details">
                                                    <i class="fas fa-eye"></i>
                                                </button>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <?php include 'includes/super_admin_mobile_nav.php'; ?>
    </div>

    <!-- Payment Details Modal -->
    <div id="paymentModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <i class="fas fa-file-invoice-dollar"></i>
                <h3>Payment Details</h3>
            </div>
            <div class="modal-body">
                <div class="detail-row">
                    <span class="detail-label">Invoice Number:</span>
                    <span class="detail-value" id="detail_invoice_number"></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">School Name:</span>
                    <span class="detail-value" id="detail_school_name"></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">Amount:</span>
                    <span class="detail-value" id="detail_amount" style="font-size: 1.2em; font-weight: bold; color: #4f46e5;"></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">Due Date:</span>
                    <span class="detail-value" id="detail_due_date"></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">Created Date:</span>
                    <span class="detail-value" id="detail_created_date"></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">Status:</span>
                    <span class="detail-value" id="detail_status"></span>
                </div>
            </div>
            <div class="modal-footer">
                <button onclick="closeModal()" class="btn-modal btn-close">
                    <i class="fas fa-times"></i> Close
                </button>
            </div>
        </div>
    </div>

    <script>
        // View payment details function
        function viewPaymentDetails(button) {
            const invoiceNum = button.getAttribute('data-invoice');
            const schoolName = button.getAttribute('data-school');
            const amount = button.getAttribute('data-amount');
            const dueDate = button.getAttribute('data-due');
            const createdDate = button.getAttribute('data-created');
            const status = button.getAttribute('data-status');
            
            document.getElementById('detail_invoice_number').textContent = '#' + invoiceNum;
            document.getElementById('detail_school_name').textContent = schoolName;
            document.getElementById('detail_amount').textContent = 'UGX ' + amount;
            document.getElementById('detail_due_date').textContent = dueDate;
            document.getElementById('detail_created_date').textContent = createdDate;
            
            const statusElement = document.getElementById('detail_status');
            statusElement.textContent = status;
            statusElement.className = 'status-badge ';
            if (status === 'Paid') {
                statusElement.className += 'status-paid';
            } else if (status === 'Overdue') {
                statusElement.className += 'status-overdue';
            } else {
                statusElement.className += 'status-pending';
            }
            
            document.getElementById('paymentModal').style.display = 'block';
        }

        function closeModal() {
            document.getElementById('paymentModal').style.display = 'none';
        }

        // Sidebar toggle
        const menuToggle = document.getElementById('menuToggle');
        const sidebar = document.getElementById('sidebar');
        const dashboardContainer = document.getElementById('dashboardContainer');
        
        if (menuToggle) {
            menuToggle.addEventListener('click', function() {
                sidebar.classList.toggle('collapsed');
                dashboardContainer.classList.toggle('sidebar-collapsed');
            });
        }
        window.onclick = function(event) {
            if (event.target.classList.contains('modal')) {
                event.target.style.display = 'none';
            }
        }
    </script>
</body>
</html>
<?php
if (isset($conn) && $conn instanceof mysqli && $conn->ping()) {
    $conn->close();
}
?>