<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\HomepageLead;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\StreamedResponse;

class HomepageLeadsController extends Controller
{
    public function index(Request $request)
    {
        $status = $request->string('status')->toString();
        $search = $request->string('q')->toString();

        $query = HomepageLead::query()
            ->search($search ?: null)
            ->when($status !== '' && in_array($status, HomepageLead::STATUSES, true), fn ($q) => $q->status($status))
            ->orderByDesc('last_message_at')
            ->orderByDesc('created_at');

        $leads = $query->paginate(20)->withQueryString();

        $counts = HomepageLead::query()
            ->selectRaw('status, COUNT(*) as total')
            ->groupBy('status')
            ->pluck('total', 'status')
            ->toArray();

        return view('admin.homepage-leads.index', [
            'leads'  => $leads,
            'status' => $status,
            'search' => $search,
            'counts' => array_merge(array_fill_keys(HomepageLead::STATUSES, 0), $counts),
            'total'  => array_sum($counts),
        ]);
    }

    public function show(HomepageLead $lead)
    {
        return view('admin.homepage-leads.show', [
            'lead' => $lead,
        ]);
    }

    public function updateStatus(Request $request, HomepageLead $lead)
    {
        $data = $request->validate([
            'status' => ['required', 'string', 'in:'.implode(',', HomepageLead::STATUSES)],
        ]);

        $lead->update(['status' => $data['status']]);

        return back()->with('success', __('Lead status updated.'));
    }

    public function updateNotes(Request $request, HomepageLead $lead)
    {
        $data = $request->validate([
            'admin_notes' => ['nullable', 'string', 'max:5000'],
        ]);

        $lead->update(['admin_notes' => $data['admin_notes'] ?? null]);

        return back()->with('success', __('Notes saved.'));
    }

    public function destroy(HomepageLead $lead)
    {
        $lead->delete();
        return redirect()->route('admin.homepage-leads.index')->with('success', __('Lead deleted.'));
    }

    public function export(Request $request): StreamedResponse
    {
        $filename = 'homepage-leads-'.now()->format('Y-m-d_His').'.csv';

        return response()->streamDownload(function () {
            $out = fopen('php://output', 'w');
            fputcsv($out, [
                'ID', 'Created', 'Name', 'Email', 'Company', 'Use case',
                'Status', 'Messages', 'AI Provider', 'AI Model', 'AI Cost', 'Page URL',
            ]);

            HomepageLead::query()->orderBy('id')->chunk(200, function ($rows) use ($out) {
                foreach ($rows as $r) {
                    fputcsv($out, [
                        $r->id,
                        $r->created_at?->toDateTimeString(),
                        $r->name,
                        $r->email,
                        $r->company,
                        $r->use_case,
                        $r->status,
                        $r->message_count,
                        $r->ai_provider,
                        $r->ai_model,
                        number_format((float) $r->ai_total_cost, 6),
                        $r->page_url,
                    ]);
                }
            });

            fclose($out);
        }, $filename, [
            'Content-Type' => 'text/csv',
        ]);
    }
}
