<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Enquiry;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class AdminEnquiryController extends Controller
{
    public function index(Request $request)
    {
        $status = $request->query('status');
        $type = $request->query('type');

        $enquiries = Enquiry::query()
            ->when($status, fn ($q) => $q->where('status', $status))
            ->when($type, fn ($q) => $q->where('type', $type))
            ->latest()
            ->paginate(20)
            ->withQueryString();

        return view('admin.enquiries.index', [
            'enquiries'    => $enquiries,
            'activeStatus' => $status,
            'activeType'   => $type,
            'counts'       => [
                'all'         => Enquiry::count(),
                'new'         => Enquiry::where('status', 'new')->count(),
                'in_progress' => Enquiry::where('status', 'in_progress')->count(),
                'closed'      => Enquiry::where('status', 'closed')->count(),
            ],
        ]);
    }

    public function show(Enquiry $enquiry)
    {
        // Mark new enquiries as in-progress when first opened.
        if ($enquiry->status === 'new') {
            $enquiry->update(['status' => 'in_progress']);
        }

        return view('admin.enquiries.show', ['enquiry' => $enquiry]);
    }

    public function update(Request $request, Enquiry $enquiry)
    {
        $data = $request->validate([
            'status' => ['required', Rule::in(['new', 'in_progress', 'closed'])],
        ]);
        $enquiry->update($data);

        return back()->with('status', 'Enquiry status updated.');
    }

    public function destroy(Enquiry $enquiry)
    {
        $enquiry->delete();

        return redirect()->route('admin.enquiries.index')->with('status', 'Enquiry deleted.');
    }
}
