<?php
class ReportController {
    private $db;
    public function __construct() { $this->db = Database::getInstance(); }

    public function index() {
        require 'app/views/reports/index.php';
    }

    public function rentroll() {
        $cid = Auth::user()['company_id'];
        $data = $this->db->fetchAll("SELECT l.*, t.first_name, t.last_name, t.email, p.name as property_name, u.unit_number, u.market_rent FROM leases l JOIN tenants t ON l.tenant_id=t.id LEFT JOIN properties p ON l.property_id=p.id LEFT JOIN units u ON l.unit_id=u.id WHERE l.company_id=? AND l.status='active' AND l.deleted_at IS NULL ORDER BY p.name, u.unit_number", [$cid]);
        $totalRent = array_sum(array_column($data, 'rent_amount'));
        $totalMarket = array_sum(array_column($data, 'market_rent'));
        require 'app/views/reports/rentroll.php';
    }

    public function occupancy() {
        $cid = Auth::user()['company_id'];
        $properties = $this->db->fetchAll("SELECT p.id, p.name, (SELECT COUNT(*) FROM units WHERE property_id=p.id AND deleted_at IS NULL) as total_units, (SELECT COUNT(*) FROM units WHERE property_id=p.id AND status='occupied' AND deleted_at IS NULL) as occupied_units FROM properties p WHERE p.company_id=? AND p.deleted_at IS NULL ORDER BY p.name", [$cid]);
        require 'app/views/reports/occupancy.php';
    }

    public function delinquency() {
        $cid = Auth::user()['company_id'];
        $data = $this->db->fetchAll("SELECT t.id, t.first_name, t.last_name, t.email, t.phone, t.balance, p.name as property_name, u.unit_number, l.rent_amount FROM tenants t LEFT JOIN leases l ON t.id=l.tenant_id AND l.status='active' LEFT JOIN properties p ON l.property_id=p.id LEFT JOIN units u ON l.unit_id=u.id WHERE t.company_id=? AND t.balance > 0 AND t.deleted_at IS NULL ORDER BY t.balance DESC", [$cid]);
        $totalDelinquent = array_sum(array_column($data, 'balance'));
        require 'app/views/reports/delinquency.php';
    }

    public function payments() {
        $cid = Auth::user()['company_id']; $from = $_GET['from'] ?? date('Y-m-01'); $to = $_GET['to'] ?? date('Y-m-t');
        $data = $this->db->fetchAll("SELECT py.*, t.first_name, t.last_name, p.name as property_name, u.unit_number FROM payments py LEFT JOIN tenants t ON py.tenant_id=t.id LEFT JOIN leases l ON py.lease_id=l.id LEFT JOIN properties p ON l.property_id=p.id LEFT JOIN units u ON l.unit_id=u.id WHERE py.company_id=? AND py.payment_date BETWEEN ? AND ? AND py.deleted_at IS NULL ORDER BY py.payment_date DESC", [$cid, $from, $to]);
        $totalAmount = array_sum(array_column($data, 'amount'));
        require 'app/views/reports/payments.php';
    }

    public function maintenance() {
        $cid = Auth::user()['company_id'];
        $data = $this->db->fetchAll("SELECT mr.*, p.name as property_name, u.unit_number, t.first_name as tenant_first, t.last_name as tenant_last FROM maintenance_requests mr LEFT JOIN properties p ON mr.property_id=p.id LEFT JOIN units u ON mr.unit_id=u.id LEFT JOIN tenants t ON mr.tenant_id=t.id WHERE mr.company_id=? AND mr.deleted_at IS NULL ORDER BY mr.created_at DESC LIMIT 200", [$cid]);
        $byStatus = []; foreach ($data as $r) { $s = $r['status'] ?? 'new'; $byStatus[$s] = ($byStatus[$s] ?? 0) + 1; }
        $byPriority = []; foreach ($data as $r) { $pr = $r['priority'] ?? 'medium'; $byPriority[$pr] = ($byPriority[$pr] ?? 0) + 1; }
        require 'app/views/reports/maintenance.php';
    }

    public function leaseExpiration() {
        $cid = Auth::user()['company_id'];
        $data = $this->db->fetchAll("SELECT l.*, t.first_name, t.last_name, t.email, p.name as property_name, u.unit_number FROM leases l JOIN tenants t ON l.tenant_id=t.id LEFT JOIN properties p ON l.property_id=p.id LEFT JOIN units u ON l.unit_id=u.id WHERE l.company_id=? AND l.status='active' AND l.end_date BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 90 DAY) AND l.deleted_at IS NULL ORDER BY l.end_date", [$cid]);
        require 'app/views/reports/lease_expiration.php';
    }

    public function ownerStatement() {
        $cid = Auth::user()['company_id']; $ownerId = $_GET['owner_id'] ?? null;
        $owners = $this->db->fetchAll("SELECT id, first_name, last_name FROM owners WHERE company_id=? AND deleted_at IS NULL ORDER BY first_name", [$cid]);
        $statement = null;
        if ($ownerId) {
            $owner = $this->db->fetch("SELECT * FROM owners WHERE id=? AND company_id=?", [$ownerId, $cid]);
            $income = $this->db->fetchColumn("SELECT COALESCE(SUM(py.amount),0) FROM payments py JOIN leases l ON py.lease_id=l.id JOIN properties p ON l.property_id=p.id WHERE p.owner_id=? AND p.company_id=? AND py.status='completed' AND MONTH(py.payment_date)=MONTH(CURDATE()) AND YEAR(py.payment_date)=YEAR(CURDATE())", [$ownerId, $cid]);
            $expenses = $this->db->fetchColumn("SELECT COALESCE(SUM(e.amount),0) FROM expenses e JOIN properties p ON e.property_id=p.id WHERE p.owner_id=? AND p.company_id=? AND MONTH(e.expense_date)=MONTH(CURDATE()) AND YEAR(e.expense_date)=YEAR(CURDATE())", [$ownerId, $cid]);
            $statement = ['owner' => $owner, 'income' => $income, 'expenses' => $expenses, 'net' => $income - $expenses];
        }
        require 'app/views/reports/owner_statement.php';
    }

    public function propertyPerformance() {
        $cid = Auth::user()['company_id'];
        $data = $this->db->fetchAll("SELECT p.id, p.name, (SELECT COUNT(*) FROM units WHERE property_id=p.id AND deleted_at IS NULL) as total_units, (SELECT COUNT(*) FROM units WHERE property_id=p.id AND status='occupied' AND deleted_at IS NULL) as occupied, (SELECT COALESCE(SUM(py.amount),0) FROM payments py JOIN leases l ON py.lease_id=l.id WHERE l.property_id=p.id AND py.status='completed' AND MONTH(py.payment_date)=MONTH(CURDATE())) as monthly_income, (SELECT COALESCE(SUM(e.amount),0) FROM expenses e WHERE e.property_id=p.id AND MONTH(e.expense_date)=MONTH(CURDATE())) as monthly_expenses, (SELECT COUNT(*) FROM maintenance_requests WHERE property_id=p.id AND status NOT IN ('completed','closed','cancelled') AND deleted_at IS NULL) as open_maintenance FROM properties p WHERE p.company_id=? AND p.deleted_at IS NULL ORDER BY p.name", [$cid]);
        require 'app/views/reports/property_performance.php';
    }
}
