<?php

/**

 * AI Recommendations Engine

 * Provides smart recommendations based on predictions

 */



class AIRecommendations {

    private $conn;

    private $predictor;

    

    public function __construct() {

        $this->conn = getDBConnection();

        $this->predictor = new AIPaymentPredictor();

    }

    

    /**

     * Get smart recommendations for dashboard

     */

    public function getDashboardRecommendations() {

        $recommendations = [];

        

        // Get at-risk students

        $atRisk = $this->predictor->identifyAtRiskStudents(0.6);

        if (!empty($atRisk)) {

            $recommendations[] = [

                'type' => 'warning',

                'title' => 'At-Risk Students Detected',

                'message' => count($atRisk) . ' students have a high probability of late payment',

                'action' => 'View At-Risk List',

                'link' => 'ai_dashboard.php?view=at_risk',

                'priority' => 'high',

                'icon' => 'exclamation-triangle'

            ];

        }

        

        // Get revenue forecast - FIXED: Check if forecast exists and has the expected structure

        $forecast = $this->predictor->predictMonthlyRevenue(3);

        

        // Safely access forecast data with defaults

        $forecastValues = isset($forecast['forecast']) && is_array($forecast['forecast']) ? $forecast['forecast'] : [0, 0, 0];

        $totalExpected = isset($forecast['total_expected']) ? $forecast['total_expected'] : 0;

        

        // Calculate average only if we have values

        $avgMonthly = !empty($forecastValues) ? array_sum($forecastValues) / count($forecastValues) : 0;

        $nextMonth = isset($forecastValues[0]) ? $forecastValues[0] : 0;

        

        if ($nextMonth > $avgMonthly * 1.2 && $avgMonthly > 0) {

            $recommendations[] = [

                'type' => 'success',

                'title' => 'Positive Revenue Forecast',

                'message' => 'Expected revenue next month is ' . round(($nextMonth / $avgMonthly - 1) * 100) . '% above average',

                'action' => 'View Forecast',

                'link' => 'ai_dashboard.php?view=forecast',

                'priority' => 'medium',

                'icon' => 'chart-line'

            ];

        } elseif ($nextMonth < $avgMonthly * 0.8 && $avgMonthly > 0) {

            $recommendations[] = [

                'type' => 'warning',

                'title' => 'Revenue Dip Predicted',

                'message' => 'Expected revenue next month is ' . round((1 - $nextMonth / $avgMonthly) * 100) . '% below average',

                'action' => 'Analyze',

                'link' => 'ai_dashboard.php?view=forecast',

                'priority' => 'medium',

                'icon' => 'chart-line'

            ];

        }

        

        // Get class performance

        $classPerformance = $this->getClassPerformance();

        if (!empty($classPerformance)) {

            $lowestClass = $classPerformance[0] ?? null;

            if ($lowestClass && isset($lowestClass['collection_rate']) && $lowestClass['collection_rate'] < 50) {

                $recommendations[] = [

                    'type' => 'warning',

                    'title' => 'Low Collection Rate in ' . ($lowestClass['class'] ?? 'Unknown'),

                    'message' => 'Collection rate is only ' . round($lowestClass['collection_rate'] ?? 0) . '%',

                    'action' => 'View Class',

                    'link' => 'reports.php?report_type=class_summary&class=' . urlencode($lowestClass['class'] ?? ''),

                    'priority' => 'medium',

                    'icon' => 'users'

                ];

            }

        }

        

        // Check for upcoming due dates

        $upcomingDues = $this->getUpcomingDues(7);

        if (isset($upcomingDues['count']) && $upcomingDues['count'] > 0) {

            $totalAmount = isset($upcomingDues['total']) ? $upcomingDues['total'] : 0;

            $recommendations[] = [

                'type' => 'info',

                'title' => 'Upcoming Fee Deadlines',

                'message' => $upcomingDues['count'] . ' fees due in the next 7 days, total: ' . formatCurrency($totalAmount),

                'action' => 'Send Reminders',

                'link' => 'alerts.php?type=fee_reminder',

                'priority' => 'high',

                'icon' => 'calendar-alt'

            ];

        }

        

        // Get expense anomalies

        $anomalies = $this->detectExpenseAnomalies();

        if (!empty($anomalies)) {

            $firstAnomaly = $anomalies[0];

            $recommendations[] = [

                'type' => 'warning',

                'title' => 'Unusual Expense Detected',

                'message' => ($firstAnomaly['description'] ?? 'An expense') . ' is ' . 

                             round($firstAnomaly['deviation'] ?? 0) . '% above normal',

                'action' => 'Review',

                'link' => 'expenses.php',

                'priority' => 'medium',

                'icon' => 'file-invoice-dollar'

            ];

        }

        

        // Sort by priority

        usort($recommendations, function($a, $b) {

            $priority = ['high' => 3, 'medium' => 2, 'low' => 1];

            $aPriority = isset($a['priority']) ? ($priority[$a['priority']] ?? 1) : 1;

            $bPriority = isset($b['priority']) ? ($priority[$b['priority']] ?? 1) : 1;

            return $bPriority - $aPriority;

        });

        

        return $recommendations;

    }

    

