<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\AdReport;
use Illuminate\Support\Facades\DB;

class AdSafetyController extends Controller
{
    /**
     * Display a listing of ad reports.
     *
     * @return \Illuminate\View\View
     */
    public function index(Request $request)
    {
        $query = AdReport::with(['ad', 'reporter']);

        // Search
        if ($request->has('search') && $request->search != '') {
            $search = $request->search;
            $query->where(function($q) use ($search) {
                $q->where('description', 'like', "%{$search}%")
                  ->orWhere('reason', 'like', "%{$search}%")
                  ->orWhereHas('ad', function($q) use ($search) {
                      $q->where('title', 'like', "%{$search}%");
                  })
                  ->orWhereHas('reporter', function($q) use ($search) {
                      $q->where('name', 'like', "%{$search}%");
                  });
            });
        }

        // Status Filter
        if ($request->has('status') && $request->status != '') {
            $query->where('status', $request->status);
        }

        // Get stats before pagination
        $stats = [
            'total_pending' => AdReport::where('status', 'pending')->count(),
            'high_risk' => 0, // Calculated dynamically below due to lack of DB column
            'resolved_today' => AdReport::where('status', 'resolved')->whereDate('updated_at', today())->count(),
        ];

        // Basic ordering
        $query->orderByRaw("FIELD(status, 'pending', 'reviewed', 'resolved', 'rejected')")
              ->orderBy('created_at', 'desc');

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

        // Calculate high risk count from the current set (approximate for UI if no column)
        // Ideally we'd persist risk_score to DB. For now, we'll iterate pending reports for a quick check or just leave it zero if too heavy.
        // Let's optimize: High risk usually means 'scam' reason.
        $stats['high_risk'] = AdReport::where('status', 'pending')->whereIn('reason', ['scam', 'fraud', 'prohibited'])->count();

        return view('admin.safety.reports', compact('reports', 'stats'));
    }

    /**
     * Handle a report action.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function handle(Request $request, $id)
    {
        $report = AdReport::findOrFail($id);
        $request->validate([
            'action' => 'required|in:suspend_ad,ban_user,dismiss,needs_edit',
            'notes' => 'nullable|string'
        ]);

        try {
            DB::beginTransaction();

            $report->admin_notes = $request->notes;
            $report->action_taken = $request->action;
            $report->status = 'resolved'; // Default to resolved unless dismissed

            if ($request->action === 'dismiss') {
                $report->status = 'rejected';
            } elseif ($request->action === 'suspend_ad') {
                $report->ad->update(['status' => 'suspended']);
            } elseif ($request->action === 'ban_user') {
                // Ban the ad owner, not the reporter!
                $report->ad->user->update(['status' => 'banned']);
                $report->ad->update(['status' => 'suspended']); // Also suspend the ad
            } elseif ($request->action === 'needs_edit') {
                $report->ad->update(['status' => 'draft']); // Or a specific status like 'needs_change'
                // TODO: Trigger notification to user
            }

            $report->save();
            DB::commit();

            return response()->json(['success' => true, 'message' => 'Action taken successfully.']);

        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['success' => false, 'message' => 'Error processing action.'], 500);
        }
    }

    public function updateSettings(Request $request)
    {
        $request->validate([
            'auto_suspend_threshold' => 'required|integer|min:1',
            'auto_ban_threshold' => 'required|integer|min:1',
            'scam_keywords' => 'required|string',
        ]);

        $settings = [
            'safety.auto_suspend_threshold' => $request->auto_suspend_threshold,
            'safety.auto_ban_threshold' => $request->auto_ban_threshold,
            'safety.ai_enabled' => $request->ai_enabled === 'true' ? 'true' : 'false',
            'safety.scam_keywords' => $request->scam_keywords,
        ];

        foreach ($settings as $key => $value) {
            \App\Models\Setting::updateOrCreate(
                ['key' => $key],
                ['value' => $value]
            );
        }

        return redirect()->back()->with('success', 'Safety settings updated successfully.');
    }

    public function updateTrustAlgorithm(Request $request)
    {
        // Validation would go here, accepting the JSON structure from frontend or flat form data
        // For simplicity with the existing blade JS, we'll accept a JSON payload or flattened keys
        
        $data = $request->all();
        
        // Map UI keys to Settings Table Keys
        $mappings = [
            // Thresholds
            'thresholds_high' => 'safety_threshold_high',
            'thresholds_medium' => 'safety_threshold_medium',
            'thresholds_low' => 'safety_threshold_low',
            
            // Weights (Max Points)
            'weights_transaction' => 'trust_score_max_sales',
            'weights_reputation' => 'trust_score_max_reputation',
            'weights_maturity' => 'trust_score_max_maturity',
            'weights_content' => 'trust_score_max_content',
            'weights_behavior' => 'trust_score_max_behavior',
            'weights_security' => 'trust_score_max_security',
            
            // Penalties
            'penalties_report' => 'trust_penalty_report',
            'penalties_warning' => 'trust_penalty_warning',
            'penalties_suspension' => 'trust_penalty_suspension',
            'penalties_multiplier' => 'trust_penalty_multiplier',
            
            // Tiers
            'tiers_legend' => 'trust_tier_legend',
            'tiers_elite' => 'trust_tier_elite',
            'tiers_highlyTrusted' => 'trust_tier_highly_trusted',
            'tiers_trusted' => 'trust_tier_trusted',
        ];

        foreach ($data as $uiKey => $value) {
            if (isset($mappings[$uiKey])) {
                \App\Models\Setting::updateOrCreate(
                    ['key' => $mappings[$uiKey]],
                    ['value' => $value]
                );
            }
        }

        if ($request->wantsJson()) {
            return response()->json(['success' => true, 'message' => 'Algorithm settings updated successfully.']);
        }
        
        return redirect()->back()->with('success', 'Algorithm settings updated successfully.');
    }
}
