<?php

namespace App\Services;

use App\Models\Visit;
use App\Models\EmailTemplate;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Log;

class EmailService
{
    /**
     * Send visit created emails to host and visitor
     */
    public function sendVisitCreatedEmails(Visit $visit): void
    {
        $registrationUrl = config('app.frontend_url') . '/visitor/register/' . $visit->registration_token;

        // Send to host
        $this->sendEmail('visit_created_host', $visit->host_email, [
            'host' => $visit->host_name,
            'requestId' => $visit->request_id,
            'visitor.email' => $visit->main_visitor_email,
            'location' => $visit->location->name,
            'meetingDate' => $this->formatMeetingDate($visit),
            'reason' => $visit->visit_reason,
        ]);

        // Send to visitor
        $this->sendEmail('visit_created_visitor', $visit->main_visitor_email, [
            'visitor.email' => $visit->main_visitor_email,
            'host' => $visit->host_name,
            'location' => $visit->location->name,
            'meetingDate' => $this->formatMeetingDate($visit),
            'reason' => $visit->visit_reason,
            'registrationUrl' => $registrationUrl,
        ]);
    }

    /**
     * Send emails after visitor submission
     */
    public function sendAfterSubmissionEmails(Visit $visit): void
    {
        $mainVisitor = $visit->mainVisitor;

        // Send to security team (get from settings or hardcoded emails)
        $securityEmails = $this->getSecurityEmails();
        foreach ($securityEmails as $email) {
            $this->sendEmail('after_submission_security', $email, [
                'requestId' => $visit->request_id,
                'host' => $visit->host_name,
                'visitor.name' => $mainVisitor->name,
                'visitor.email' => $mainVisitor->email,
                'location' => $visit->location->name,
                'meetingDate' => $this->formatMeetingDate($visit),
            ]);
        }

        // Send to host
        $this->sendEmail('after_submission_host', $visit->host_email, [
            'host' => $visit->host_name,
            'visitor.name' => $mainVisitor->name,
            'requestId' => $visit->request_id,
            'meetingDate' => $this->formatMeetingDate($visit),
        ]);
    }

    /**
     * Send approval emails
     */
    public function sendApprovalEmails(Visit $visit): void
    {
        $mainVisitor = $visit->mainVisitor;

        // Send to visitor
        $this->sendEmail('after_approval_visitor', $mainVisitor->email, [
            'visitor.name' => $mainVisitor->name,
            'location' => $visit->location->name,
            'meetingDate' => $this->formatMeetingDate($visit),
            'host' => $visit->host_name,
        ]);

        // Send to host
        $this->sendEmail('after_approval_host', $visit->host_email, [
            'host' => $visit->host_name,
            'visitor.name' => $mainVisitor->name,
            'requestId' => $visit->request_id,
            'meetingDate' => $this->formatMeetingDate($visit),
        ]);
    }

    /**
     * Send rejection email
     */
    public function sendRejectionEmail(Visit $visit): void
    {
        $this->sendEmail('rejection', $visit->host_email, [
            'host' => $visit->host_name,
            'visitor.email' => $visit->main_visitor_email,
            'reason' => $visit->rejection_reason,
            'requestId' => $visit->request_id,
        ]);
    }

    /**
     * Send security return email
     */
    public function sendSecurityReturnEmail(Visit $visit): void
    {
        $registrationUrl = config('app.frontend_url') . '/visitor/register/' . $visit->registration_token;

        $this->sendEmail('security_return', $visit->host_email, [
            'host' => $visit->host_name,
            'visitor.email' => $visit->main_visitor_email,
            'reason' => $visit->rejection_reason,
            'requestId' => $visit->request_id,
            'registrationUrl' => $registrationUrl,
        ]);
    }

    /**
     * Send reminder email to visitor
     */
    public function sendReminderEmail(Visit $visit): void
    {
        $registrationUrl = config('app.frontend_url') . '/visitor/register/' . $visit->registration_token;

        $this->sendEmail('reminder', $visit->main_visitor_email, [
            'visitor.email' => $visit->main_visitor_email,
            'host' => $visit->host_name,
            'meetingDate' => $this->formatMeetingDate($visit),
            'registrationUrl' => $registrationUrl,
        ]);
    }

    /**
     * Send email using template
     */
    private function sendEmail(string $templateType, string $to, array $variables): void
    {
        $template = EmailTemplate::getByType($templateType);

        if (!$template) {
            Log::warning("Email template not found: {$templateType}");
            return;
        }

        $processed = $template->replaceVariables($variables);

        try {
            Mail::send([], [], function ($message) use ($to, $processed) {
                $message->to($to)
                    ->subject($processed['subject'])
                    ->html($processed['body']);
            });
        } catch (\Exception $e) {
            Log::error("Failed to send email: " . $e->getMessage());
        }
    }

    /**
     * Format meeting date for email
     */
    private function formatMeetingDate(Visit $visit): string
    {
        if ($visit->meeting_type === 'single') {
            return $visit->date->format('Y-m-d') . ' from ' .
                $visit->start_time . ' to ' . $visit->end_time;
        }

        return $visit->date_from->format('Y-m-d') . ' to ' .
            $visit->date_to->format('Y-m-d') . ' (8 AM - 6 PM)';
    }

    /**
     * Get security team emails
     */
    private function getSecurityEmails(): array
    {
        // Get all security members and admins
        return \App\Models\UserRole::whereIn('role', ['security_member', 'security_admin'])
            ->where('is_active', true)
            ->pluck('email')
            ->toArray();
    }
}