    /**

     * Get class performance data

     */

    private function getClassPerformance() {

        $query = "SELECT 

                    s.class,

                    COUNT(DISTINCT s.id) as student_count,

                    COALESCE(SUM(p.amount_paid), 0) as total_collected,

                    COALESCE((SELECT SUM(fs.amount) FROM fee_structures fs 

                              WHERE fs.class_name = s.class), 0) as expected_total,

                    CASE 

                        WHEN COALESCE((SELECT SUM(fs.amount) FROM fee_structures fs 

                                      WHERE fs.class_name = s.class), 0) > 0 

                        THEN (COALESCE(SUM(p.amount_paid), 0) / 

                             COALESCE((SELECT SUM(fs.amount) FROM fee_structures fs 

                                      WHERE fs.class_name = s.class), 1)) * 100 

                        ELSE 0 

                    END as collection_rate

                  FROM students s

                  LEFT JOIN payments p ON s.id = p.student_id

                  WHERE s.status = 'active'

                  GROUP BY s.class

                  HAVING expected_total > 0

                  ORDER BY collection_rate ASC";

        

        $result = $this->conn->query($query);

        $performance = [];

        

        if ($result) {

            while ($row = $result->fetch_assoc()) {

                $performance[] = $row;

            }

        }

        

        return $performance;

    }

    

    /**

     * Get upcoming due dates

     */

    private function getUpcomingDues($days) {

        $query = "SELECT 

                    COUNT(*) as count,

                    COALESCE(SUM(amount), 0) as total

                  FROM fee_structures

                  WHERE due_date BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL ? DAY)";

        

        $stmt = $this->conn->prepare($query);

        $stmt->bind_param("i", $days);

        $stmt->execute();

        $result = $stmt->get_result();

        $row = $result->fetch_assoc();

        $stmt->close();

        

        return [

            'count' => $row['count'] ?? 0,

            'total' => $row['total'] ?? 0

        ];

    }

    

    /**

     * Detect expense anomalies

     */

    private function detectExpenseAnomalies() {

        // Load expense model

        $modelFile = AI_MODELS_PATH . 'expense_predictor_v1.0.json';

        if (!file_exists($modelFile)) {

            return [];

        }

        

        $modelData = json_decode(file_get_contents($modelFile), true);

        $baselines = $modelData['weights'] ?? [];

        

        // Get recent expenses

        $query = "SELECT * FROM expenses 

                  WHERE expense_date >= DATE_SUB(NOW(), INTERVAL 7 DAY)

                  ORDER BY expense_date DESC";

        

        $result = $this->conn->query($query);

        $anomalies = [];

        

        if ($result) {

            while ($expense = $result->fetch_assoc()) {

                $category = $expense['category'];

                $amount = $expense['amount'];

                

                if (isset($baselines[$category])) {

                    $expected = $baselines[$category]['avg_amount'] ?? $amount;

                    $stdDev = ($baselines[$category]['avg_amount'] ?? $amount) * 0.3;

                    

                    if ($amount > $expected + 2 * $stdDev) {

                        $deviation = $expected > 0 ? (($amount - $expected) / $expected) * 100 : 100;

                        $anomalies[] = [

                            'id' => $expense['id'],

                            'date' => $expense['expense_date'],

                            'category' => $category,

                            'description' => $expense['description'],

                            'amount' => $amount,

                            'expected' => $expected,

                            'deviation' => $deviation,

                            'severity' => $deviation > 100 ? 'high' : 'medium'

                        ];

                    }

                }

            }

        }

        

        return $anomalies;

    }

    

    /**

     * Get personalized recommendations for a student

     */

    public function getStudentRecommendations($studentId) {

        $prediction = $this->predictor->predictPaymentProbability($studentId);

        

        $recommendations = [

            'student_id' => $studentId,

            'payment_probability' => $prediction['payment_probability'] ?? 0,

            'risk_level' => $prediction['risk_level'] ?? 'Unknown',

            'risk_factors' => $prediction['risk_factors'] ?? [],

            'suggestions' => $prediction['recommendations'] ?? [],

            'next_best_action' => $this->getNextBestAction($prediction)

        ];

        

        return $recommendations;

    }

    

    /**

     * Determine next best action

     */

    private function getNextBestAction($prediction) {

        $probability = $prediction['payment_probability'] ?? 0;

        

        if ($probability < 30) {

            return [

                'action' => 'Immediate Contact',

                'description' => 'Call parent today to discuss payment options',

                'priority' => 'high',

                'estimated_impact' => 'High'

            ];

        } elseif ($probability < 60) {

            return [

                'action' => 'Send Reminder',

                'description' => 'Send SMS and email reminder with due date',

                'priority' => 'medium',

                'estimated_impact' => 'Medium'

            ];

        } else {

            return [

                'action' => 'Monitor',

                'description' => 'Continue monitoring; no immediate action needed',

                'priority' => 'low',

                'estimated_impact' => 'Low'

            ];

        }

    }

}