<?php
class DashboardController {

    public function index() {
        $db = Database::getInstance();
        $cid = Auth::user()['company_id'];

        // KPI metrics
        $totalProperties = $db->fetchColumn("SELECT COUNT(*) FROM properties WHERE company_id = ? AND deleted_at IS NULL", [$cid]);
        $totalUnits = $db->fetchColumn("SELECT COUNT(*) FROM units WHERE company_id = ? AND deleted_at IS NULL", [$cid]);
        $occupiedUnits = $db->fetchColumn("SELECT COUNT(*) FROM units WHERE company_id = ? AND deleted_at IS NULL AND status = 'occupied'", [$cid]);
        $vacantUnits = $db->fetchColumn("SELECT COUNT(*) FROM units WHERE company_id = ? AND deleted_at IS NULL AND status = 'vacant'", [$cid]);
        $occupancyRate = $totalUnits > 0 ? round(($occupiedUnits / $totalUnits) * 100, 1) : 0;

        $totalTenants = $db->fetchColumn("SELECT COUNT(*) FROM tenants WHERE company_id = ? AND deleted_at IS NULL AND status = 'active'", [$cid]);

        // Financial
        $monthStart = date('Y-m-01');
        $monthEnd = date('Y-m-t');
        
        $expectedRent = $db->fetchColumn(
            "SELECT COALESCE(SUM(c.amount), 0) FROM charges c 
             JOIN leases l ON c.lease_id = l.id 
             WHERE c.company_id = ? AND c.type = 'rent' AND c.due_date BETWEEN ? AND ? AND c.deleted_at IS NULL",
            [$cid, $monthStart, $monthEnd]
        );

        $collectedRent = $db->fetchColumn(
            "SELECT COALESCE(SUM(amount), 0) FROM payments 
             WHERE company_id = ? AND status = 'completed' AND payment_date BETWEEN ? AND ? AND deleted_at IS NULL",
            [$cid, $monthStart, $monthEnd]
        );

        $outstandingRent = max(0, $expectedRent - $collectedRent);

        // Maintenance
        $openMaintenance = $db->fetchColumn(
            "SELECT COUNT(*) FROM maintenance_requests WHERE company_id = ? AND status IN ('new','reviewed','assigned','in_progress') AND deleted_at IS NULL",
            [$cid]
        );

        // Upcoming lease expirations (next 60 days)
        $expiringLeases = $db->fetchAll(
            "SELECT l.*, t.first_name, t.last_name, u.unit_number, p.name as property_name
             FROM leases l
             LEFT JOIN tenants t ON l.tenant_id = t.id
             LEFT JOIN units u ON l.unit_id = u.id
             LEFT JOIN properties p ON l.property_id = p.id
             WHERE l.company_id = ? AND l.status = 'active' AND l.end_date BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 60 DAY) AND l.deleted_at IS NULL
             ORDER BY l.end_date ASC LIMIT 10",
            [$cid]
        );

        // Recent payments
        $recentPayments = $db->fetchAll(
            "SELECT p.*, t.first_name, t.last_name 
             FROM payments p 
             LEFT JOIN tenants t ON p.tenant_id = t.id
             WHERE p.company_id = ? AND p.deleted_at IS NULL
             ORDER BY p.created_at DESC LIMIT 8",
            [$cid]
        );

        // Recent maintenance
        $recentMaintenance = $db->fetchAll(
            "SELECT mr.*, t.first_name, t.last_name, u.unit_number, p.name as property_name
             FROM maintenance_requests mr
             LEFT JOIN tenants t ON mr.tenant_id = t.id
             LEFT JOIN units u ON mr.unit_id = u.id
             LEFT JOIN properties p ON mr.property_id = p.id
             WHERE mr.company_id = ? AND mr.deleted_at IS NULL
             ORDER BY mr.created_at DESC LIMIT 8",
            [$cid]
        );

        // Monthly revenue data (last 6 months) for chart
        $revenueData = [];
        for ($i = 5; $i >= 0; $i--) {
            $mStart = date('Y-m-01', strtotime("-$i months"));
            $mEnd = date('Y-m-t', strtotime("-$i months"));
            $rev = $db->fetchColumn(
                "SELECT COALESCE(SUM(amount), 0) FROM payments WHERE company_id = ? AND status = 'completed' AND payment_date BETWEEN ? AND ? AND deleted_at IS NULL",
                [$cid, $mStart, $mEnd]
            );
            $revenueData[] = ['month' => date('M', strtotime($mStart)), 'amount' => (float)$rev];
        }

        $pageTitle = 'Dashboard';
        $page = 'dashboard';
        ob_start();
        require APP_PATH . '/views/dashboard/index.php';
        $content = ob_get_clean();
        require APP_PATH . '/views/layouts/app.php';
    }
}
