<?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 {
    $database = new Database();
    $pdo = $database->getConnection();
    
    // Get fee structure from settings or default values
    $stmt = $pdo->prepare("
        SELECT setting_key, setting_value, description 
        FROM settings 
        WHERE setting_key LIKE 'membership_fee_%'
        ORDER BY setting_key
    ");
    $stmt->execute();
    $fee_settings = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Default fee structure if no settings exist
    $default_structure = [
        'membership_fee_individual_annual' => [
            'value' => '50.00',
            'description' => 'Annual membership fee for individual members'
        ],
        'membership_fee_family_annual' => [
            'value' => '80.00',
            'description' => 'Annual membership fee for family members'
        ],
        'membership_fee_individual_monthly' => [
            'value' => '5.00',
            'description' => 'Monthly membership fee for individual members'
        ],
        'membership_fee_family_monthly' => [
            'value' => '8.00',
            'description' => 'Monthly membership fee for family members'
        ],
        'membership_fee_late_penalty' => [
            'value' => '10.00',
            'description' => 'Late payment penalty fee'
        ],
        'membership_fee_registration' => [
            'value' => '25.00',
            'description' => 'One-time registration fee for new members'
        ]
    ];
    
    // Organize fee settings
    $fee_structure = [];
    
    if (empty($fee_settings)) {
        // Use default structure
        foreach ($default_structure as $key => $data) {
            $fee_structure[] = [
                'setting_key' => $key,
                'setting_value' => $data['value'],
                'description' => $data['description'],
                'formatted_value' => '$' . number_format($data['value'], 2),
                'is_default' => true
            ];
        }
    } else {
        // Use database settings
        foreach ($fee_settings as $setting) {
            $fee_structure[] = [
                'setting_key' => $setting['setting_key'],
                'setting_value' => $setting['setting_value'],
                'description' => $setting['description'],
                'formatted_value' => '$' . number_format($setting['setting_value'], 2),
                'is_default' => false
            ];
        }
        
        // Add any missing default settings
        $existing_keys = array_column($fee_settings, 'setting_key');
        foreach ($default_structure as $key => $data) {
            if (!in_array($key, $existing_keys)) {
                $fee_structure[] = [
                    'setting_key' => $key,
                    'setting_value' => $data['value'],
                    'description' => $data['description'],
                    'formatted_value' => '$' . number_format($data['value'], 2),
                    'is_default' => true
                ];
            }
        }
    }
    
    // Group fees by category
    $grouped_structure = [
        'annual_fees' => [],
        'monthly_fees' => [],
        'special_fees' => []
    ];
    
    foreach ($fee_structure as $fee) {
        if (strpos($fee['setting_key'], '_annual') !== false) {
            $grouped_structure['annual_fees'][] = $fee;
        } elseif (strpos($fee['setting_key'], '_monthly') !== false) {
            $grouped_structure['monthly_fees'][] = $fee;
        } else {
            $grouped_structure['special_fees'][] = $fee;
        }
    }
    
    // Calculate fee comparison
    $individual_annual = 50.00;
    $family_annual = 80.00;
    $individual_monthly = 5.00;
    $family_monthly = 8.00;
    
    // Get actual values from structure
    foreach ($fee_structure as $fee) {
        switch ($fee['setting_key']) {
            case 'membership_fee_individual_annual':
                $individual_annual = (float)$fee['setting_value'];
                break;
            case 'membership_fee_family_annual':
                $family_annual = (float)$fee['setting_value'];
                break;
            case 'membership_fee_individual_monthly':
                $individual_monthly = (float)$fee['setting_value'];
                break;
            case 'membership_fee_family_monthly':
                $family_monthly = (float)$fee['setting_value'];
                break;
        }
    }
    
    $fee_comparison = [
        'individual' => [
            'annual' => $individual_annual,
            'monthly_equivalent' => $individual_monthly * 12,
            'savings_with_annual' => ($individual_monthly * 12) - $individual_annual,
            'formatted' => [
                'annual' => '$' . number_format($individual_annual, 2),
                'monthly_equivalent' => '$' . number_format($individual_monthly * 12, 2),
                'monthly_fee' => '$' . number_format($individual_monthly, 2),
                'savings_with_annual' => '$' . number_format(($individual_monthly * 12) - $individual_annual, 2)
            ]
        ],
        'family' => [
            'annual' => $family_annual,
            'monthly_equivalent' => $family_monthly * 12,
            'savings_with_annual' => ($family_monthly * 12) - $family_annual,
            'formatted' => [
                'annual' => '$' . number_format($family_annual, 2),
                'monthly_equivalent' => '$' . number_format($family_monthly * 12, 2),
                'monthly_fee' => '$' . number_format($family_monthly, 2),
                'savings_with_annual' => '$' . number_format(($family_monthly * 12) - $family_annual, 2)
            ]
        ]
    ];
    
    // Format for frontend table display
    $table_data = [];
    
    // Convert fee structure to table format
    foreach ($fee_structure as $fee) {
        $key = $fee['setting_key'];
        $membership_type = 'Unknown';
        $duration = 'Unknown';
        
        if (strpos($key, 'individual_annual') !== false) {
            $membership_type = 'Individual';
            $duration = 'Annual';
        } elseif (strpos($key, 'family_annual') !== false) {
            $membership_type = 'Family';
            $duration = 'Annual';
        } elseif (strpos($key, 'individual_monthly') !== false) {
            $membership_type = 'Individual';
            $duration = 'Monthly';
        } elseif (strpos($key, 'family_monthly') !== false) {
            $membership_type = 'Family';
            $duration = 'Monthly';
        } elseif (strpos($key, 'registration') !== false) {
            $membership_type = 'All';
            $duration = 'One-time';
        } elseif (strpos($key, 'late_penalty') !== false) {
            $membership_type = 'All';
            $duration = 'Penalty';
        }
        
        $table_data[] = [
            'membership_type' => $membership_type,
            'duration' => $duration,
            'amount' => $fee['setting_value'],
            'status' => $fee['is_default'] ? 'default' : 'active'
        ];
    }

    echo json_encode([
        'success' => true,
        'data' => $table_data,
        'fee_structure' => $fee_structure,
        'grouped_structure' => $grouped_structure,
        'fee_comparison' => $fee_comparison,
        'last_updated' => date('Y-m-d H:i:s')
    ]);
    
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Database error: ' . $e->getMessage()]);
}
?>
