<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Setting;
use App\Models\Tier;
use App\Models\TierAssessment;
use App\Models\User;
use App\Services\TierEngine;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class TierController extends Controller
{
    public function __construct(private TierEngine $engine) {}

    /**
     * Quarterly assessment dashboard — pending assessments + member overview.
     */
    public function index()
    {
        $autoSuggest = Setting::get('tier_auto_suggest', true);

        $pending = TierAssessment::with(['user', 'previousTier', 'recommendedTier'])
            ->where('status', 'pending')
            ->latest('assessed_at')
            ->paginate(20);

        $tierStats = Tier::withCount(['members as current_members_count'])->orderBy('display_order')->get();

        $atRiskCount = 0;
        User::where('status', 'active')->with(['currentTier.tier', 'visits'])->chunk(50, function ($members) use (&$atRiskCount) {
            foreach ($members as $user) {
                $result = $this->engine->evaluate($user);
                if ($result['at_risk']) $atRiskCount++;
            }
        });

        return view('admin.tiers.index', compact('pending', 'autoSuggest', 'tierStats', 'atRiskCount'));
    }

    /**
     * Toggle auto-suggest on/off.
     */
    public function toggleAutoSuggest(Request $request)
    {
        $current = Setting::get('tier_auto_suggest', true);
        Setting::set('tier_auto_suggest', ! $current);

        return redirect()->route('admin.tiers.index')
            ->with('success', 'Auto-suggest ' . (! $current ? 'enabled' : 'disabled') . '.');
    }

    /**
     * Run quarterly assessment now (admin-triggered).
     */
    public function runAssessment()
    {
        $count = $this->engine->runQuarterlyAssessment(Auth::guard('admin')->id());

        return redirect()->route('admin.tiers.index')
            ->with('success', "Assessment complete. {$count} member" . ($count !== 1 ? 's' : '') . " flagged for review.");
    }

    /**
     * Show a single member's tier evaluation detail.
     */
    public function evaluate(User $user)
    {
        $result = $this->engine->evaluate($user);
        $tiers  = Tier::orderBy('display_order')->get();
        return view('admin.tiers.evaluate', compact('user', 'result', 'tiers'));
    }

    /**
     * Manually override a member's tier.
     */
    public function override(Request $request, User $user)
    {
        $data = $request->validate([
            'tier_id' => ['required', 'exists:tiers,id'],
            'reason'  => ['required', 'string', 'max:500'],
        ]);

        $newTier = Tier::findOrFail($data['tier_id']);
        $this->engine->applyTierChange($user, $newTier, Auth::guard('admin')->id(), $data['reason'], 'manual');

        // Dismiss any pending assessments for this member
        TierAssessment::where('user_id', $user->id)->where('status', 'pending')
            ->update(['status' => 'actioned', 'actioned_by' => Auth::guard('admin')->id(), 'actioned_at' => now(), 'new_tier_id' => $newTier->id]);

        return redirect()->route('admin.members.show', $user)
            ->with('success', "Tier updated to {$newTier->name} for {$user->full_name}.");
    }

    /**
     * Action a pending assessment — approve or dismiss.
     */
    public function action(Request $request, TierAssessment $assessment)
    {
        $data = $request->validate([
            'decision' => ['required', 'in:approve,dismiss'],
            'reason'   => ['nullable', 'string', 'max:500'],
        ]);

        if ($data['decision'] === 'approve') {
            $this->engine->applyTierChange(
                $assessment->user,
                $assessment->recommendedTier,
                Auth::guard('admin')->id(),
                $data['reason'] ?? $assessment->reason,
                $assessment->trigger
            );
            $assessment->update([
                'status'      => 'actioned',
                'new_tier_id' => $assessment->recommended_tier_id,
                'actioned_by' => Auth::guard('admin')->id(),
                'actioned_at' => now(),
                'reason'      => $data['reason'] ?? $assessment->reason,
            ]);
            $msg = "Tier change approved for {$assessment->user->full_name}.";
        } else {
            $assessment->update([
                'status'      => 'dismissed',
                'actioned_by' => Auth::guard('admin')->id(),
                'actioned_at' => now(),
                'reason'      => $data['reason'] ?? 'Dismissed by admin.',
            ]);
            $msg = "Assessment dismissed for {$assessment->user->full_name}.";
        }

        return redirect()->route('admin.tiers.index')->with('success', $msg);
    }
}
