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

try {
    $activities = [];
    
    // Get recent orders
    $ordersResult = $conn->query("
        SELECT 'order' as type, id, full_name, total, status, created_at 
        FROM orders 
        ORDER BY created_at DESC 
        LIMIT 5
    ");
    
    if ($ordersResult) {
        while ($row = $ordersResult->fetch_assoc()) {
            $row['icon'] = 'fa-shopping-bag';
            $row['description'] = 'New order from ' . $row['full_name'];
            $row['time'] = $row['created_at'];
            $activities[] = $row;
        }
    }
    
    // Get recent bookings
    $bookingsResult = $conn->query("
        SELECT 'booking' as type, id, name, status, booking_date, created_at 
        FROM bookings 
        ORDER BY created_at DESC 
        LIMIT 5
    ");
    
    if ($bookingsResult) {
        while ($row = $bookingsResult->fetch_assoc()) {
            $row['icon'] = 'fa-calendar';
            $row['description'] = 'New booking from ' . $row['name'];
            $row['time'] = $row['created_at'];
            $activities[] = $row;
        }
    }
    
    // Get recent contacts
    $contactsResult = $conn->query("
        SELECT 'contact' as type, id, name, message, status, created_at 
        FROM contacts 
        ORDER BY created_at DESC 
        LIMIT 5
    ");
    
    if ($contactsResult) {
        while ($row = $contactsResult->fetch_assoc()) {
            $row['icon'] = 'fa-envelope';
            $row['description'] = 'New contact from ' . $row['name'];
            $row['time'] = $row['created_at'];
            $activities[] = $row;
        }
    }
    
    // Get recent feedback
    $feedbackResult = $conn->query("
        SELECT 'feedback' as type, id, name, subject, rating, created_at 
        FROM feedback 
        ORDER BY created_at DESC 
        LIMIT 5
    ");
    
    if ($feedbackResult) {
        while ($row = $feedbackResult->fetch_assoc()) {
            $row['icon'] = 'fa-star';
            $row['description'] = 'New feedback from ' . $row['name'] . ' (' . $row['rating'] . ' stars)';
            $row['time'] = $row['created_at'];
            $activities[] = $row;
        }
    }
    
    // Sort all activities by time (most recent first)
    usort($activities, function($a, $b) {
        return strtotime($b['time']) - strtotime($a['time']);
    });
    
    // Take only the latest 10 activities
    $activities = array_slice($activities, 0, 10);
    
    echo json_encode([
        'success' => true,
        'data' => $activities
    ]);

} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Error fetching recent activities: ' . $e->getMessage(),
        'data' => []
    ]);
}

$conn->close();
?>
