<?php

namespace App\Http\Controllers;

use App\Models\Setting;
use App\Models\User;
use App\Notifications\ContactFormSubmission;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Notification;
use Inertia\Inertia;
use Inertia\Response;

class ContactController extends Controller
{
    /**
     * Display the contact page.
     */
    public function index(): Response
    {
        return Inertia::render('Contact', [
            'contactEmail' => Setting::get('contact_email', 'soporte@coachpro.com'),
            'contactPhone' => Setting::get('contact_phone', '+1 (809) 555-0123'),
            'businessHours' => Setting::get('business_hours', 'Lunes a Viernes: 9:00 AM - 6:00 PM'),
            'address' => Setting::get('contact_address', ''),
            'siteName' => Setting::get('site_name', 'CoachPro'),
            'socialLinks' => $this->getSocialLinks(),
            'systemLogo' => Setting::get('logo'),
        ]);
    }

    /**
     * Handle contact form submission.
     */
    public function submit(Request $request): RedirectResponse
    {
        $validated = $request->validate([
            'name' => 'required|string|max:100',
            'email' => 'required|email|max:255',
            'phone' => 'nullable|string|max:20',
            'subject' => 'required|string|max:200',
            'message' => 'required|string|min:10|max:2000',
            'type' => 'required|in:general,support,sales,other',
        ], [
            'name.required' => 'El nombre es obligatorio.',
            'name.max' => 'El nombre no puede exceder 100 caracteres.',
            'email.required' => 'El correo electrónico es obligatorio.',
            'email.email' => 'Ingresa un correo electrónico válido.',
            'subject.required' => 'El asunto es obligatorio.',
            'subject.max' => 'El asunto no puede exceder 200 caracteres.',
            'message.required' => 'El mensaje es obligatorio.',
            'message.min' => 'El mensaje debe tener al menos 10 caracteres.',
            'message.max' => 'El mensaje no puede exceder 2000 caracteres.',
            'type.required' => 'Selecciona un tipo de consulta.',
            'type.in' => 'Tipo de consulta no válido.',
        ]);

        // Get system email (primary recipient for contact form)
        $systemEmail = Setting::get('system_email', env('MAIL_FROM_ADDRESS', 'soporte@coachpro.com'));
        
        // Send notification to system email using on-demand notification
        try {
            Notification::route('mail', $systemEmail)
                ->notify(new ContactFormSubmission($validated));
        } catch (\Exception $e) {
            \Log::error('Error sending contact form to system email: ' . $e->getMessage());
        }
        
        // Also notify first admin user for in-app notifications
        $admin = User::where('role', 'admin')->first();
        if ($admin && $admin->email !== $systemEmail) {
            try {
                $admin->notify(new ContactFormSubmission($validated));
            } catch (\Exception $e) {
                \Log::error('Error sending contact form notification to admin: ' . $e->getMessage());
            }
        }

        // Log the contact submission
        \Log::info('Contact form submission', [
            'name' => $validated['name'],
            'email' => $validated['email'],
            'subject' => $validated['subject'],
            'type' => $validated['type'],
        ]);

        return back()->with('success', '¡Gracias por contactarnos! Hemos recibido tu mensaje y te responderemos lo antes posible.');
    }

    /**
     * Get social links from settings.
     */
    private function getSocialLinks(): array
    {
        return \App\Models\SocialLink::where('is_active', true)
            ->orderBy('sort_order')
            ->get()
            ->map(function ($link) {
                return [
                    'platform' => $link->platform,
                    'url' => $link->url,
                ];
            })
            ->toArray();
    }
}
