<?php

namespace App\Http\Controllers\Frontend;

use App\Http\Controllers\Controller;
use App\Models\Anime;
use App\Models\Tribunal;
use App\Models\TribunalArgument;
use App\Models\TribunalArgumentVote;
use App\Models\TribunalVote;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class TribunalController extends Controller
{
    public function index()
    {
        $tribunals = Tribunal::with(['anime', 'creator'])
            ->withCount('votes')
            ->latest()
            ->paginate(15);

        return view('frontend.tribunal.index', compact('tribunals'));
    }

    public function show(Tribunal $tribunal)
    {
        $tribunal->load(['anime', 'episode', 'creator']);

        $me = Auth::id();

        $myVote = $me
            ? TribunalVote::where('tribunal_id', $tribunal->id)->where('user_id', $me)->value('side')
            : null;

        $myArgument = $me
            ? TribunalArgument::where('tribunal_id', $tribunal->id)->where('user_id', $me)->first()
            : null;

        // Tüm tarafların oy sayımları
        $allSides = $tribunal->allSides();
        $voteCounts = [];
        $total = 0;
        foreach (array_keys($allSides) as $key) {
            $cnt = TribunalVote::where('tribunal_id', $tribunal->id)->where('side', $key)->count();
            $voteCounts[$key] = $cnt;
            $total += $cnt;
        }

        $arguments = TribunalArgument::with('user:id,name,username')
            ->where('tribunal_id', $tribunal->id)
            ->orderByDesc('vote_count')
            ->get()
            ->map(function ($arg) use ($me) {
                $voted = $me
                    ? TribunalArgumentVote::where('argument_id', $arg->id)->where('user_id', $me)->exists()
                    : false;
                return [
                    'id'         => $arg->id,
                    'side'       => $arg->side,
                    'body'       => $arg->body,
                    'vote_count' => $arg->vote_count,
                    'username'   => $arg->user?->username,
                    'name'       => $arg->user?->name,
                    'is_mine'    => $me && $arg->user_id === $me,
                    'voted'      => $voted,
                    'created_at' => $arg->created_at->diffForHumans(),
                ];
            });

        return view('frontend.tribunal.show', compact(
            'tribunal', 'myVote', 'myArgument', 'allSides', 'voteCounts', 'total', 'arguments'
        ));
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'anime_id'    => 'required|exists:animes,id',
            'episode_id'  => 'nullable|exists:episodes,id',
            'question'    => 'required|string|min:10|max:280',
            'side_a'      => 'required|string|min:2|max:100',
            'side_b'      => 'required|string|min:2|max:100',
            'extra_sides' => 'nullable|array|max:4',
            'extra_sides.*' => 'required|string|min:2|max:100',
            'closes_at'   => 'nullable|date|after:now',
        ]);

        $data['created_by']  = Auth::id();
        $data['closes_at']   = $data['closes_at'] ?? now()->addDays(7);
        $data['extra_sides'] = array_values(array_filter($data['extra_sides'] ?? []));

        $tribunal = Tribunal::create($data);

        return response()->json([
            'ok'  => true,
            'url' => route('tribunal.show', $tribunal),
        ]);
    }

    public function vote(Request $request, Tribunal $tribunal)
    {
        if ($tribunal->status === 'closed') {
            return response()->json(['error' => 'Bu dava kapandı.'], 422);
        }

        $validSides = array_keys($tribunal->allSides());
        $data = $request->validate(['side' => 'required|in:' . implode(',', $validSides)]);
        $me   = Auth::id();

        $existing = TribunalVote::where('tribunal_id', $tribunal->id)
            ->where('user_id', $me)
            ->first();

        if ($existing) {
            if ($existing->side === $data['side']) {
                $existing->delete();
                $voted = null;
            } else {
                $existing->update(['side' => $data['side']]);
                $voted = $data['side'];
            }
        } else {
            TribunalVote::create([
                'tribunal_id' => $tribunal->id,
                'user_id'     => $me,
                'side'        => $data['side'],
                'created_at'  => now(),
            ]);
            $voted = $data['side'];
        }

        $counts = [];
        foreach (array_keys($tribunal->allSides()) as $key) {
            $counts[$key] = TribunalVote::where('tribunal_id', $tribunal->id)->where('side', $key)->count();
        }

        return response()->json([
            'voted'  => $voted,
            'counts' => $counts,
            'total'  => array_sum($counts),
        ]);
    }

    public function argue(Request $request, Tribunal $tribunal)
    {
        if ($tribunal->status === 'closed') {
            return response()->json(['error' => 'Bu dava kapandı.'], 422);
        }

        $validSides = array_keys($tribunal->allSides());
        $data = $request->validate([
            'side' => 'required|in:' . implode(',', $validSides),
            'body' => 'required|string|min:10|max:500',
        ]);

        $me = Auth::id();

        $existing = TribunalArgument::where('tribunal_id', $tribunal->id)
            ->where('user_id', $me)
            ->first();

        if ($existing) {
            return response()->json(['error' => 'Bu dava için zaten bir argüman girdiniz.'], 422);
        }

        $arg = TribunalArgument::create([
            'tribunal_id' => $tribunal->id,
            'user_id'     => $me,
            'side'        => $data['side'],
            'body'        => $data['body'],
        ]);

        return response()->json(['ok' => true, 'id' => $arg->id]);
    }

    public function argVote(Request $request, TribunalArgument $argument)
    {
        $me = Auth::id();

        $existing = TribunalArgumentVote::where('argument_id', $argument->id)
            ->where('user_id', $me)
            ->first();

        if ($existing) {
            $existing->delete();
            $argument->decrement('vote_count');
            return response()->json(['voted' => false, 'vote_count' => $argument->fresh()->vote_count]);
        }

        TribunalArgumentVote::create([
            'argument_id' => $argument->id,
            'user_id'     => $me,
            'created_at'  => now(),
        ]);
        $argument->increment('vote_count');

        return response()->json(['voted' => true, 'vote_count' => $argument->fresh()->vote_count]);
    }

    public function forAnime(Anime $anime)
    {
        $tribunals = Tribunal::where('anime_id', $anime->id)
            ->withCount('votes')
            ->latest()
            ->get()
            ->map(fn($t) => [
                'id'       => $t->id,
                'question' => $t->question,
                'side_a'   => $t->side_a,
                'side_b'   => $t->side_b,
                'status'   => $t->status,
                'url'      => route('tribunal.show', $t),
                'votes'    => $t->votes_count,
            ]);

        return response()->json(['tribunals' => $tribunals]);
    }
}
