<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\CrmLead;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

class SupportTicketController extends Controller
{
    public function index(Request $request): View
    {
        $search = trim((string) $request->query('q', ''));
        $status = (string) $request->query('status', 'all');
        if (! in_array($status, ['all', 'new', 'contacted', 'qualified', 'converted', 'closed'], true)) {
            $status = 'all';
        }

        $query = CrmLead::query()
            ->where('source', 'support_ticket');

        if ($status !== 'all') {
            $query->where('status', $status);
        }

        if ($search !== '') {
            $query->where(function ($builder) use ($search): void {
                $builder->where('name', 'like', "%{$search}%")
                    ->orWhere('mobile', 'like', "%{$search}%")
                    ->orWhere('email', 'like', "%{$search}%")
                    ->orWhere('remarks', 'like', "%{$search}%")
                    ->orWhere('meta->ticket_code', 'like', "%{$search}%");
            });
        }

        return view('admin.support', [
            'tickets' => $query->latest('id')->paginate(25)->withQueryString(),
            'search' => $search,
            'status' => $status,
        ]);
    }

    public function update(Request $request, int $ticketId): RedirectResponse
    {
        $validated = $request->validate([
            'status' => ['required', 'in:new,contacted,qualified,converted,closed'],
            'admin_note' => ['nullable', 'string', 'max:1000'],
        ]);

        $ticket = CrmLead::query()
            ->where('id', $ticketId)
            ->where('source', 'support_ticket')
            ->firstOrFail();

        $meta = is_array($ticket->meta) ? $ticket->meta : [];
        if (! empty($validated['admin_note'])) {
            $meta['admin_note'] = $validated['admin_note'];
            $meta['admin_note_updated_at'] = now()->toDateTimeString();
            $meta['admin_note_updated_by'] = auth()->id();
        }

        $ticket->status = $validated['status'];
        $ticket->meta = $meta;
        $ticket->assigned_to = auth()->id();
        $ticket->save();

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