<?php

namespace App\Http\Controllers;

use App\Models\Dispute;
use App\Models\Order;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class DisputeController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index()
    {
        $user = auth()->user();
        
        if ($user->hasRole('verifier')) {
            $disputes = Dispute::where('assigned_to', $user->id)
                ->orderByDesc('deadline_at')
                ->paginate(15);
        } else {
            $disputes = Dispute::where(function ($q) use ($user) {
                $q->where('initiator_id', $user->id)
                  ->orWhere('respondent_id', $user->id);
            })
            ->orderByDesc('created_at')
            ->paginate(15);
        }

        return view('disputes.index', compact('disputes'));
    }

    public function create(Order $order)
    {
        $user = auth()->user();

        if ($order->user_id !== $user->id && $order->seller->user_id !== $user->id) {
            abort(403);
        }

        return view('disputes.create', compact('order'));
    }

    public function store(Request $request, Order $order)
    {
        $user = auth()->user();

        if ($order->user_id !== $user->id && $order->seller->user_id !== $user->id) {
            abort(403);
        }

        $validated = $request->validate([
            'type' => 'required|in:quality,non_delivery,payment_issue,fraud,other',
            'description' => 'required|string|min:20',
        ]);

        DB::beginTransaction();
        try {
            $respondent = $order->user_id === $user->id ? $order->seller : $order->user;

            $dispute = Dispute::create([
                'order_id' => $order->id,
                'initiator_id' => $user->id,
                'respondent_id' => $respondent->id,
                'type' => $validated['type'],
                'description' => $validated['description'],
                'status' => 'open',
                'opened_at' => now(),
                'deadline_at' => now()->addDays(7),
            ]);

            Log::info("Dispute #{$dispute->id} créé par {$user->name}");

            DB::commit();
            return redirect()->route('disputes.show', $dispute)->with('success', 'Litige créé.');

        } catch (\Exception $e) {
            DB::rollBack();
            Log::error("Erreur création litige: " . $e->getMessage());
            return redirect()->back()->with('error', 'Erreur.');
        }
    }

    public function show(Dispute $dispute)
    {
        $user = auth()->user();

        if (!$this->canAccess($dispute, $user)) {
            abort(403);
        }

        return view('disputes.show', compact('dispute'));
    }

    public function update(Request $request, Dispute $dispute)
    {
        if (!auth()->user()->hasRole('verifier') || $dispute->assigned_to !== auth()->id()) {
            abort(403);
        }

        $validated = $request->validate([
            'status' => 'required|in:open,in_review,resolved,escalated',
            'notes' => 'nullable|string',
        ]);

        $dispute->update([
            'status' => $validated['status'],
            'notes' => $validated['notes'] ?? $dispute->notes,
        ]);

        if ($validated['status'] === 'in_review') {
            $dispute->update(['status' => 'in_review']);
        }

        return redirect()->back()->with('success', 'Litige mis à jour.');
    }

    public function resolve(Request $request, Dispute $dispute)
    {
        if (!auth()->user()->hasRole('verifier') || $dispute->assigned_to !== auth()->id()) {
            abort(403);
        }

        $validated = $request->validate([
            'decision' => 'required|in:in_favor_of_buyer,in_favor_of_seller,partial_refund',
            'refund_amount' => 'nullable|numeric|min:0',
            'resolution' => 'required|string|min:20',
        ]);

        DB::beginTransaction();
        try {
            $dispute->update([
                'status' => 'resolved',
                'decision' => $validated['decision'],
                'refund_amount' => $validated['refund_amount'],
                'resolution' => $validated['resolution'],
                'resolved_by' => auth()->id(),
                'resolved_at' => now(),
            ]);

            // Traiter remboursement si applicable
            if ($validated['decision'] === 'in_favor_of_buyer' && $dispute->refund_amount) {
                $buyer = $dispute->initiator_id === $dispute->order->user_id ? 
                    $dispute->order->user : $dispute->order->seller;
                
                $buyer->wallet->increment('balance', $dispute->refund_amount);
            }

            Log::info("Litige #{$dispute->id} résolu par " . auth()->user()->name);

            DB::commit();
            return redirect()->route('disputes.show', $dispute)->with('success', 'Litige résolu.');

        } catch (\Exception $e) {
            DB::rollBack();
            Log::error("Erreur résolution litige: " . $e->getMessage());
            return redirect()->back()->with('error', 'Erreur.');
        }
    }

    public function escalate(Dispute $dispute)
    {
        if (!auth()->user()->hasRole('verifier') || $dispute->assigned_to !== auth()->id()) {
            abort(403);
        }

        if (now() > $dispute->deadline_at && !$dispute->sla_breached) {
            $dispute->update([
                'sla_breached' => true,
                'escalation_triggered_at' => now(),
                'status' => 'escalated',
            ]);
        }

        return redirect()->back()->with('success', 'Litige escaladé.');
    }

    private function canAccess(Dispute $dispute, User $user)
    {
        if ($user->id === $dispute->initiator_id || $user->id === $dispute->respondent_id) {
            return true;
        }

        if ($user->hasRole('verifier')) {
            return true;
        }

        return false;
    }
}
