<?php

namespace App\Helpers;

class Mailer
{
    private static $mailer = null;

    private static function getDbSettings()
    {
        $settings = [];
        try {
            $db = \App\Config\Database::getInstance()->getConnection();
            $stmt = $db->query("SELECT `key`, `value` FROM `settings` WHERE `group` = 'mail'");
            while ($row = $stmt->fetch(\PDO::FETCH_OBJ)) {
                $settings[$row->key] = $row->value;
            }
        } catch (\Exception $e) {
        }
        return $settings;
    }

    private static function getSetting($dbSettings, $key, $constName, $default)
    {
        if (isset($dbSettings[$key]) && $dbSettings[$key] !== '') {
            return $dbSettings[$key];
        }
        if (defined($constName)) {
            return constant($constName);
        }
        return $default;
    }

    public static function init()
    {
        if (self::$mailer === null) {
            $composerAutoload = __DIR__ . '/../../public/vendor/vendor/autoload.php';
            if (file_exists($composerAutoload)) {
                require_once $composerAutoload;
            } else {
                require_once __DIR__ . '/../../public/vendor/phpmailer/PHPMailer.php';
                require_once __DIR__ . '/../../public/vendor/phpmailer/SMTP.php';
                require_once __DIR__ . '/../../public/vendor/phpmailer/Exception.php';
            }

            $dbSettings = self::getDbSettings();

            $mail = new \PHPMailer\PHPMailer\PHPMailer(true);

            $provider = self::getSetting($dbSettings, 'mail_provider', 'MAIL_PROVIDER', 'smtp');
            if ($provider === 'smtp' || $provider === '') {
                $mail->isSMTP();
            }
            $mail->Host = self::getSetting($dbSettings, 'mail_host', 'MAIL_HOST', 'smtp.gmail.com');
            $mail->SMTPAuth = true;
            $mail->Username = self::getSetting($dbSettings, 'mail_username', 'MAIL_USERNAME', '');
            $mail->Password = self::getSetting($dbSettings, 'mail_password', 'MAIL_PASSWORD', '');
            $mail->SMTPSecure = self::getSetting($dbSettings, 'mail_encryption', 'MAIL_ENCRYPTION', 'tls');
            $mail->Port = self::getSetting($dbSettings, 'mail_port', 'MAIL_PORT', 587);
            $mail->setFrom(
                self::getSetting($dbSettings, 'mail_from_address', 'MAIL_FROM_ADDRESS', 'noreply@ghanaanaesthesia.com'),
                self::getSetting($dbSettings, 'mail_from_name', 'MAIL_FROM_NAME', 'Ghana Anaesthesiologists Society')
            );
            $mail->isHTML(true);
            $mail->CharSet = 'UTF-8';

            self::$mailer = $mail;
        }
        return self::$mailer;
    }

    public static function send($to, $subject, $body, $attachments = [])
    {
        try {
            $mail = self::init();
            $mail->clearAddresses();
            $mail->clearAttachments();

            $mail->addAddress($to);
            $mail->Subject = $subject;
            $mail->Body = $body;
            $mail->AltBody = strip_tags($body);

            foreach ($attachments as $attachment) {
                if (file_exists($attachment)) {
                    $mail->addAttachment($attachment);
                }
            }

            return $mail->send();
        } catch (\Exception $e) {
            error_log("Mailer Error: " . $e->getMessage());
            return false;
        }
    }

    public static function sendApprovalEmail($email, $name)
    {
        $subject = "Membership Approved - Ghana Anaesthesiologists Society";
        $body = "
        <div style='font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; background: #f8f9fa; padding: 30px;'>
            <div style='background: linear-gradient(135deg, #21417A, #4e73df); padding: 30px; border-radius: 10px 10px 0 0; text-align: center;'>
                <h1 style='color: white; margin: 0; font-size: 24px;'>Ghana Anaesthesiologists Society</h1>
                <p style='color: rgba(255,255,255,0.8); margin: 10px 0 0;'>Membership Approved</p>
            </div>
            <div style='background: white; padding: 30px; border-radius: 0 0 10px 10px;'>
                <p>Dear <strong>{$name}</strong>,</p>
                <p>We are pleased to inform you that your membership application to the <strong>Ghana Anaesthesiologists Society</strong> has been reviewed and <strong style='color: #1cc88a;'>APPROVED</strong>.</p>
                <p>You can now log in to your account using the credentials you created during registration:</p>
                <div style='background: #f0f4ff; padding: 15px; border-radius: 8px; margin: 20px 0; text-align: center;'>
                    <p style='margin: 5px 0;'><a href='" . Url::to('/login') . "' style='display: inline-block; background: linear-gradient(135deg, #4e73df, #224abe); color: white; padding: 12px 30px; text-decoration: none; border-radius: 8px; font-weight: bold;'>Login to Your Account</a></p>
                </div>
                <p>Once logged in, please complete your membership profile to access all features including:</p>
                <ul style='color: #555;'>
                    <li>Member Directory</li>
                    <li>Event Registration</li>
                    <li>Forum Discussions</li>
                    <li>Document Library</li>
                    <li>And more...</li>
                </ul>
                <p>If you have any questions, please contact the society secretariat.</p>
                <p>Best regards,<br><strong>Ghana Anaesthesiologists Society</strong></p>
                <hr style='border: none; border-top: 1px solid #eee; margin: 20px 0;'>
                <p style='color: #999; font-size: 12px;'>This is an automated message. Please do not reply directly.</p>
            </div>
        </div>";

        return self::send($email, $subject, $body);
    }

