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

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

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

// Get the requested table
$table = isset($_GET['table']) ? $_GET['table'] : '';
$recent = isset($_GET['recent']) ? filter_var($_GET['recent'], FILTER_VALIDATE_BOOLEAN) : false;
$filter = isset($_GET['filter']) ? $_GET['filter'] : '';
$type = isset($_GET['type']) ? $_GET['type'] : '';

try {
    $database = new Database();
    $conn = $database->getConnection();
    
    $data = [];
    
    switch ($table) {
        case 'members':
            // Fetch members data
            $query = "SELECT id, kso_id, first_name, last_name, email, status, created_at 
                      FROM members";
            
            if ($recent) {
                $query .= " ORDER BY created_at DESC LIMIT 10";
            }
            
            $stmt = $conn->prepare($query);
            $stmt->execute();
            $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
            break;
            
        case 'events':
            // Fetch events data
            $query = "SELECT id, event_title, event_description, event_date, event_time, 
                       event_location, event_type, status, created_at 
                      FROM events";
            
            if ($filter === 'upcoming') {
                $query .= " WHERE status = 'upcoming'";
            }
            
            if ($recent) {
                $query .= " ORDER BY event_date ASC LIMIT 10";
            } else {
                $query .= " ORDER BY event_date ASC";
            }
            
            $stmt = $conn->prepare($query);
            $stmt->execute();
            $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
            break;
            
        case 'transactions':
            // This is a combined view of finance (income) and expenses
            if ($type === 'expense' || $type === '') {
                // Fetch expenses
                $expenseQuery = "SELECT id, expense_title as title, amount, expense_date as payment_date, 
                                'expense' as transaction_type, 'expenses' as from_table
                                FROM expenses";
                
                if ($recent) {
                    $expenseQuery .= " ORDER BY expense_date DESC LIMIT 5";
                }
                
                $stmt = $conn->prepare($expenseQuery);
                $stmt->execute();
                $expenseData = $stmt->fetchAll(PDO::FETCH_ASSOC);
                
                if ($type === 'expense') {
                    $data = $expenseData;
                } else {
                    $data = array_merge($data, $expenseData);
                }
            }
            
            if ($type === 'income' || $type === '') {
                // Fetch income
                $incomeQuery = "SELECT id, transaction_type, amount, payment_date,
                               'finance' as from_table  
                               FROM finance";
                
                if ($recent) {
                    $incomeQuery .= " ORDER BY payment_date DESC LIMIT 5";
                }
                
                $stmt = $conn->prepare($incomeQuery);
                $stmt->execute();
                $incomeData = $stmt->fetchAll(PDO::FETCH_ASSOC);
                
                if ($type === 'income') {
                    $data = $incomeData;
                } else {
                    $data = array_merge($data, $incomeData);
                }
            }
            
            // Sort combined data by date
            usort($data, function($a, $b) {
                return strtotime($b['payment_date']) - strtotime($a['payment_date']);
            });
            
            // Limit to 10 records if combined
            if ($type === '' && count($data) > 10) {
                $data = array_slice($data, 0, 10);
            }
            
            break;
            
        default:
            echo json_encode(['success' => false, 'message' => 'Invalid table requested']);
            exit;
    }
    
    echo json_encode(['success' => true, 'data' => $data]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false, 
        'message' => 'Error: ' . $e->getMessage()
    ]);
}
?>
