<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class AiRecommendationController extends Controller
{
    public function index()
    {
        $recommendations = [];

        // 1. High-Risk Defaulters (Overdue by more than 60 days)
        $highRiskDefaulters = \App\Models\Installment::where('status', 'Overdue')
            ->whereDate('due_date', '<', now()->subDays(60))
            ->with(['installmentPlan.booking.customer'])
            ->get()
            ->unique(function ($item) {
                return $item->installmentPlan->booking->customer_id ?? null;
            });
            
        foreach ($highRiskDefaulters as $installment) {
            $customer = $installment->installmentPlan->booking->customer ?? null;
            if ($customer) {
                $recommendations[] = [
                    'type' => 'High Risk Defaulter',
                    'level' => 'Critical',
                    'message' => "Customer {$customer->full_name} is overdue by over 60 days.",
                    'action_url' => route('customers.show', $customer->id),
                    'action_text' => 'View Profile',
                ];
            }
        }

        // 2. Missing Documents
        $bookingsWithMissingDocs = \App\Models\Booking::whereDoesntHave('documents')
            ->where('status', '!=', 'Cancelled')
            ->with(['customer'])
            ->get();
            
        foreach ($bookingsWithMissingDocs as $booking) {
            if ($booking->customer) {
                $recommendations[] = [
                    'type' => 'Missing Documents',
                    'level' => 'Warning',
                    'message' => "Booking #{$booking->id} for {$booking->customer->full_name} has no uploaded documents.",
                    'action_url' => route('bookings.show', $booking->id),
                    'action_text' => 'Upload Documents',
                ];
            }
        }

        // 3. Unusual Discounts (Discount > 15% of total price)
        $unusualDiscounts = \App\Models\Booking::where('discount', '>', 0)
            ->whereRaw('(discount / total_price) > 0.15')
            ->with(['customer'])
            ->get();

        foreach ($unusualDiscounts as $booking) {
            if ($booking->customer) {
                $discountPercent = round(($booking->discount / $booking->total_price) * 100, 2);
                $recommendations[] = [
                    'type' => 'Unusual Discount',
                    'level' => 'Info',
                    'message' => "Booking #{$booking->id} has a high discount of {$discountPercent}% (Rs " . number_format($booking->discount) . ").",
                    'action_url' => route('bookings.show', $booking->id),
                    'action_text' => 'Review Booking',
                ];
            }
        }

        return view('ai.recommendations', compact('recommendations'));
    }
}
