<?php

namespace App\Http\Controllers;

use App\Models\Lead;
use App\Models\Website;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Carbon\Carbon;

class LeadController extends Controller
{
    public function dashboard(Request $request)
    {
        $websites = Website::orderBy('name')->get();

        $query = Lead::query();

        // Filters
        $query = $this->applyFilters($query, $request);

        $totalLeads = (clone $query)->count();

        // Website-wise counts based on filtered query
        $websiteCounts = (clone $query)
            ->selectRaw('website_id, COUNT(*) as total')
            ->groupBy('website_id')
            ->pluck('total', 'website_id');

        return view('dashboard', [
            'websites' => $websites,
            'totalLeads' => $totalLeads,
            'websiteCounts' => $websiteCounts,
            'filters' => $request->all(),
        ]);
    }

    public function index(Request $request)
    {
        $websites = Website::orderBy('name')->get();

        $query = Lead::with('website')->latest();
        $query = $this->applyFilters($query, $request);

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

        return view('leads.index', [
            'websites' => $websites,
            'leads' => $leads,
            'filters' => $request->all(),
        ]);
    }

    public function exportCsv(Request $request): StreamedResponse
    {
        $query = Lead::with('website')->latest();
        $query = $this->applyFilters($query, $request);

        $filename = 'leads_' . now()->format('Ymd_His') . '.csv';

        return response()->streamDownload(function () use ($query) {
            $out = fopen('php://output', 'w');

            // CSV Header
            fputcsv($out, [
                'ID', 'Website', 'Name', 'Email', 'Phone',
                'Form', 'Page URL', 'Created At', 'Payload(JSON)'
            ]);

            $query->chunk(500, function ($rows) use ($out) {
                foreach ($rows as $lead) {
                    fputcsv($out, [
                        $lead->id,
                        optional($lead->website)->name,
                        $lead->name,
                        $lead->email,
                        $lead->phone,
                        $lead->source_form,
                        $lead->page_url,
                        $lead->created_at?->format('Y-m-d H:i:s'),
                        json_encode($lead->payload ?? [], JSON_UNESCAPED_UNICODE),
                    ]);
                }
            });

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

    private function applyFilters($query, Request $request)
    {
        // website filter (by key or id)
        if ($request->filled('website')) {
            $website = Website::where('key', $request->website)
                ->orWhere('id', $request->website)
                ->first();

            if ($website) {
                $query->where('website_id', $website->id);
            }
        }

        // month wise filter: YYYY-MM
        if ($request->filled('month')) {
            try {
                $start = Carbon::createFromFormat('Y-m', $request->month)->startOfMonth();
                $end   = (clone $start)->endOfMonth();
                $query->whereBetween('created_at', [$start, $end]);
            } catch (\Throwable $e) {
                // ignore invalid month
            }
        }

        // start/end date filter: YYYY-MM-DD
        if ($request->filled('start_date')) {
            try {
                $startDate = Carbon::createFromFormat('Y-m-d', $request->start_date)->startOfDay();
                $query->where('created_at', '>=', $startDate);
            } catch (\Throwable $e) {}
        }

        if ($request->filled('end_date')) {
            try {
                $endDate = Carbon::createFromFormat('Y-m-d', $request->end_date)->endOfDay();
                $query->where('created_at', '<=', $endDate);
            } catch (\Throwable $e) {}
        }

        return $query;
    }
    public function website(Request $request, string $websiteKey)
{
    $websites = \App\Models\Website::orderBy('name')->get();
    $site = \App\Models\Website::where('key', $websiteKey)->firstOrFail();

    $query = \App\Models\Lead::with('website')->latest()
        ->where('website_id', $site->id);

    $query = $this->applyFilters($query, $request);

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

    return view('leads.index', [
        'pageTitle' => $site->name . ' Leads',
        'websites'  => $websites,
        'leads'     => $leads,
        'filters'   => array_merge($request->all(), ['website' => $websiteKey]),
    ]);
}

}
