<?php
require_once '../config/database.php';
header('Content-Type: application/json');

try {
    $database = new Database();
    $pdo = $database->getConnection();

    // Get filter parameter
    $filter = $_GET['filter'] ?? 'upcoming';

    // Check if events table exists and has data
    $stmt = $pdo->query("SHOW TABLES LIKE 'events'");
    if ($stmt->rowCount() == 0) {
        // If no table exists, return empty data
        echo json_encode([
            'success' => true,
            'data' => [],
            'count' => 0,
            'note' => 'Events table not found'
        ]);
        exit;
    }

    // Try to fetch from existing table structure
    try {
        // Build filter clause
        $whereClause = '';
        switch ($filter) {
            case 'upcoming':
                $whereClause = "WHERE event_date > CURDATE()";
                break;
            case 'current':
                $whereClause = "WHERE event_date = CURDATE()";
                break;
            case 'past':
                $whereClause = "WHERE event_date < CURDATE()";
                break;
            default:
                $whereClause = "";
                break;
        }

        // Query using actual database column names
        $query = "SELECT 
            id,
            event_title,
            event_description,
            event_banner_url,
            event_date,
            event_time,
            event_location,
            event_type,
            max_participants,
            registration_fee,
            status,
            created_by,
            created_at,
            updated_at
        FROM events 
        $whereClause 
        ORDER BY event_date DESC, event_time DESC 
        LIMIT 50";
        
        $stmt = $pdo->query($query);
        $events = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
    } catch (Exception $e) {
        // Fallback query if table structure is different
        try {
            $stmt = $pdo->query("SELECT id, event_title, event_date, event_location, status FROM events ORDER BY event_date DESC LIMIT 50");
            $events = $stmt->fetchAll(PDO::FETCH_ASSOC);
        } catch (Exception $e2) {
            // If even basic query fails, return empty with error info
            echo json_encode([
                'success' => true,
                'data' => [],
                'count' => 0,
                'error' => 'Query failed: ' . $e2->getMessage(),
                'original_error' => $e->getMessage()
            ]);
            exit;
        }
    }

    // Format data consistently using actual database columns
    $formattedEvents = [];
    foreach ($events as $event) {
        $formattedEvents[] = [
            'id' => $event['id'] ?? '',
            'title' => $event['event_title'] ?? 'Unknown Event',
            'description' => $event['event_description'] ?? '',
            'banner_url' => $event['event_banner_url'] ?? '',
            'event_date' => $event['event_date'] ?? '',
            'event_time' => $event['event_time'] ?? '',
            'location' => $event['event_location'] ?? '',
            'event_type' => $event['event_type'] ?? '',
            'max_participants' => $event['max_participants'] ?? 0,
            'registration_fee' => $event['registration_fee'] ?? 0.00,
            'status' => $event['status'] ?? 'upcoming',
            'created_by' => $event['created_by'] ?? '',
            'created_at' => $event['created_at'] ?? date('Y-m-d H:i:s'),
            'updated_at' => $event['updated_at'] ?? date('Y-m-d H:i:s')
        ];
    }

    echo json_encode([
        'success' => true,
        'data' => $formattedEvents,
        'count' => count($formattedEvents),
        'filter' => $filter
    ]);

} catch (Exception $e) {
    // Return empty data if database connection fails
    echo json_encode([
        'success' => true,
        'data' => [],
        'count' => 0,
        'error' => 'Database connection failed: ' . $e->getMessage(),
        'note' => 'Please upload this file to your hosting server'
    ]);
}
?>
