<?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();
        $activeTab = $request->query('tab', 'overview');

        $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(),
            'activeTab' => in_array($activeTab, ['overview', 'tokens'], true) ? $activeTab : 'overview',
        ]);
    }

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

        $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(),
            'statuses' => $statuses,
        ]);
    }

    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',
                'Status', '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->status,
                        $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);
            }
        }

        if ($request->filled('status') && array_key_exists($request->status, Lead::statuses())) {
            $query->where('status', $request->status);
        }

        // 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 updateStatus(Request $request, Lead $lead)
    {
        $validated = $request->validate([
            'status' => ['required', 'string', 'in:'.implode(',', array_keys(Lead::statuses()))],
        ]);

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

        if ($request->expectsJson()) {
            return response()->json([
                'ok' => true,
                'message' => 'Lead status updated.',
                'lead' => [
                    'id' => $lead->id,
                    'status' => $lead->status,
                    'status_label' => Lead::statuses()[$lead->status] ?? $lead->status,
                ],
            ]);
        }

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

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

    $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,
        'statuses'  => $statuses,
        'filters'   => array_merge($request->all(), ['website' => $websiteKey]),
    ]);
}

}
