<?php

namespace App\Http\Controllers;

use App\Models\ContactList;
use Illuminate\Http\Request;
use Inertia\Inertia;

class ListController extends Controller
{
    public function index()
    {
        $lists = ContactList::when(request('search'), fn($q, $s) => $q->where('title', 'like', "%{$s}%"))
            ->latest()
            ->orderByDesc('id')
            ->paginate(10)
            ->withQueryString();

        return Inertia::render('Audience/Lists', [
            'lists' => $lists,
        ]);
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'title'       => 'required|string|max:255',
            'slug'        => 'required|string|max:255|unique:lists,slug',
            'description' => 'nullable|string',
            'color'       => 'nullable|string|max:20',
        ]);

        $list = ContactList::create($validated);

        if ($request->wantsJson()) {
            return response()->json(['success' => true, 'list' => $list]);
        }

        return redirect()->route('lists.index')->with('success', 'List created successfully.');
    }

    public function update(Request $request, ContactList $list)
    {
        $validated = $request->validate([
            'title'       => 'required|string|max:255',
            'slug'        => 'required|string|max:255|unique:lists,slug,' . $list->id,
            'description' => 'nullable|string',
            'color'       => 'nullable|string|max:20',
        ]);

        $list->update($validated);

        return redirect()->route('lists.index')->with('success', 'List updated successfully.');
    }

    public function destroy(ContactList $list)
    {
        $list->delete();

        return redirect()->route('lists.index')->with('success', 'List deleted successfully.');
    }

    public function bulkDestroy(Request $request)
    {
        $ids = $request->validate([
            'ids' => 'required|array',
            'ids.*' => 'exists:lists,id'
        ])['ids'];

        ContactList::whereIn('id', $ids)->delete();

        return redirect()->route('lists.index')->with('success', 'Selected lists deleted.');
    }
}
