<?php
/**
 * Dashboard Stats Controller
 * Real-time statistics from database
 */

class DashboardStatsController {
    private $db;

    public function __construct($db) {
        $this->db = $db;
    }

    public function getStats($property_id = null) {
        try {
            $stats = [];

            // Active bookings (current + upcoming)
            $query = "SELECT COUNT(*) as count FROM bookings WHERE status IN ('confirmed', 'checked_in') AND check_out >= CURDATE()";
            if ($property_id) $query .= " AND property_id = " . (int)$property_id;
            $stats['active_bookings'] = $this->db->query($query)->fetch()['count'];

            // Pending guest requests
            $query = "SELECT COUNT(*) as count FROM tickets WHERE status IN ('open', 'pending')";
            $stats['guest_requests'] = $this->db->query($query)->fetch()['count'];

            // This month revenue
            $query = "SELECT COALESCE(SUM(total), 0) as revenue FROM folio_charges WHERE status = 'paid' AND MONTH(paid_date) = MONTH(CURDATE()) AND YEAR(paid_date) = YEAR(CURDATE())";
            if ($property_id) $query .= " AND property_id = " . (int)$property_id;
            $stats['month_revenue'] = $this->db->query($query)->fetch()['revenue'];

            // Occupancy rate (rooms occupied / total rooms)
            $total_rooms = $this->db->query("SELECT COUNT(*) as count FROM rooms" . ($property_id ? " WHERE property_id = " . (int)$property_id : ""))->fetch()['count'];
            $occupied = $this->db->query("SELECT COUNT(DISTINCT room_id) as count FROM bookings WHERE status = 'checked_in' AND CURDATE() BETWEEN check_in AND check_out" . ($property_id ? " AND property_id = " . (int)$property_id : ""))->fetch()['count'];
            $stats['occupancy_rate'] = $total_rooms > 0 ? round(($occupied / $total_rooms) * 100) : 0;

            // Pending invoices
            $query = "SELECT COUNT(*) as count, COALESCE(SUM(total), 0) as amount FROM folio_charges WHERE status = 'pending'";
            $pending = $this->db->query($query)->fetch();
            $stats['pending_invoices'] = $pending['count'];
            $stats['pending_amount'] = $pending['amount'];

            // Today's check-ins
            $query = "SELECT COUNT(*) as count FROM bookings WHERE DATE(check_in) = CURDATE() AND status = 'confirmed'";
            $stats['todays_checkins'] = $this->db->query($query)->fetch()['count'];

            // Today's check-outs
            $query = "SELECT COUNT(*) as count FROM bookings WHERE DATE(check_out) = CURDATE() AND status = 'checked_in'";
            $stats['todays_checkouts'] = $this->db->query($query)->fetch()['count'];

            // Recent bookings
            $query = "SELECT b.booking_reference, b.check_in, b.price, b.source, g.name as guest_name 
                      FROM bookings b JOIN guests g ON b.guest_id = g.id 
                      ORDER BY b.created_at DESC LIMIT 5";
            $stats['recent_bookings'] = $this->db->query($query)->fetchAll(PDO::FETCH_ASSOC);

            return ['success' => true, 'stats' => $stats];

        } catch (Exception $e) {
            error_log('Dashboard stats error: ' . $e->getMessage());
            return ['success' => false, 'message' => 'Error fetching stats'];
        }
    }
}
