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

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

// Check authentication
if (!isAuthenticated()) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit;
}

// Check if membership type is provided
if (!isset($_GET['type']) || empty($_GET['type'])) {
    echo json_encode(['success' => false, 'message' => 'Membership type is required']);
    exit;
}

$membershipType = $_GET['type'];

try {
    $database = new Database();
    $conn = $database->getConnection();
    
    // Get current session year
    $currentYear = date('Y');
    
    // Query to get membership fee for the specified type and current session
    $query = "SELECT * FROM membership_fee_settings 
              WHERE membership_type = ? 
              AND session_year = ? 
              AND is_active = 1
              ORDER BY id DESC
              LIMIT 1";
    
    $stmt = $conn->prepare($query);
    $stmt->execute([$membershipType, $currentYear]);
    
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    
    // If no fee found for current year, check previous years
    if (!$result) {
        $query = "SELECT * FROM membership_fee_settings 
                  WHERE membership_type = ? 
                  AND is_active = 1
                  ORDER BY session_year DESC
                  LIMIT 1";
        
        $stmt = $conn->prepare($query);
        $stmt->execute([$membershipType]);
        
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
    }
    
    // If still no fee found, set default values
    if (!$result) {
        $result = [
            'membership_type' => $membershipType,
            'session_year' => $currentYear,
            'fee_amount' => $membershipType === 'Individual' ? 1000.00 : 1500.00,
            'late_fee_amount' => $membershipType === 'Individual' ? 200.00 : 300.00,
            'description' => 'Default fee'
        ];
    }
    
    echo json_encode([
        'success' => true,
        'data' => $result,
        'message' => 'Membership fee fetched successfully'
    ]);
    
} catch (PDOException $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}
