<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\TrustScore;
use App\Models\User;
use Illuminate\Http\Request;

class TrustScoreController extends Controller
{
   public function __construct()
    {
        $this->middleware('permission:view trust score', ['only' => ['index', 'show']]);
        $this->middleware('permission:create trust score', ['only' => ['create', 'store']]);
        $this->middleware('permission:update trust score', ['only' => ['edit', 'update']]);
        $this->middleware('permission:delete trust score', ['only' => ['destroy']]);
    }

    public function index()
    {
        $trustScores = TrustScore::with(['user', 'reviewer'])->latest()->paginate(20);
        $users = User::orderBy('name')->get();

        return view('admin.trust-scores.index', compact('trustScores', 'users'));
    }

    public function create()
    {
        return redirect()->route('admin.trust-scores.index');
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'user_id' => ['required', 'exists:users,id'],
            'score_change' => ['required', 'numeric'],
            'reason' => ['nullable', 'string', 'max:255'],
            'notes' => ['nullable', 'string'],
        ]);

        $data['reviewed_by'] = auth()->id();
        TrustScore::create($data);

        User::where('id', $data['user_id'])->increment('trust_score', (float) $data['score_change']);

        return redirect()->route('admin.trust-scores.index')->with('status', 'Trust score event added.');
    }

    public function show(string $id)
    {
        return redirect()->route('admin.trust-scores.index');
    }

    public function edit(string $id)
    {
        return redirect()->route('admin.trust-scores.index');
    }

    public function update(Request $request, string $id)
    {
        abort(405);
    }

    public function destroy(TrustScore $trustScore)
    {
        $trustScore->delete();

        return redirect()->route('admin.trust-scores.index')->with('status', 'Trust score record deleted.');
    }
}
