<?php
header('Content-Type: application/json');
header('Cache-Control: no-cache, must-revalidate');

session_start();
include_once('../includes/config.php');

// Check if user is logged in
if (!isset($_SESSION['uid'])) {
    http_response_code(401);
    echo json_encode(['error' => 'Unauthorized']);
    exit();
}

try {
    // Get real-time statistics
    $stats = [];
    
    // Today's statistics
    $todayStats = "SELECT 
        COUNT(CASE WHEN CheckInDate = CURDATE() THEN 1 END) as TodayCheckIns,
        COUNT(CASE WHEN CheckOutDate = CURDATE() THEN 1 END) as TodayCheckOuts,
        COUNT(CASE WHEN BookingDate >= CURDATE() THEN 1 END) as TodayBookings,
        SUM(CASE WHEN CheckInDate = CURDATE() THEN TotalAmount ELSE 0 END) as TodayRevenue
        FROM tblbookings WHERE IsActive = 1";
    
    $todayResult = mysqli_query($con, $todayStats);
    if ($todayResult) {
        $stats['today'] = mysqli_fetch_assoc($todayResult);
    }
    
    // Room occupancy statistics
    $roomStats = "SELECT 
        COUNT(*) as TotalRooms,
        COUNT(CASE WHEN Status = 'Available' THEN 1 END) as AvailableRooms,
        COUNT(CASE WHEN Status = 'Occupied' THEN 1 END) as OccupiedRooms,
        COUNT(CASE WHEN Status = 'Maintenance' THEN 1 END) as MaintenanceRooms
        FROM tblrooms WHERE IsActive = 1";
    
    $roomResult = mysqli_query($con, $roomStats);
    if ($roomResult) {
        $stats['rooms'] = mysqli_fetch_assoc($roomResult);
        // Calculate occupancy rate
        $total = $stats['rooms']['TotalRooms'];
        $occupied = $stats['rooms']['OccupiedRooms'];
        $stats['rooms']['OccupancyRate'] = $total > 0 ? round(($occupied / $total) * 100, 1) : 0;
    }
    
    // Recent payments (last 24 hours)
    $recentPayments = "SELECT 
        COUNT(*) as PaymentCount,
        SUM(Amount) as TotalAmount
        FROM tblbookingpayments 
        WHERE IsActive = 1 AND PaymentDate >= DATE_SUB(NOW(), INTERVAL 24 HOUR)";
    
    $paymentsResult = mysqli_query($con, $recentPayments);
    if ($paymentsResult) {
        $stats['payments'] = mysqli_fetch_assoc($paymentsResult);
    }
    
    // Pending check-ins for today
    $pendingCheckIns = "SELECT 
        b.ID, b.BookingNumber, b.CustomerName, b.CustomerPhone,
        br.BranchName, r.RoomName, b.CheckInDate
        FROM tblbookings b
        LEFT JOIN tblbranches br ON b.BranchID = br.ID
        LEFT JOIN tblrooms r ON b.RoomID = r.ID
        WHERE b.IsActive = 1 
        AND b.BookingStatus = 'Confirmed' 
        AND b.CheckInDate = CURDATE()
        ORDER BY b.CheckInDate ASC
        LIMIT 5";
    
    $checkInsResult = mysqli_query($con, $pendingCheckIns);
    $stats['pendingCheckIns'] = [];
    if ($checkInsResult) {
        while ($row = mysqli_fetch_assoc($checkInsResult)) {
            $stats['pendingCheckIns'][] = $row;
        }
    }
    
    // Pending check-outs for today
    $pendingCheckOuts = "SELECT 
        b.ID, b.BookingNumber, b.CustomerName, b.CustomerPhone,
        br.BranchName, r.RoomName, b.CheckOutDate
        FROM tblbookings b
        LEFT JOIN tblbranches br ON b.BranchID = br.ID
        LEFT JOIN tblrooms r ON b.RoomID = r.ID
        WHERE b.IsActive = 1 
        AND b.BookingStatus = 'CheckedIn' 
        AND b.CheckOutDate = CURDATE()
        ORDER BY b.CheckOutDate ASC
        LIMIT 5";
    
    $checkOutsResult = mysqli_query($con, $pendingCheckOuts);
    $stats['pendingCheckOuts'] = [];
    if ($checkOutsResult) {
        while ($row = mysqli_fetch_assoc($checkOutsResult)) {
            $stats['pendingCheckOuts'][] = $row;
        }
    }
    
    // Low availability rooms (less than 20% available)
    $lowAvailability = "SELECT 
        br.BranchName,
        COUNT(*) as TotalRooms,
        COUNT(CASE WHEN r.Status = 'Available' THEN 1 END) as AvailableRooms,
        ROUND((COUNT(CASE WHEN r.Status = 'Available' THEN 1 END) / COUNT(*)) * 100, 1) as AvailabilityPercentage
        FROM tblrooms r
        LEFT JOIN tblbranches br ON r.BranchID = br.ID
        WHERE r.IsActive = 1 AND br.IsActive = 1
        GROUP BY r.BranchID, br.BranchName
        HAVING AvailabilityPercentage < 20
        ORDER BY AvailabilityPercentage ASC";
    
    $lowAvailResult = mysqli_query($con, $lowAvailability);
    $stats['lowAvailability'] = [];
    if ($lowAvailResult) {
        while ($row = mysqli_fetch_assoc($lowAvailResult)) {
            $stats['lowAvailability'][] = $row;
        }
    }
    
    // System notifications
    $stats['notifications'] = [];
    
    // Check for overdue payments
    $overduePayments = "SELECT COUNT(*) as Count 
        FROM tblbookings 
        WHERE IsActive = 1 
        AND PaymentStatus IN ('Pending', 'Partial') 
        AND CheckOutDate < CURDATE()";
    
    $overdueResult = mysqli_query($con, $overduePayments);
    if ($overdueResult) {
        $overdue = mysqli_fetch_assoc($overdueResult);
        if ($overdue['Count'] > 0) {
            $stats['notifications'][] = [
                'type' => 'warning',
                'message' => $overdue['Count'] . ' booking(s) have overdue payments',
                'action' => 'financial-report.php'
            ];
        }
    }
    
    // Check for rooms in maintenance
    $maintenanceRooms = "SELECT COUNT(*) as Count 
        FROM tblrooms 
        WHERE IsActive = 1 AND Status = 'Maintenance'";
    
    $maintenanceResult = mysqli_query($con, $maintenanceRooms);
    if ($maintenanceResult) {
        $maintenance = mysqli_fetch_assoc($maintenanceResult);
        if ($maintenance['Count'] > 0) {
            $stats['notifications'][] = [
                'type' => 'info',
                'message' => $maintenance['Count'] . ' room(s) are under maintenance',
                'action' => 'rooms-management.php'
            ];
        }
    }
    
    // Revenue trend (last 7 days)
    $revenueTrend = "SELECT 
        DATE(bp.PaymentDate) as PaymentDay,
        SUM(bp.Amount) as DayRevenue
        FROM tblbookingpayments bp
        WHERE bp.IsActive = 1 
        AND bp.PaymentDate >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)
        GROUP BY DATE(bp.PaymentDate)
        ORDER BY PaymentDay ASC";
    
    $trendResult = mysqli_query($con, $revenueTrend);
    $stats['revenueTrend'] = [];
    if ($trendResult) {
        while ($row = mysqli_fetch_assoc($trendResult)) {
            $stats['revenueTrend'][] = [
                'date' => $row['PaymentDay'],
                'revenue' => floatval($row['DayRevenue'])
            ];
        }
    }
    
    // Add timestamp for cache management
    $stats['timestamp'] = date('Y-m-d H:i:s');
    $stats['success'] = true;
    
    echo json_encode($stats);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => 'Database error occurred',
        'timestamp' => date('Y-m-d H:i:s')
    ]);
    error_log("Dashboard API Error: " . $e->getMessage());
}
?>