<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Reader;
use App\Models\Category;
use Illuminate\Http\Request;

class ReaderController extends Controller
{
    public function index(Request $request)
    {
        $query = Reader::query();

        if ($request->filled('search')) {
            $query->where(function($q) use ($request) {
                $q->where('name', 'like', '%' . $request->search . '%')
                  ->orWhere('whatsapp_number', 'like', '%' . $request->search . '%');
            });
        }

        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        $readers = $query->orderBy('created_at', 'desc')->paginate(20);
        $categories = Category::where('active', true)->orderBy('name')->get();

        return view('admin.readers.index', compact('readers', 'categories'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'whatsapp_number' => 'required|string|max:20',
            'categories_interest' => 'nullable|array',
            'receive_group' => 'boolean',
            'receive_private' => 'boolean',
            'city' => 'nullable|string',
            'state' => 'nullable|string|max:2',
        ]);

        // Limpar número (apenas números)
        $validated['whatsapp_number'] = preg_replace('/[^0-9]/', '', $validated['whatsapp_number']);

        Reader::create($validated);

        return redirect()->route('admin.readers.index')
            ->with('success', 'Leitor cadastrado com sucesso!');
    }

    public function update(Request $request, Reader $reader)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'whatsapp_number' => 'required|string|max:20',
            'categories_interest' => 'nullable|array',
            'receive_group' => 'boolean',
            'receive_private' => 'boolean',
            'status' => 'required|in:active,inactive,blocked',
        ]);

        $validated['whatsapp_number'] = preg_replace('/[^0-9]/', '', $validated['whatsapp_number']);

        $reader->update($validated);

        return redirect()->route('admin.readers.index')
            ->with('success', 'Leitor atualizado com sucesso!');
    }

    public function destroy(Reader $reader)
    {
        $reader->delete();
        return redirect()->route('admin.readers.index')
            ->with('success', 'Leitor excluído com sucesso!');
    }
}

