<?php

namespace App\Http\Controllers;

use App\Mail\ContactTemplateMail;
use App\Models\Contact;
use App\Models\Setting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;

class ContactController extends Controller
{
    public function index(Request $request)
    {
        $intent = trim((string) $request->query('intent', ''));
        $service = trim((string) $request->query('service', ''));
        $package = trim((string) $request->query('package', ''));

        $subject = match ($intent) {
            'free-audit' => 'Request a free tracking audit',
            'pricing' => 'Ask about pricing and packages',
            default => 'Tell us what you need to measure.',
        };

        $intro = match ($intent) {
            'free-audit' => 'Share your website or campaign details and request a free audit. We will review the current setup and highlight the most important tracking gaps first.',
            'pricing' => 'Share the service or package you are interested in and we will confirm fit, scope, and timing.',
            default => "Share your website, campaigns, or reporting challenge and we'll help you figure out the best tracking setup.",
        };

        $message = match ($intent) {
            'free-audit' => trim("Hi Saleem,\n\nI'd like a free audit" . ($service ? " for {$service}" : '') . ".\n\nWebsite / landing page:\nMain tracking issue:\nCurrent platforms:\n"),
            'pricing' => trim("Hi Saleem,\n\nI'm interested in pricing" . ($package ? " for the {$package} package" : '') . ($service ? " related to {$service}" : '') . ".\n\nPlease share scope, timeline, and next steps.\n"),
            default => '',
        };

        $contactContext = [
            'title' => $subject,
            'intro' => $intro,
            'service' => $service,
            'package' => $package,
            'intent' => $intent,
            'message' => $message,
        ];

        return view('frontend.contact', compact('contactContext'));
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|max:255',
            'phone' => 'nullable|string|max:20',
            'message' => 'required|string',
            'source' => 'nullable|string|in:contact_form,support_chat',
            'page_url' => 'nullable|string|max:2048',
        ]);

        $data['status'] = 'new';
        $data['source'] = $data['source'] ?? 'contact_form';

        $contact = Contact::create($data);
        $settings = Setting::query()->first();

        $this->sendNotifications($contact, $settings);

        $redirectTo = url()->previous() ?: route('contact');

        return redirect($redirectTo)
            ->with('success', 'Thank you for your message.')
            ->with('contact_source', $contact->source);
    }

    protected function sendNotifications(Contact $contact, ?Setting $settings): void
    {
        if (! $settings) {
            return;
        }

        $settings->applyMailConfiguration();

        $notificationSent = false;

        $templateData = [
            'name' => $contact->name,
            'email' => $contact->email,
            'phone' => $contact->phone ?: 'Not provided',
            'message' => $contact->message,
            'source' => $contact->source ?: 'contact_form',
            'source_label' => str($contact->source ?: 'contact_form')->replace('_', ' ')->title()->toString(),
            'page_url' => $contact->page_url ?: 'Not provided',
            'site_name' => $settings->site_name ?: config('app.name'),
            'contact_email' => $settings->contact_email ?: config('mail.from.address'),
            'submitted_at' => now()->format('M j, Y g:i A'),
        ];

        try {
            if ($settings->admin_contact_notifications_enabled && filled($settings->contact_email)) {
                Mail::to($settings->contact_email)->send(new ContactTemplateMail(
                    subjectLine: $this->renderTemplate(
                        $settings->admin_contact_subject ?: 'New contact inquiry from {{ name }}',
                        $templateData,
                    ),
                    heading: 'New Contact Inquiry',
                    bodyHtml: $this->renderBody(
                        $settings->admin_contact_template ?: <<<HTML
<p>You received a new contact form submission on {{ site_name }}.</p>
<p><strong>Name:</strong> {{ name }}</p>
<p><strong>Email:</strong> {{ email }}</p>
<p><strong>Phone:</strong> {{ phone }}</p>
<p><strong>Source:</strong> {{ source_label }}</p>
<p><strong>Page URL:</strong> {{ page_url }}</p>
<p><strong>Submitted:</strong> {{ submitted_at }}</p>
<p><strong>Message:</strong></p>
<p>{{ message }}</p>
HTML,
                        $templateData,
                    ),
                ));
                $notificationSent = true;
            }

            if ($settings->user_contact_auto_reply_enabled && filled($contact->email)) {
                Mail::to($contact->email)->send(new ContactTemplateMail(
                    subjectLine: $this->renderTemplate(
                        $settings->user_contact_subject ?: 'We received your message, {{ name }}',
                        $templateData,
                    ),
                    heading: 'Thanks for reaching out',
                    bodyHtml: $this->renderBody(
                        $settings->user_contact_template ?: <<<HTML
<p>Hello {{ name }},</p>
<p>Thank you for contacting {{ site_name }}. Your message has been received and we will review it shortly.</p>
<p><strong>Source:</strong> {{ source_label }}</p>
<p><strong>Your message:</strong></p>
<p>{{ message }}</p>
<p>If you need to add more details, reply to {{ contact_email }}.</p>
HTML,
                        $templateData,
                    ),
                ));
                $notificationSent = true;
            }

            if ($notificationSent) {
                $contact->forceFill([
                    'notified_at' => now(),
                ])->save();
            }
        } catch (\Throwable $exception) {
            Log::warning('Contact form email delivery failed.', [
                'contact_id' => $contact->id,
                'message' => $exception->getMessage(),
            ]);
        }
    }

    protected function renderTemplate(string $template, array $data): string
    {
        return preg_replace_callback('/{{\s*([a-z0-9_]+)\s*}}/i', function (array $matches) use ($data): string {
            $key = strtolower((string) ($matches[1] ?? ''));

            return (string) ($data[$key] ?? '');
        }, $template) ?: $template;
    }

    protected function renderBody(string $template, array $data): string
    {
        $rendered = preg_replace_callback('/{{\s*([a-z0-9_]+)\s*}}/i', function (array $matches) use ($data): string {
            $key = strtolower((string) ($matches[1] ?? ''));

            return e((string) ($data[$key] ?? ''));
        }, $template) ?: $template;

        if (! str_contains($rendered, '<')) {
            return nl2br($rendered);
        }

        return nl2br($rendered);
    }
}
