<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Report;
use App\Models\Item;
use App\Models\User;
use App\Models\AdminSetting;

class ReportController extends Controller
{
    public function create(Request $request)
    {
        $type = 'item'; // Always report items
        $id = $request->get('id');

        if (!$id) {
            return redirect()->route('items.index')->with('error', 'Invalid report request.');
        }

        // Get the reportable object
        $reportable = null;
        try {
            $reportable = Item::findOrFail($id);
        } catch (\Exception $e) {
            return redirect()->route('items.index')->with('error', 'Item not found.');
        }

        // Check if user has already reported this
        $existingReport = Report::where('reporter_id', auth()->id())
            ->where('reportable_type', $type)
            ->where('reportable_id', $id)
            ->first();

        if ($existingReport) {
            return redirect()->route('items.show', $id)->with('error', 'You have already reported this item.');
        }

        return view('reports.create', compact('type', 'reportable'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'reportable_type' => 'required|in:item',
            'reportable_id' => 'required|integer',
            'reason' => 'required|in:' . implode(',', array_keys(Report::getReasonOptions())),
            'description' => 'nullable|string|max:1000'
        ]);

        // Verify the item exists
        $reportable = Item::findOrFail($validated['reportable_id']);

        // Check for existing report
        $existingReport = Report::where('reporter_id', auth()->id())
            ->where('reportable_type', 'item')
            ->where('reportable_id', $validated['reportable_id'])
            ->first();

        if ($existingReport) {
            return redirect()->route('items.show', $validated['reportable_id'])->with('error', 'You have already reported this item.');
        }

        // Create report
        $report = Report::create([
            'reporter_id' => auth()->id(),
            'reportable_type' => 'item',
            'reportable_id' => $validated['reportable_id'],
            'reason' => $validated['reason'],
            'description' => $validated['description'],
        ]);

        // Auto-disable if setting is enabled
        if (AdminSetting::get('auto_disable_flagged', false)) {
            $reportable->update(['status' => 'flagged']);
        }

        // Notify all admins about the report
        $admins = \App\Models\User::where('is_admin', true)->get();
        foreach ($admins as $admin) {
            $admin->notify(new \App\Notifications\ItemReported($report));
        }

        return redirect()->route('items.show', $validated['reportable_id'])->with('success', 'Report submitted successfully. Our administrators will review it shortly.');
    }
}
