<?php

namespace App\Http\Controllers;

use App\Models\SafetyReport;
use App\Models\UserTrustScore;
use App\Models\SafetyAction;
use App\Models\Ad;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Log;

class SafetyController extends Controller
{
    /**
     * Report an ad or user for safety concerns
     */
    public function report(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'reported_user_id' => 'required|exists:users,id',
            'ad_id' => 'nullable|exists:ads,id',
            'report_type' => 'required|string|in:scam,fake,spam,inappropriate,other',
            'description' => 'nullable|string|max:1000',
            'is_anonymous' => 'boolean',
            'evidence' => 'nullable|array',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed',
                'errors' => $validator->errors()
            ], 422);
        }

        try {
            $report = SafetyReport::create([
                'reported_user_id' => $request->reported_user_id,
                'ad_id' => $request->ad_id,
                'report_type' => $request->report_type,
                'description' => $request->description,
                'reporter_id' => Auth::check() ? Auth::id() : null,
                'is_anonymous' => $request->is_anonymous ?? false,
                'evidence' => $request->evidence,
                'status' => 'pending'
            ]);

            // Trigger automated detection
            $this->triggerAutomatedDetection($report);

            return response()->json([
                'success' => true,
                'message' => 'Report submitted successfully',
                'report' => $report
            ], 201);

        } catch (\Exception $e) {
            Log::error('Safety report failed: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Failed to submit report'
            ], 500);
        }
    }

    /**
     * Get user's trust score
     */
    public function getTrustScore(Request $request, $userId = null)
    {
        $user = $userId ? User::find($userId) : Auth::user();
        
        if (!$user) {
            return response()->json([
                'success' => false,
                'message' => 'User not found'
            ], 404);
        }

        $trustScore = UserTrustScore::firstOrCreate(
            ['user_id' => $user->id],
            [
                'score' => 50,
                'tier' => 'trusted',
                'breakdown' => $this->getDefaultBreakdown()
            ]
        );

        // Update score if older than 1 hour
        if (!$trustScore->last_calculated || now()->diffInHours($trustScore->last_calculated) > 1) {
            $this->calculateTrustScore($user);
        }

        return response()->json([
            'success' => true,
            'trust_score' => $trustScore,
            'user' => [
                'id' => $user->id,
                'name' => $user->name,
                'email' => $user->email,
                'is_verified' => $user->is_verified
            ]
        ]);
    }

    /**
     * Admin: Get safety reports
     */
    public function getReports(Request $request)
    {
        $this->authorize('viewSafetyReports', User::class);

        $query = SafetyReport::with(['reportedUser', 'ad', 'reporter', 'admin'])
            ->latest();

        // Filters
        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        if ($request->filled('type')) {
            $query->where('report_type', $request->type);
        }

        if ($request->filled('user_id')) {
            $query->where('reported_user_id', $request->user_id);
        }

        $reports = $query->paginate(20);

        return response()->json([
            'success' => true,
            'reports' => $reports
        ]);
    }

    /**
     * Admin: Review a safety report
     */
    public function reviewReport(Request $request, $reportId)
    {
        $this->authorize('manageSafetyReports', User::class);

        $validator = Validator::make($request->all(), [
            'status' => 'required|string|in:reviewed,action_taken,dismissed',
            'admin_notes' => 'nullable|string|max:500',
            'action_type' => 'nullable|string',
            'action_reason' => 'nullable|string',
            'action_duration' => 'nullable|integer|min:1|max:365'
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed',
                'errors' => $validator->errors()
            ], 422);
        }

        $report = SafetyReport::findOrFail($reportId);
        $report->status = $request->status;
        $report->admin_id = Auth::id();
        $report->reviewed_at = now();
        $report->admin_notes = $request->admin_notes;
        $report->save();

        // Take action if needed
        if ($request->filled('action_type')) {
            $this->takeSafetyAction($report, $request->action_type, $request->action_reason, $request->action_duration);
        }

        return response()->json([
            'success' => true,
            'message' => 'Report reviewed successfully',
            'report' => $report
        ]);
    }

    /**
     * Admin: Get safety analytics
     */
    public function getAnalytics(Request $request)
    {
        $this->authorize('viewSafetyAnalytics', User::class);

        $analytics = [
            'total_reports' => SafetyReport::count(),
            'pending_reports' => SafetyReport::where('status', 'pending')->count(),
            'resolved_reports' => SafetyReport::whereIn('status', ['reviewed', 'action_taken', 'dismissed'])->count(),
            'trust_score_distribution' => $this->getTrustScoreDistribution(),
            'recent_reports' => SafetyReport::with(['reportedUser', 'ad'])
                ->latest()
                ->limit(10)
                ->get(),
            'safety_actions' => SafetyAction::with(['user', 'admin'])
                ->latest()
                ->limit(20)
                ->get()
        ];

        return response()->json([
            'success' => true,
            'analytics' => $analytics
        ]);
    }

    /**
     * Admin: Take manual safety action
     */
    public function takeManualAction(Request $request)
    {
        $this->authorize('manageSafetyActions', User::class);

        $validator = Validator::make($request->all(), [
            'user_id' => 'required|exists:users,id',
            'action_type' => 'required|string',
            'reason' => 'required|string|max:500',
            'duration_days' => 'nullable|integer|min:1|max:365'
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed',
                'errors' => $validator->errors()
            ], 422);
        }

        $action = SafetyAction::create([
            'user_id' => $request->user_id,
            'action_type' => $request->action_type,
            'reason' => $request->reason,
            'auto_generated' => false,
            'admin_id' => Auth::id(),
            'expires_at' => $request->duration_days ? now()->addDays($request->duration_days) : null,
            'is_active' => true
        ]);

        // Apply the action
        $this->applySafetyAction($action);

        return response()->json([
            'success' => true,
            'message' => 'Safety action applied successfully',
            'action' => $action
        ]);
    }

    /**
     * Helper: Trigger automated detection
     */
    protected function triggerAutomatedDetection(SafetyReport $report)
    {
        // Check for scam patterns
        $scamScore = $this->calculateScamScore($report);
        
        if ($scamScore > 70) {
            // High confidence scam - auto action
            $this->takeSafetyAction($report, 'auto_suspend', 'High scam probability detected', 7);
        } elseif ($scamScore > 40) {
            // Medium confidence - flag for review
            $this->takeSafetyAction($report, 'manual_review', 'Medium scam probability detected', null);
        }
    }

    /**
     * Helper: Calculate scam score
     */
    protected function calculateScamScore(SafetyReport $report)
    {
        $score = 0;

        // Check report type
        $scamTypes = ['scam', 'fake'];
        if (in_array($report->report_type, $scamTypes)) {
            $score += 30;
        }

        // Check description for scam keywords
        $scamKeywords = ['urgent', 'too good', 'send money', 'wire transfer', 'advance fee', 'lottery', 'inheritance'];
        $description = strtolower($report->description ?? '');
        
        foreach ($scamKeywords as $keyword) {
            if (strpos($description, $keyword) !== false) {
                $score += 10;
            }
        }

        // Check if reported user has previous reports
        $previousReports = SafetyReport::where('reported_user_id', $report->reported_user_id)
            ->where('status', 'action_taken')
            ->count();
        
        $score += $previousReports * 15;

        return min($score, 100);
    }

    /**
     * Helper: Take safety action
     */
    protected function takeSafetyAction(SafetyReport $report, $actionType, $reason, $durationDays = null)
    {
        $action = SafetyAction::create([
            'user_id' => $report->reported_user_id,
            'report_id' => $report->id,
            'action_type' => $actionType,
            'reason' => $reason,
            'auto_generated' => true,
            'expires_at' => $durationDays ? now()->addDays($durationDays) : null,
            'is_active' => true
        ]);

        $this->applySafetyAction($action);
    }

    /**
     * Helper: Apply safety action
     */
    protected function applySafetyAction(SafetyAction $action)
    {
        switch ($action->action_type) {
            case 'auto_suspend':
            case 'manual_suspend':
                $this->suspendUser($action->user, $action->expires_at, $action->reason);
                break;
            
            case 'auto_delete':
                $this->deleteUserContent($action->user);
                break;
            
            case 'warning':
                $this->sendWarning($action->user, $action->reason);
                break;
        }
    }

    /**
     * Helper: Calculate trust score
     */
    protected function calculateTrustScore(User $user)
    {
        $trustScore = UserTrustScore::firstOrCreate(
            ['user_id' => $user->id],
            [
                'score' => 50,
                'tier' => 'trusted',
                'breakdown' => $this->getDefaultBreakdown()
            ]
        );

        $score = 50;
        $breakdown = [];

        // Transaction History (30%)
        $completedSales = $user->ads()->where('status', 'sold')->count();
        $breakdown['transaction_history'] = min($completedSales * 2, 30);
        $score += $breakdown['transaction_history'];

        // Account Maturity (20%)
        $accountAge = $user->created_at->diffInMonths(now());
        $breakdown['account_maturity'] = min($accountAge * 1, 20);
        $score += $breakdown['account_maturity'];

        // Content Quality (25%)
        $qualityScore = $this->calculateContentQuality($user);
        $breakdown['content_quality'] = $qualityScore;
        $score += $qualityScore;

        // Behavior Analysis (15%)
        $behaviorScore = $this->calculateBehaviorScore($user);
        $breakdown['behavior'] = $behaviorScore;
        $score += $behaviorScore;

        // Security Features (10%)
        $securityScore = 0;
        if ($user->phone_verified) $securityScore += 5;
        if ($user->id_verified) $securityScore += 5;
        $breakdown['security'] = $securityScore;
        $score += $securityScore;

        // Apply penalties
        $penaltyPoints = $this->calculatePenaltyPoints($user);
        $score -= $penaltyPoints;

        // Ensure score is within bounds
        $score = max(0, min(100, $score));

        $trustScore->update([
            'score' => $score,
            'tier' => $trustScore->calculateTier($score),
            'breakdown' => $breakdown,
            'penalty_points' => $penaltyPoints,
            'last_calculated' => now()
        ]);

        return $trustScore;
    }

    /**
     * Helper: Get default breakdown
     */
    protected function getDefaultBreakdown()
    {
        return [
            'transaction_history' => 0,
            'account_maturity' => 0,
            'content_quality' => 0,
            'behavior' => 0,
            'security' => 0
        ];
    }

    /**
     * Helper: Calculate content quality
     */
    protected function calculateContentQuality(User $user)
    {
        $ads = $user->ads;
        if ($ads->isEmpty()) return 10; // New users get base score

        $totalScore = 0;
        foreach ($ads as $ad) {
            $score = 10; // Base score
            
            // Description quality
            if (strlen($ad->description ?? '') > 100) $score += 3;
            if ($ad->images && count($ad->images) >= 3) $score += 2;
            
            // Price accuracy (compare to category average)
            // This would need category average calculation
            
            $totalScore += $score;
        }

        return min($totalScore / $ads->count(), 25);
    }

    /**
     * Helper: Calculate behavior score
     */
    protected function calculateBehaviorScore(User $user)
    {
        $score = 10; // Base score

        // Check for reports
        $reports = SafetyReport::where('reported_user_id', $user->id)
            ->where('status', 'action_taken')
            ->count();
        
        $score -= $reports * 3;

        // Check response rate (simplified)
        // This would need messaging system integration

        return max(0, $score);
    }

    /**
     * Helper: Calculate penalty points
     */
    protected function calculatePenaltyPoints(User $user)
    {
        $points = 0;

        // Active safety actions
        $activeActions = SafetyAction::where('user_id', $user->id)
            ->where('is_active', true)
            ->where('expires_at', '>', now())
            ->count();

        $points += $activeActions * 10;

        // Recent reports
        $recentReports = SafetyReport::where('reported_user_id', $user->id)
            ->where('created_at', '>=', now()->subMonths(3))
            ->count();

        $points += $recentReports * 5;

        return $points;
    }

    /**
     * Helper: Get trust score distribution
     */
    protected function getTrustScoreDistribution()
    {
        return [
            'legend' => UserTrustScore::where('score', '>=', 85)->count(),
            'elite' => UserTrustScore::whereBetween('score', [70, 84])->count(),
            'highly_trusted' => UserTrustScore::whereBetween('score', [50, 69])->count(),
            'trusted' => UserTrustScore::whereBetween('score', [30, 49])->count(),
            'new' => UserTrustScore::where('score', '<', 30)->count(),
        ];
    }

    /**
     * Helper: Suspend user
     */
    protected function suspendUser(User $user, $until, $reason)
    {
        $user->update([
            'is_suspended' => true,
            'suspension_until' => $until,
            'suspension_reason' => $reason
        ]);

        // Suspend all their ads
        $user->ads()->update(['status' => 'suspended']);
    }

    /**
     * Helper: Delete user content
     */
    protected function deleteUserContent(User $user)
    {
        // Soft delete all their ads
        $user->ads()->update(['status' => 'deleted']);
    }

    /**
     * Helper: Send warning
     */
    protected function sendWarning(User $user, $reason)
    {
        // This would integrate with your notification system
        // For now, just log it
        Log::info("Warning sent to user {$user->id}: {$reason}");
    }
}
