<?php
require_once '../config/database.php';
require_once '../config/auth_enhanced.php';

if (!isLoggedIn()) {
    http_response_code(401);
    echo json_encode(['error' => 'Unauthorized access']);
    exit;
}

header('Content-Type: application/json');

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // Fetch membership fees with member details
    $stmt = $pdo->prepare("
        SELECT 
            mf.id,
            m.name as member_name,
            m.email,
            m.membership_type,
            mf.amount,
            mf.fee_type,
            mf.due_date,
            mf.paid_date,
            mf.status,
            mf.payment_method,
            mf.notes,
            mf.created_at,
            CASE 
                WHEN mf.status = 'paid' THEN 'Paid'
                WHEN mf.due_date < CURDATE() THEN 'Overdue'
                WHEN mf.due_date <= DATE_ADD(CURDATE(), INTERVAL 7 DAY) THEN 'Due Soon'
                ELSE 'Pending'
            END as payment_status
        FROM membership_fees mf
        LEFT JOIN members m ON mf.member_id = m.id
        ORDER BY mf.due_date DESC, m.name ASC
    ");
    $stmt->execute();
    $fees = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Format data for DataTables
    $data = [];
    foreach ($fees as $fee) {
        $statusClass = '';
        switch ($fee['payment_status']) {
            case 'Paid':
                $statusClass = 'success';
                break;
            case 'Overdue':
                $statusClass = 'danger';
                break;
            case 'Due Soon':
                $statusClass = 'warning';
                break;
            default:
                $statusClass = 'info';
        }
        
        $data[] = [
            'id' => $fee['id'],
            'member_name' => $fee['member_name'],
            'email' => $fee['email'],
            'membership_type' => ucfirst($fee['membership_type']),
            'amount' => '$' . number_format($fee['amount'], 2),
            'fee_type' => ucfirst(str_replace('_', ' ', $fee['fee_type'])),
            'due_date' => date('M d, Y', strtotime($fee['due_date'])),
            'paid_date' => $fee['paid_date'] ? date('M d, Y', strtotime($fee['paid_date'])) : '-',
            'status' => '<span class="badge badge-' . $statusClass . '">' . $fee['payment_status'] . '</span>',
            'payment_method' => $fee['payment_method'] ? ucfirst($fee['payment_method']) : '-',
            'notes' => $fee['notes'] ?: '-',
            'actions' => '<button class="btn btn-sm btn-info view-fee" data-id="' . $fee['id'] . '">View</button>'
        ];
    }
    
    echo json_encode(['data' => $data]);
    
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Database error: ' . $e->getMessage()]);
}
?>
