<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
include "../include/config.php";

if (isset($_SESSION['studentid'])) {
    $userlogin = $_SESSION['studentid'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Association Fees & Payments</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@300;400;500;600&display=swap" rel="stylesheet">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>
    <meta name="theme-color" content="var(--primary)">
    
    <style>
        :root {
            --primary-color: #1a73e8;
            --secondary-color: #2c3e50;
            --success-color: #0f9d58;
            --warning-color: #f4b400;
            --danger-color: #db4437;
            --light-color: #f8f9fa;
            --dark-color: #343a40;
        }
        
        body {
            font-family: 'Montserrat', sans-serif;
            background-color: #f5f7fa;
            color: #333;
            padding: 0;
            margin: 0;
            font-size: 14px;
        }
        
        .navbar-custom {
            background-color: var(--secondary-color);
        }
        
        .content {
            margin-left: 210px;
            padding: 10px;
                        border: none !important;

        }
        
        @media (max-width: 992px) {
            .content {
                margin-left: 0;
            }
        }
        
        .card {
            border-radius: 12px;
                        border: none !important;
            margin-bottom: 20px;
            transition: transform 0.2s ease;
        }
        
        .card:hover {
            transform: translateY(-2px);
        }
        
        .card-header {
            font-weight: 600;
                        border: none !important;

        }
        
        .invoice-card .card-header {
            background: linear-gradient(135deg, var(--primary-color), #0d47a1);
            color: white;
        }
        
        .payment-card .card-header {
            background: linear-gradient(135deg, var(--success-color), #0a7e42);
            color: white;
        }
        
        .table-container {
            border-radius: 8px;
            overflow: hidden;
            margin-bottom: 20px;
            background: white;
        }
        
        .data-table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 0;
        }
        
        .data-table th {
            background-color: #e9ecef;
            color: var(--secondary-color);
            font-weight: 600;
            padding: 12px 15px;
            text-align: left;
            border-bottom: 2px solid #dee2e6;
        }
        
        .data-table td {
            padding: 12px 15px;
            border-bottom: 1px solid #eaeaea;
            vertical-align: middle;
        }
        
        .data-table tr:last-child td {
            border-bottom: none;
        }
        
        .data-table tr:hover {
            background-color: #f8f9fa;
        }
        
        .status-badge {
            padding: 5px 12px;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: 600;
            display: inline-block;
            min-width: 80px;
            text-align: center;
        }
        
        .status-paid {
            background-color: rgba(15, 157, 88, 0.15);
            color: var(--success-color);
        }
        
        .status-pending {
            background-color: rgba(244, 180, 0, 0.15);
            color: var(--warning-color);
        }
        
        .status-overdue {
            background-color: rgba(219, 68, 55, 0.15);
            color: var(--danger-color);
        }
        
        .amount {
            font-weight: 600;
        }
        
        .amount-paid {
            color: var(--success-color);
        }
        
        .amount-pending {
            color: var(--danger-color);
        }
        
        .amount-due {
            color: var(--warning-color);
        }
        
        .no-results {
            text-align: center;
            padding: 40px;
            color: #6c757d;
            font-style: italic;
        }
        
        .stats-box {
            background-color: #f8f9fa;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 20px;
            border-left: 4px solid var(--primary-color);
            text-align: center;
        }
        
        .stats-box.invoice-stats {
            border-left-color: var(--primary-color);
        }
        
        .stats-box.payment-stats {
            border-left-color: var(--success-color);
        }
        
        .stats-box h6 {
            color: #6c757d;
            font-size: 0.9rem;
            margin-bottom: 5px;
        }
        
        .stats-box h3 {
            margin: 0;
            font-weight: 700;
        }
        
        .academic-info {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 20px;
        }
        
        .academic-info h5 {
            margin-bottom: 15px;
            font-weight: 600;
        }
        
        .info-row {
            display: flex;
            justify-content: space-between;
            margin-bottom: 8px;
        }
        
        .info-label {
            font-weight: 500;
            opacity: 0.9;
        }
        
        .info-value {
            font-weight: 600;
        }
        
        .payment-method {
            display: inline-flex;
            align-items: center;
            padding: 4px 10px;
            border-radius: 15px;
            background-color: #e9ecef;
            font-size: 0.8rem;
        }
        
        .payment-method i {
            margin-right: 5px;
        }
        
        .due-date {
            font-weight: 600;
        }
        
        .due-date.overdue {
            color: var(--danger-color);
        }
        
        .due-date.upcoming {
            color: var(--warning-color);
        }
        
        .due-date.future {
            color: var(--success-color);
        }
        
        .filter-container {
            background: white;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .filter-group {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }
        
        .filter-btn {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            padding: 8px 16px;
            border-radius: 20px;
            font-size: 0.85rem;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .filter-btn.active {
            background: var(--primary-color);
            color: white;
            border-color: var(--primary-color);
        }
        
        .filter-btn:hover {
            background: #e9ecef;
        }
        
        @media (max-width: 768px) {
            .content {
                padding: 15px;
            }
            
            .data-table {
                font-size: 0.85rem;
            }
            
            .data-table th, 
            .data-table td {
                padding: 8px 10px;
            }
            
            .stats-box {
                padding: 10px;
                margin-bottom: 15px;
            }
            
            .stats-box h3 {
                font-size: 1.5rem;
            }
            
            .info-row {
                flex-direction: column;
                margin-bottom: 10px;
            }
            
            .filter-group {
                flex-direction: column;
            }
        }
    </style>
</head>
<body>
    <?php include "../include/nav.php"; ?>

    <div class="content">
        <div class="container-fluid">
            

            <!-- Invoice Section -->
            <div class="card invoice-card">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fa fa-file-invoice-dollar me-2"></i>Association Invoices</h5>
                    <p class="mb-0 mt-1 small opacity-75">Your association fees and dues</p>
                </div>
                
                <div class="card-body">
                    <?php
                    // Query to get association invoices for the student
                    $invoiceQuery = "SELECT `id`, `student_type`, `description`, `amount`, `year`, `semester`, `due_date`, `created_at` 
                                   FROM `association_invoice` 
                                   WHERE student_type IN (SELECT student_type FROM students WHERE studentid = '$userlogin')
                                   ORDER BY due_date DESC, created_at DESC";
                    
                    $invoiceResult = mysqli_query($conn, $invoiceQuery);
                    
                    if ($invoiceResult && mysqli_num_rows($invoiceResult) > 0) {
                        $total_invoices = 0;
                        $total_amount = 0;
                        $total_paid = 0;
                        $total_pending = 0;
                        $overdue_count = 0;
                        
                        // Calculate statistics
                        $invoices = array();
                        while ($invoice = mysqli_fetch_assoc($invoiceResult)) {
                            $invoices[] = $invoice;
                            $total_invoices++;
                            $total_amount += $invoice['amount'];
                            
                            // Check if invoice is paid
                            $paymentQuery = "SELECT SUM(amount) as paid_amount FROM `association_payment` 
                                           WHERE studentid = '$userlogin' AND invoice_id = '" . $invoice['id'] . "'";
                            $paymentResult = mysqli_query($conn, $paymentQuery);
                            $paymentData = mysqli_fetch_assoc($paymentResult);
                            $paid_amount = $paymentData['paid_amount'] ?? 0;
                            
                            if ($paid_amount >= $invoice['amount']) {
                                $total_paid++;
                            } else {
                                $total_pending++;
                                
                                // Check if invoice is overdue
                                $due_date = strtotime($invoice['due_date']);
                                $current_date = time();
                                
                                if ($current_date > $due_date) {
                                    $overdue_count++;
                                }
                            }
                        }
                        
                      
                        
                        // Display invoices
                        echo '<div class="table-container">';
                        echo '<table class="data-table">';
                        
                        echo '<tr>';
                        echo '<th>Amount</th>';
                        echo '<th>Year/Semester</th>';
                        echo '<th>Status</th>';
                        echo '</tr>';
                        
                        foreach ($invoices as $invoice) {
                            // Check payment status
                            $paymentQuery = "SELECT SUM(amount) as paid_amount FROM `association_payment` 
                                           WHERE studentid = '$userlogin' AND invoice_id = '" . $invoice['id'] . "'";
                            $paymentResult = mysqli_query($conn, $paymentQuery);
                            $paymentData = mysqli_fetch_assoc($paymentResult);
                            $paid_amount = $paymentData['paid_amount'] ?? 0;
                            
                            // Determine status
                            $due_date = strtotime($invoice['due_date']);
                            $current_date = time();
                            
                            if ($paid_amount >= $invoice['amount']) {
                                $status_class = 'status-paid';
                                $status_text = 'Paid';
                                $amount_class = 'amount-paid';
                            } else {
                                if ($current_date > $due_date) {
                                    $status_class = 'status-overdue';
                                    $status_text = 'Overdue';
                                    $amount_class = 'amount-pending';
                                } else {
                                    $status_class = 'status-pending';
                                    $status_text = 'Pending';
                                    $amount_class = 'amount-due';
                                }
                            }
                            
                            // Determine due date class
                            $days_diff = floor(($due_date - $current_date) / (60 * 60 * 24));
                            $due_date_class = 'future';
                            
                            if ($current_date > $due_date) {
                                $due_date_class = 'overdue';
                            } elseif ($days_diff <= 7) {
                                $due_date_class = 'upcoming';
                            }
                            
                            echo '<tr>';
                            echo '<td class="amount ' . $amount_class . '">K ' . number_format($invoice['amount'], 2) . '<br><small class="text-muted">Paid: K ' . number_format($paid_amount, 2) . '</small></td>';
                            echo '<td>Year ' . $invoice['year'] . ' - Sem ' . $invoice['semester'] . '</td>';
                           
                            echo '<td><span class="status-badge ' . $status_class . '">' . $status_text . '</span></td>';
                            echo '</tr>';
                        }
                        
                        echo '</table>';
                        echo '</div>';
                    } else {
                        echo '<div class="no-results">';
                        echo '<i class="fa fa-file-invoice-dollar fa-3x mb-3"></i>';
                        echo '<h5>No invoices found</h5>';
                        echo '<p>No association invoices are available for your account.</p>';
                        echo '</div>';
                    }
                    ?>
                </div>
                <br><br>
            </div>



    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Add hover effects to table rows
            const rows = document.querySelectorAll('.data-table tr');
            rows.forEach(row => {
                row.addEventListener('mouseenter', function() {
                    this.style.backgroundColor = '#f1f4f7';
                    this.style.transition = 'background-color 0.2s ease';
                });
                
                row.addEventListener('mouseleave', function() {
                    this.style.backgroundColor = '';
                });
            });
            
            // Filter functionality
            const filterButtons = document.querySelectorAll('.filter-btn');
            filterButtons.forEach(button => {
                button.addEventListener('click', function() {
                    filterButtons.forEach(btn => btn.classList.remove('active'));
                    this.classList.add('active');
                    
                    // Filter logic can be added here
                    const filterValue = this.getAttribute('data-filter');
                    console.log('Filtering by:', filterValue);
                });
            });
            
            // Tooltips for payment methods
            const paymentMethods = document.querySelectorAll('.payment-method');
            paymentMethods.forEach(method => {
                method.addEventListener('mouseenter', function() {
                    const methodName = this.textContent.trim();
                    // You could show a tooltip here
                });
            });
        });
        
        // Function to format currency
        function formatCurrency(amount) {
            return 'K ' + parseFloat(amount).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
        }
    </script>
</body>
</html>
<?php
} else {
    header("location:../index.php");
}
?>