<?php

namespace App\Http\Controllers\Member;

use App\Http\Controllers\Controller;
use App\Models\ReturnRequest;
use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class ReturnController extends Controller
{
    public function index()
    {
        $returns = Auth::user()->returns()
            ->with(['order', 'orderItem'])
            ->latest()
            ->paginate(10);

        return view('member.returns.index', compact('returns'));
    }

    public function create(Order $order)
    {
        if ($order->user_id !== Auth::id()) {
            abort(403);
        }

        $order->load('items');
        return view('member.returns.create', compact('order'));
    }

    public function store(Request $request, Order $order)
    {
        if ($order->user_id !== Auth::id()) {
            abort(403);
        }

        $validated = $request->validate([
            'order_item_id' => ['nullable', 'exists:order_items,id'],
            'type' => ['required', 'in:return,exchange,cancellation'],
            'reason' => ['required', 'string', 'min:10'],
        ]);

        $validated['user_id'] = Auth::id();
        $validated['order_id'] = $order->id;

        ReturnRequest::create($validated);

        return redirect()->route('member.returns.index')->with('success', 'İade talebiniz oluşturuldu. En kısa sürede değerlendirilecektir.');
    }

    public function show(ReturnRequest $return)
    {
        if ($return->user_id !== Auth::id()) {
            abort(403);
        }

        $return->load(['order.items', 'orderItem']);

        return view('member.returns.show', compact('return'));
    }
}
