<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\CardRequest;
use Illuminate\Http\Request;

class CardRequestAdminController extends Controller
{
    public function index()
    {
        $requests = CardRequest::with('store')
            ->orderByRaw("FIELD(status, 'pending', 'contacted', 'collected', 'cancelled') ASC")
            ->orderBy('created_at', 'desc')
            ->paginate(20);

        return view('admin.card-requests.index', compact('requests'));
    }

    public function show(CardRequest $cardRequest)
    {
        $cardRequest->load('store');
        return view('admin.card-requests.show', compact('cardRequest'));
    }

    public function update(Request $request, CardRequest $cardRequest)
    {
        $data = $request->validate([
            'admin_notes' => 'nullable|string|max:5000',
            'status'      => 'required|in:pending,contacted,collected,cancelled',
        ]);

        if (!empty($data['admin_notes'])) {
            $data['replied_at'] = now();
        }

        $cardRequest->update($data);

        return redirect()
            ->route('admin.card-requests.show', $cardRequest)
            ->with('success', 'Pedido actualizado com sucesso.');
    }

    public function destroy(CardRequest $cardRequest)
    {
        $cardRequest->delete();

        return redirect()
            ->route('admin.card-requests.index')
            ->with('success', 'Pedido removido.');
    }
}