    public static function sendRejectionEmail($email, $name, $reason = '')
    {
        $subject = "Membership Application Update - Ghana Anaesthesiologists Society";
        $reasonText = $reason ? "<p><strong>Reason:</strong> {$reason}</p>" : '';
        $body = "
        <div style='font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; background: #f8f9fa; padding: 30px;'>
            <div style='background: linear-gradient(135deg, #e74a3b, #c0392b); padding: 30px; border-radius: 10px 10px 0 0; text-align: center;'>
                <h1 style='color: white; margin: 0; font-size: 24px;'>Ghana Anaesthesiologists Society</h1>
                <p style='color: rgba(255,255,255,0.8); margin: 10px 0 0;'>Membership Application Update</p>
            </div>
            <div style='background: white; padding: 30px; border-radius: 0 0 10px 10px;'>
                <p>Dear <strong>{$name}</strong>,</p>
                <p>Thank you for your interest in joining the <strong>Ghana Anaesthesiologists Society</strong>.</p>
                <p>After careful review, we regret to inform you that your membership application has been <strong style='color: #e74a3b;'>declined</strong> at this time.</p>
                {$reasonText}
                <p>You may reapply in the future or contact the society secretariat for further clarification.</p>
                <p>Best regards,<br><strong>Ghana Anaesthesiologists Society</strong></p>
            </div>
        </div>";

        return self::send($email, $subject, $body);
    }

    public static function sendProfileReminder($email, $name)
    {
        $subject = "Complete Your Profile - Ghana Anaesthesiologists Society";
        $body = "
        <div style='font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; background: #f8f9fa; padding: 30px;'>
            <div style='background: linear-gradient(135deg, #f6c23e, #d4a72c); padding: 30px; border-radius: 10px 10px 0 0; text-align: center;'>
                <h1 style='color: white; margin: 0; font-size: 24px;'>Profile Reminder</h1>
            </div>
            <div style='background: white; padding: 30px; border-radius: 0 0 10px 10px;'>
                <p>Dear <strong>{$name}</strong>,</p>
                <p>Your membership profile is <strong>incomplete</strong>. Please log in to complete your profile to access all member benefits.</p>
                <div style='background: #f0f4ff; padding: 15px; border-radius: 8px; margin: 20px 0; text-align: center;'>
                    <p style='margin: 5px 0;'><a href='" . Url::to('/member/profile') . "' style='display: inline-block; background: linear-gradient(135deg, #4e73df, #224abe); color: white; padding: 12px 30px; text-decoration: none; border-radius: 8px; font-weight: bold;'>Complete Your Profile</a></p>
                </div>
                <p>Completing your profile ensures you receive relevant updates and can participate fully in society activities.</p>
                <p>Thank you,<br><strong>Ghana Anaesthesiologists Society</strong></p>
            </div>
        </div>";

        return self::send($email, $subject, $body);
    }

