<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Waitlist;
use Illuminate\Http\Response;
use Illuminate\View\View;

class WaitlistController extends Controller
{
    public function index(): View
    {
        $waitlists = Waitlist::query()->latest()->paginate(20);

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

    public function export(): Response
    {
        $rows = Waitlist::query()->latest()->get();
        $csv = fopen('php://temp', 'r+');

        fputcsv($csv, ['Name', 'Email', 'WhatsApp', 'Source', 'Joined At']);

        foreach ($rows as $row) {
            fputcsv($csv, [
                $this->safeCsvCell($row->name),
                $this->safeCsvCell($row->email),
                $this->safeCsvCell($row->whatsapp),
                $this->safeCsvCell($row->source),
                $row->created_at?->toDateTimeString(),
            ]);
        }

        rewind($csv);
        $content = stream_get_contents($csv);
        fclose($csv);

        return response($content, 200, [
            'Content-Type' => 'text/csv',
            'Content-Disposition' => 'attachment; filename="vizutrade-waitlist.csv"',
        ]);
    }

    private function safeCsvCell(?string $value): string
    {
        $value = (string) $value;

        return preg_match('/^[=+\-@\t\r]/', $value) === 1 ? "'".$value : $value;
    }
}
