<?php

namespace App\Http\Controllers;

use App\Models\Complaint;
use App\Models\Parcel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class ComplaintController extends Controller
{
    /**
     * Display a listing of complaints.
     */
    public function index()
    {
        $query = Complaint::with(['parcel', 'seller']);

        // Filter by seller if not admin
        // Use canonical Spatie role names
        if (!Auth::user()->hasAnyRole(['Admin', 'Super Admin', 'Support'])) {
            $query->where('seller_id', Auth::id());
        }

        $complaints = $query->latest()->paginate(20);

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

    /**
     * Show the form for creating a new complaint.
     */
    public function create()
    {
        $parcels = Parcel::where('seller_id', Auth::id())->get();
        return view('complaints.create', compact('parcels'));
    }

    /**
     * Store a newly created complaint in storage.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'parcel_id' => 'required|exists:parcels,id',
            'subject' => 'required|string|min:5',
            'description' => 'required|string|min:20',
        ]);

        $validated['seller_id'] = Auth::id();
        $validated['status'] = 'Open';

        $complaint = Complaint::create($validated);

        return redirect()->route('complaints.show', $complaint)
            ->with('success', 'Complaint submitted successfully!');
    }

    /**
     * Display the specified complaint.
     */
    public function show(Complaint $complaint)
    {
        // Check authorization
        if (!Auth::user()->hasAnyRole(['Admin', 'Super Admin', 'Support']) 
            && $complaint->seller_id !== Auth::id()) {
            abort(403);
        }

        $complaint->load(['parcel', 'seller']);

        return view('complaints.show', compact('complaint'));
    }

    /**
     * Update the complaint status (admin only).
     */
    public function update(Request $request, Complaint $complaint)
    {
        if (!Auth::user()->hasAnyRole(['admin', 'super-admin', 'support'])) {
            abort(403);
        }

        $validated = $request->validate([
            'status' => 'required|in:Open,In Progress,Resolved,Closed',
        ]);

        $complaint->update($validated);

        return back()->with('success', 'Complaint status updated successfully!');
    }
}
