<?php
namespace App\Controllers;

use Core\Controller;
use App\Helpers\Helper;

class AdminController extends Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->requireRole(['super_admin','property_owner','property_manager','accountant','receptionist']);
    }

    public function dashboard(): void
    {
        // Dashboard statistics
        $stats = [
            'total_properties' => (int) $this->db->fetchColumn("SELECT COUNT(*) FROM properties WHERE status='active'"),
            'total_units'      => (int) $this->db->fetchColumn("SELECT COUNT(*) FROM units"),
            'occupied_units'   => (int) $this->db->fetchColumn("SELECT COUNT(*) FROM units WHERE status='occupied'"),
            'available_units'  => (int) $this->db->fetchColumn("SELECT COUNT(*) FROM units WHERE status='available'"),
            'total_tenants'    => (int) $this->db->fetchColumn("SELECT COUNT(*) FROM tenants WHERE status='active'"),
            'active_leases'    => (int) $this->db->fetchColumn("SELECT COUNT(*) FROM leases WHERE status='active'"),
            'pending_bookings' => (int) $this->db->fetchColumn("SELECT COUNT(*) FROM bookings WHERE status='pending'"),
            'open_maintenance' => (int) $this->db->fetchColumn("SELECT COUNT(*) FROM maintenance_requests WHERE status IN ('open','in_progress')"),
        ];

        // Revenue this month
        $stats['monthly_revenue'] = (float) $this->db->fetchColumn(
            "SELECT COALESCE(SUM(amount),0) FROM payments WHERE status='completed' AND MONTH(payment_date)=MONTH(NOW()) AND YEAR(payment_date)=YEAR(NOW())"
        );

        // Overdue invoices
        $stats['overdue_invoices'] = (int) $this->db->fetchColumn("SELECT COUNT(*) FROM invoices WHERE status='overdue'");
        $stats['overdue_amount']   = (float) $this->db->fetchColumn("SELECT COALESCE(SUM(balance),0) FROM invoices WHERE status='overdue'");

        // Occupancy rate
        $stats['occupancy_rate'] = $stats['total_units'] > 0
            ? round(($stats['occupied_units'] / $stats['total_units']) * 100, 1) : 0;

        // Recent payments
        $recentPayments = $this->db->fetchAll(
            "SELECT p.*, CONCAT(t.first_name,' ',t.last_name) AS tenant_name, u.unit_number,
                    pm.name AS method_name
             FROM payments p
             JOIN tenants t ON t.id = p.tenant_id
             LEFT JOIN units u ON u.id = p.unit_id
             LEFT JOIN payment_methods pm ON pm.id = p.payment_method_id
             WHERE p.status='completed'
             ORDER BY p.created_at DESC LIMIT 10"
        );

        // Recent bookings
        $recentBookings = $this->db->fetchAll(
            "SELECT b.*, pr.name AS property_name, u.unit_number
             FROM bookings b
             JOIN properties pr ON pr.id = b.property_id
             JOIN units u ON u.id = b.unit_id
             ORDER BY b.created_at DESC LIMIT 8"
        );

        // Monthly revenue chart data (last 12 months)
        $revenueChart = $this->db->fetchAll(
            "SELECT DATE_FORMAT(payment_date,'%Y-%m') AS month, SUM(amount) AS total
             FROM payments WHERE status='completed' AND payment_date >= DATE_SUB(NOW(), INTERVAL 12 MONTH)
             GROUP BY DATE_FORMAT(payment_date,'%Y-%m') ORDER BY month"
        );

        // Upcoming lease renewals
        $upcomingRenewals = $this->db->fetchAll(
            "SELECT l.*, CONCAT(t.first_name,' ',t.last_name) AS tenant_name, 
                    u.unit_number, p.name AS property_name
             FROM leases l
             JOIN tenants t ON t.id = l.tenant_id
             JOIN units u ON u.id = l.unit_id
             JOIN properties p ON p.id = l.property_id
             WHERE l.status='active' AND l.end_date BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 30 DAY)
             ORDER BY l.end_date ASC LIMIT 10"
        );

        // Emergency maintenance
        $emergencyMaintenance = $this->db->fetchAll(
            "SELECT mr.*, u.unit_number, p.name AS property_name
             FROM maintenance_requests mr
             JOIN units u ON u.id = mr.unit_id
             JOIN properties p ON p.id = mr.property_id
             WHERE mr.priority='emergency' AND mr.status IN ('open','in_progress')
             ORDER BY mr.created_at DESC"
        );

        $this->adminView('admin.dashboard', compact(
            'stats', 'recentPayments', 'recentBookings', 'revenueChart',
            'upcomingRenewals', 'emergencyMaintenance'
        ) + ['title' => 'Dashboard - ' . APP_NAME], 'admin');
    }
}