    public static function sendNewRegistrationAlert($adminEmail, $adminName, $applicant)
    {
        $subject = "New Membership Registration - {$applicant->name}";
        $name = htmlspecialchars($applicant->name);
        $email = htmlspecialchars($applicant->email);
        $pin = htmlspecialchars($applicant->professional_pin ?: 'Not provided');
        $date = date('M d, Y h:i A', strtotime($applicant->created_at));

        $body = "
        <div style='font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; background: #f8f9fa; padding: 30px;'>
            <div style='background: linear-gradient(135deg, #f6c23e, #d4a72c); padding: 30px; border-radius: 10px 10px 0 0; text-align: center;'>
                <h1 style='color: white; margin: 0; font-size: 24px;'>New Registration Alert</h1>
                <p style='color: rgba(255,255,255,0.8); margin: 10px 0 0;'>Ghana Anaesthesiologists Society</p>
            </div>
            <div style='background: white; padding: 30px; border-radius: 0 0 10px 10px;'>
                <p>Dear <strong>{$adminName}</strong>,</p>
                <p>A new membership application has been submitted and requires your review.</p>
                <table style='width: 100%; border-collapse: collapse; margin: 20px 0;'>
                    <tr><td style='padding: 10px; border-bottom: 1px solid #eee; color: #888; width: 40%;'>Applicant</td><td style='padding: 10px; border-bottom: 1px solid #eee; font-weight: bold;'>{$name}</td></tr>
                    <tr><td style='padding: 10px; border-bottom: 1px solid #eee; color: #888;'>Email</td><td style='padding: 10px; border-bottom: 1px solid #eee;'>{$email}</td></tr>
                    <tr><td style='padding: 10px; border-bottom: 1px solid #eee; color: #888;'>Professional PIN</td><td style='padding: 10px; border-bottom: 1px solid #eee;'>{$pin}</td></tr>
                    <tr><td style='padding: 10px; color: #888;'>Submitted</td><td style='padding: 10px;'>{$date}</td></tr>
                </table>
                <div style='background: #f0f4ff; padding: 15px; border-radius: 8px; margin: 20px 0; text-align: center;'>
                    <a href='" . Url::to('/users/pending') . "' style='display: inline-block; background: linear-gradient(135deg, #4e73df, #224abe); color: white; padding: 12px 30px; text-decoration: none; border-radius: 8px; font-weight: bold;'>Review Pending Applications</a>
                </div>
                <p>Best regards,<br><strong>Ghana Anaesthesiologists Society</strong></p>
            </div>
        </div>";

        return self::send($adminEmail, $subject, $body);
    }

    public static function sendMessageNotification($email, $name, $senderName, $subject, $messageBody)
    {
        $subjectLine = "New Message: {$subject} - Ghana Anaesthesiologists Society";
        $preview = substr(strip_tags($messageBody), 0, 200);

        $body = "
        <div style='font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; background: #f8f9fa; padding: 30px;'>
            <div style='background: linear-gradient(135deg, #21417A, #4e73df); padding: 30px; border-radius: 10px 10px 0 0; text-align: center;'>
                <h1 style='color: white; margin: 0; font-size: 20px;'>New Message Received</h1>
            </div>
            <div style='background: white; padding: 30px; border-radius: 0 0 10px 10px;'>
                <p>Dear <strong>{$name}</strong>,</p>
                <p>You have received a new message from <strong>{$senderName}</strong>.</p>
                <div style='background: #f8f9fa; padding: 15px; border-radius: 8px; margin: 15px 0; border-left: 3px solid #4e73df;'>
                    <p style='margin: 0 0 5px; font-weight: bold;'>{$subject}</p>
                    <p style='margin: 0; color: #666;'>{$preview}...</p>
                </div>
                <div style='background: #f0f4ff; padding: 15px; border-radius: 8px; margin: 20px 0; text-align: center;'>
                    <a href='" . Url::to('/messages/inbox') . "' style='display: inline-block; background: linear-gradient(135deg, #4e73df, #224abe); color: white; padding: 12px 30px; text-decoration: none; border-radius: 8px; font-weight: bold;'>View Message</a>
                </div>
                <p>Best regards,<br><strong>Ghana Anaesthesiologists Society</strong></p>
            </div>
        </div>";

        return self::send($email, $subjectLine, $body);
    }

    public static function sendAnnouncement($email, $name, $title, $content)
    {
        $subject = "Announcement: {$title} - Ghana Anaesthesiologists Society";
        $body = "
        <div style='font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; background: #f8f9fa; padding: 30px;'>
            <div style='background: linear-gradient(135deg, #21417A, #4e73df); padding: 20px; border-radius: 10px 10px 0 0; text-align: center;'>
                <h2 style='color: white; margin: 0; font-size: 20px;'>{$title}</h2>
            </div>
            <div style='background: white; padding: 30px; border-radius: 0 0 10px 10px;'>
                <p>Dear <strong>{$name}</strong>,</p>
                <div style='color: #555; line-height: 1.6;'>{$content}</div>
                <hr style='border: none; border-top: 1px solid #eee; margin: 20px 0;'>
                <p style='color: #999; font-size: 12px;'>Ghana Anaesthesiologists Society</p>
            </div>
        </div>";

        return self::send($email, $subject, $body);
    }
}
