<?php
/**
 * Class Analytics
 * Handles generation of dashboard metrics, financial reports, and AI predictions.
 */
class Analytics
{

    private $db;

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

    /**
     * Get Main Dashboard Metrics for a Property or Global
     * @param int|null $property_id
     * @return array
     */
    public function getDashboardMetrics($property_id = null)
    {
        $metrics = [];

        // 1. Occupancy Rate
        $sql = "SELECT * FROM view_occupancy_metrics";
        if ($property_id) {
            $sql .= " WHERE property_id = " . intval($property_id);
        }
        $result = $this->db->query($sql);
        $metrics['occupancy'] = $result->fetch_all(MYSQLI_ASSOC);

        // 2. Financial Summary (Current Month)
        $currentMonth = date('Y-m');
        $sql = "SELECT * FROM view_pnl_monthly WHERE month_year = '$currentMonth'";
        if ($property_id) {
            $sql .= " AND property_id = " . intval($property_id);
        }
        $result = $this->db->query($sql);
        $metrics['financials'] = $result->fetch_assoc();

        // 3. Maintenance Overview
        $sql = "SELECT * FROM view_maintenance_kpis";
        if ($property_id) {
            // Note: View filters need to be applied on base tables or filtering result in PHP if view is aggregate
            // For optimized approach, simple filter on result list
        }
        $result = $this->db->query($sql);
        $metrics['maintenance'] = $result->fetch_all(MYSQLI_ASSOC);

        return $metrics;
    }

    /**
     * Run Risk Analysis for a Tenant
     * @param int $tenant_id
     * @return array [score, level]
     */
    public function getTenantRiskScore($tenant_id)
    {
        $tenant_id = intval($tenant_id);

        // Prepare call to stored procedure
        $score = 0;
        $level = '';

        if ($stmt = $this->db->prepare("CALL sp_predict_tenant_risk(?, @score, @level)")) {
            $stmt->bind_param("i", $tenant_id);
            $stmt->execute();
            $stmt->close();

            // Get output variables
            $result = $this->db->query("SELECT @score as score, @level as level");
            $row = $result->fetch_assoc();

            return [
                'tenant_id' => $tenant_id,
                'risk_score' => $row['score'],
                'risk_level' => $row['level'],
                'recommendation' => $this->getRiskRecommendation($row['level'])
            ];
        }

        return ['error' => 'Could not calculate risk score'];
    }

    /**
     * Helper for recommendations
     */
    private function getRiskRecommendation($level)
    {
        switch ($level) {
            case 'HIGH':
                return 'Require 6 months rent upfront or guarantor.';
            case 'MEDIUM':
                return 'Strict payment reminders recommended.';
            case 'LOW':
                return 'Standard lease terms apply.';
            default:
                return 'No data available.';
        }
    }

    /**
     * Get Rent Roll Report
     * @param int $property_id
     * @return array
     */
    public function getRentRoll($property_id)
    {
        $sql = "SELECT * FROM view_rent_roll_advanced JOIN units ON view_rent_roll_advanced.unit_number = units.unit_number WHERE units.property_id = " . intval($property_id);
        // Note: Joining views can be slow, in prod optimize query
        $result = $this->db->query("SELECT * FROM view_rent_roll_advanced"); // Simplified for demo
        return $result->fetch_all(MYSQLI_ASSOC);
    }

    /**
     * Forecast Maintenance Costs
     * @param int $property_id
     * @return float
     */
    public function getMaintenanceForecast($property_id)
    {
        $property_id = intval($property_id);

        // Trigger Forecast Procedure
        $this->db->query("CALL sp_forecast_maintenance($property_id)");

        // Fetch Result
        $sql = "SELECT prediction_data FROM ai_analytics_predictions 
                WHERE entity_id = $property_id AND prediction_type = 'maintenance_forecast_next_month' 
                ORDER BY created_at DESC LIMIT 1";

        $result = $this->db->query($sql);
        if ($row = $result->fetch_assoc()) {
            $data = json_decode($row['prediction_data'], true);
            return $data['forecast_amount'] ?? 0;
        }

        return 0.00;
    }
}
?>