<?php

namespace App\Http\Controllers;

use App\Models\AuditLog;
use App\Models\Lead;
use Illuminate\Http\Request;

class ExportController extends Controller
{
    public function leads(Request $request)
    {
        $currentUser = auth()->user();

        $filename = 'highra-leads-' . now()->format('Y-m-d-His') . '.csv';
        $leads = Lead::forUser($currentUser, 'leads')->latest()->get();

        AuditLog::log('leads_exported', 'Leads', "Exported {$leads->count()} leads to CSV", null);

        return response()->streamDownload(function () use ($leads) {
            $out = fopen('php://output', 'w');
            fputcsv($out, ['Lead Code', 'Name', 'Phone', 'Email', 'Source', 'Status', 'Campaign', 'Expected Value', 'Created']);
            foreach ($leads as $lead) {
                fputcsv($out, [
                    $lead->lead_code,
                    $lead->name,
                    $lead->phone,
                    $lead->email,
                    $lead->source,
                    $lead->status,
                    $lead->campaign,
                    $lead->expected_value,
                    optional($lead->created_at)->format('Y-m-d H:i:s'),
                ]);
            }
            fclose($out);
        }, $filename, ['Content-Type' => 'text/csv']);
    }
}
