<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\ContactSubmission;
use App\Models\Lead;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ContactSubmissionController extends Controller
{
    public function index(Request $request)
    {
        $query = ContactSubmission::query()
            ->with('lead')
            ->when($request->search, function ($q) use ($request) {
                $search = (string) $request->search;
                $q->where(function ($q2) use ($search) {
                    $q2->where('name', 'like', "%{$search}%")
                        ->orWhere('phone', 'like', "%{$search}%")
                        ->orWhere('email', 'like', "%{$search}%");
                });
            })
            ->when($request->status, fn ($q) => $q->where('status', $request->status))
            ->latest();

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

        $stats = [
            'total' => ContactSubmission::count(),
            'new' => ContactSubmission::where('status', 'new')->count(),
            'contacted' => ContactSubmission::where('status', 'contacted')->count(),
            'closed' => ContactSubmission::where('status', 'closed')->count(),
            'converted' => ContactSubmission::whereNotNull('lead_id')->count(),
            'today' => ContactSubmission::whereDate('created_at', today())->count(),
        ];

        return view('admin.contact-submissions.index', compact('submissions', 'stats'));
    }

    public function show(ContactSubmission $contactSubmission)
    {
        $contactSubmission->load('lead');

        return view('admin.contact-submissions.show', compact('contactSubmission'));
    }

    public function update(Request $request, ContactSubmission $contactSubmission)
    {
        $data = $request->validate([
            'status' => 'required|in:new,contacted,closed',
        ]);

        $contactSubmission->update($data);

        return back()->with('success', 'Contact request updated.');
    }

    public function destroy(ContactSubmission $contactSubmission)
    {
        $contactSubmission->delete();

        return redirect()
            ->route('admin.contact-submissions.index')
            ->with('success', 'Contact request deleted.');
    }

    public function convertToLead(ContactSubmission $contactSubmission)
    {
        if ($contactSubmission->lead_id) {
            return redirect()
                ->route('admin.leads.show', $contactSubmission->lead_id)
                ->with('success', 'This contact request is already converted to a lead.');
        }

        $phone = $this->normalizePhone((string) $contactSubmission->phone);
        if ($phone === null) {
            return back()->with('error', 'Could not convert: invalid phone number.');
        }

        $existingLead = Lead::query()
            ->where('phone', $phone)
            ->whereIn('status', ['new', 'contacted', 'enrolled'])
            ->first();

        if ($existingLead) {
            $contactSubmission->update([
                'lead_id' => $existingLead->id,
                'converted_at' => now(),
            ]);

            return redirect()
                ->route('admin.leads.show', $existingLead)
                ->with('success', 'Existing lead found. Linked this contact request to that lead.');
        }

        $lead = DB::transaction(function () use ($contactSubmission, $phone) {
            $notes = $this->buildLeadNotes($contactSubmission);

            $lead = Lead::create([
                'phone' => $phone,
                'name' => $contactSubmission->name,
                'email' => $contactSubmission->email,
                'country_id' => $contactSubmission->country_id,
                'country_name' => $contactSubmission->country_name,
                'otp' => null,
                'otp_verified_at' => now(),
                'source' => 'contact_submission',
                'utm_source' => $contactSubmission->utm_source,
                'utm_medium' => $contactSubmission->utm_medium,
                'utm_campaign' => $contactSubmission->utm_campaign,
                'utm_content' => $contactSubmission->utm_content,
                'utm_term' => $contactSubmission->utm_term,
                'fbclid' => $contactSubmission->fbclid,
                'gclid' => $contactSubmission->gclid,
                'page_url' => $contactSubmission->page_url,
                'referrer_url' => $contactSubmission->referrer_url,
                'landing_page' => $contactSubmission->landing_page,
                'ip_address' => $contactSubmission->ip_address,
                'status' => 'new',
                'notes' => $notes,
            ]);

            $contactSubmission->update([
                'lead_id' => $lead->id,
                'converted_at' => now(),
                'status' => 'closed',
            ]);

            return $lead;
        });

        return redirect()
            ->route('admin.leads.show', $lead)
            ->with('success', 'Contact request converted to lead successfully.');
    }

    private function normalizePhone(string $phone): ?string
    {
        $raw = trim($phone);
        if ($raw === '') {
            return null;
        }

        $compact = preg_replace('/[^\d\+]/', '', $raw) ?? '';
        if (str_starts_with($compact, '00')) {
            $compact = '+' . substr($compact, 2);
        }

        if (preg_match('/^\+\d{8,15}$/', $compact)) {
            return $compact;
        }

        if (preg_match('/^8801\d{9}$/', $compact)) {
            return '+' . $compact;
        }

        if (preg_match('/^01\d{9}$/', $compact)) {
            return '+88' . $compact;
        }

        if (preg_match('/^1\d{9}$/', $compact)) {
            return '+880' . $compact;
        }

        return null;
    }

    private function buildLeadNotes(ContactSubmission $contactSubmission): string
    {
        $lines = [
            'Converted from Contact Request #' . $contactSubmission->id,
            'Study level: ' . str_replace('_', ' ', ucfirst((string) $contactSubmission->study_level)),
            'Consultation mode: ' . str_replace('_', ' ', ucfirst((string) $contactSubmission->consultation_mode)),
        ];

        if (! empty($contactSubmission->second_country_name)) {
            $lines[] = 'Second country: ' . $contactSubmission->second_country_name;
        }

        if (! empty($contactSubmission->message)) {
            $lines[] = 'Message: ' . $contactSubmission->message;
        }

        return implode("\n", $lines);
    }
}
