<?php
// app/Helpers/MailHelper.php

class MailHelper {
    /**
     * Send email using custom SMTP settings or fallback to standard PHP mail()
     */
    public static function send($to, $subject, $body) {
        $db = getDB();
        
        // Fetch SMTP settings from system_settings
        $settings = [];
        try {
            $rows = $db->query('SELECT * FROM system_settings WHERE setting_key LIKE "smtp_%"')->fetchAll();
            foreach ($rows as $row) {
                $settings[$row['setting_key']] = $row['setting_value'];
            }
        } catch (\Exception $e) {
            // Table might not exist or database query fails
        }
        
        $host = $settings['smtp_host'] ?? '';
        $port = $settings['smtp_port'] ?? '';
        $user = $settings['smtp_user'] ?? '';
        $pass = $settings['smtp_pass'] ?? '';
        $enc  = $settings['smtp_encryption'] ?? 'none';
        $fromEmail = $settings['smtp_from_email'] ?? 'noreply@restpo.com';
        $fromName  = $settings['smtp_from_name'] ?? 'RestPO';

        if (empty($host) || empty($port)) {
            // Fallback to PHP mail()
            $headers = "MIME-Version: 1.0\r\n";
            $headers .= "Content-Type: text/html; charset=UTF-8\r\n";
            $headers .= "From: " . $fromName . " <" . $fromEmail . ">\r\n";
            return @mail($to, $subject, $body, $headers);
        }

        // Custom SMTP socket client
        $socketHost = ($enc === 'ssl') ? 'ssl://' . $host : $host;
        $socket = @fsockopen($socketHost, $port, $errno, $errstr, 15);
        if (!$socket) {
            error_log("SMTP connection failed: $errstr ($errno)");
            // If socket fails, try PHP mail() as last-resort fallback
            $headers = "MIME-Version: 1.0\r\n";
            $headers .= "Content-Type: text/html; charset=UTF-8\r\n";
            $headers .= "From: " . $fromName . " <" . $fromEmail . ">\r\n";
            return @mail($to, $subject, $body, $headers);
        }

        $getResponse = function() use ($socket) {
            $response = "";
            while (($line = fgets($socket, 512)) !== false) {
                $response .= $line;
                if (substr($line, 3, 1) === " ") {
                    break;
                }
            }
            return $response;
        };

        $sendCommand = function($cmd) use ($socket, $getResponse) {
            fputs($socket, $cmd . "\r\n");
            return $getResponse();
        };

        $getResponse(); // Read greeting

        $sendCommand("EHLO " . ($_SERVER['SERVER_NAME'] ?? 'localhost'));

        if ($enc === 'tls') {
            $res = $sendCommand("STARTTLS");
            if (strpos($res, '220') === false) {
                fclose($socket);
                return false;
            }
            if (!stream_socket_enable_crypto($socket, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) {
                fclose($socket);
                return false;
            }
            $sendCommand("EHLO " . ($_SERVER['SERVER_NAME'] ?? 'localhost'));
        }

        if (!empty($user) && !empty($pass)) {
            $sendCommand("AUTH LOGIN");
            $sendCommand(base64_encode($user));
            $res = $sendCommand(base64_encode($pass));
            if (strpos($res, '235') === false) {
                fclose($socket);
                error_log("SMTP Auth failed for user $user");
                return false;
            }
        }

        $sendCommand("MAIL FROM:<$fromEmail>");
        $sendCommand("RCPT TO:<$to>");
        $sendCommand("DATA");

        $headers = [
            "MIME-Version: 1.0",
            "Content-Type: text/html; charset=UTF-8",
            "From: =?UTF-8?B?" . base64_encode($fromName) . "?= <$fromEmail>",
            "To: <$to>",
            "Subject: =?UTF-8?B?" . base64_encode($subject) . "?=",
            "Date: " . date('r'),
        ];
        
        $emailContent = implode("\r\n", $headers) . "\r\n\r\n" . $body . "\r\n.";
        $res = $sendCommand($emailContent);
        
        $sendCommand("QUIT");
        fclose($socket);

        // Save in notifications table
        try {
            $db = getDB();
            $stmt = $db->prepare('INSERT INTO notifications (title, message, type, status) VALUES (?, ?, "email", ?)');
            $stmt->execute([$subject, strip_tags($body), (strpos($res, '250') !== false) ? 'sent' : 'failed']);
        } catch (\Exception $ex) {
            // Ignore if notifications log fails
        }

        return (strpos($res, '250') !== false);
    }

    /**
     * Send welcome email to newly created restaurant admin
     */
    public static function sendWelcomeEmail($toEmail, $adminName, $restaurantName) {
        $subject = "Welcome to RestPO - Your Restaurant Account is Ready!";
        
        $loginUrl = ($_SERVER['REQUEST_SCHEME'] ?? 'http') . '://' . ($_SERVER['HTTP_HOST'] ?? 'localhost') . '/restpo/login';
        
        $body = '
        <div style="font-family: \'Inter\', sans-serif; max-width: 600px; margin: 0 auto; padding: 25px; border: 1px solid #e2e8f0; border-radius: 16px; background-color: #ffffff; color: #1e293b;">
            <div style="text-align: center; margin-bottom: 25px;">
                <div style="display: inline-block; width: 48px; height: 48px; border-radius: 12px; background: linear-gradient(135deg, #8b5cf6, #3b82f6); line-height: 48px; color: white; font-size: 24px; font-weight: bold;">R</div>
                <h2 style="font-size: 20px; font-weight: bold; color: #0f172a; margin-top: 15px;">Account Approved Successfully!</h2>
            </div>
            
            <p>Hello <strong>' . htmlspecialchars($adminName) . '</strong>,</p>
            <p>Welcome to <strong>RestPO</strong>! Your restaurant portal for <strong>' . htmlspecialchars($restaurantName) . '</strong> has been approved and activated by the System Administrator.</p>
            
            <div style="background-color: #f8fafc; border: 1px solid #e2e8f0; border-radius: 12px; padding: 18px; margin: 20px 0;">
                <h4 style="margin-top: 0; margin-bottom: 12px; color: #0f172a; font-size: 14px; text-transform: uppercase; letter-spacing: 0.05em;">Your Login Details:</h4>
                <table style="width: 100%; font-size: 13.5px; border-spacing: 0 6px;">
                    <tr>
                        <td style="color: #64748b; width: 100px;">Portal URL:</td>
                        <td><a href="' . $loginUrl . '" style="color: #8b5cf6; font-weight: bold; text-decoration: none;">' . $loginUrl . '</a></td>
                    </tr>
                    <tr>
                        <td style="color: #64748b;">Admin Email:</td>
                        <td style="font-weight: bold; color: #0f172a;">' . htmlspecialchars($toEmail) . '</td>
                    </tr>
                </table>
            </div>
            
            <p style="font-size: 14px; color: #475569; margin-bottom: 20px;">You can now log in using the email and password you created during registration.</p>
            
            <div style="text-align: center; margin: 30px 0;">
                <a href="' . $loginUrl . '" style="display: inline-block; padding: 12px 24px; background: linear-gradient(135deg, #8b5cf6, #3b82f6); color: white; text-decoration: none; font-weight: bold; border-radius: 8px; box-shadow: 0 4px 6px rgba(139, 92, 246, 0.25);">Login to Dashboard</a>
            </div>
            
            <hr style="border: 0; border-top: 1px solid #f1f5f9; margin: 25px 0;">
            <p style="font-size: 12px; color: #94a3b8; text-align: center; margin: 0;">&copy; ' . date('Y') . ' RestPO. All Rights Reserved.</p>
        </div>
        ';

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

    /**
     * Send confirmation email for approved subscriptions
     */
    public static function sendSubscriptionApprovedEmail($toEmail, $adminName, $packageName, $endDate) {
        $subject = "Subscription Activated - RestPO!";
        
        $body = '
        <div style="font-family: \'Inter\', sans-serif; max-width: 600px; margin: 0 auto; padding: 25px; border: 1px solid #e2e8f0; border-radius: 16px; background-color: #ffffff; color: #1e293b;">
            <div style="text-align: center; margin-bottom: 25px;">
                <div style="display: inline-block; width: 48px; height: 48px; border-radius: 12px; background: linear-gradient(135deg, #10b981, #059669); line-height: 48px; color: white; font-size: 24px; font-weight: bold;"><i class="fas fa-check"></i></div>
                <h2 style="font-size: 20px; font-weight: bold; color: #0f172a; margin-top: 15px;">Subscription Approved!</h2>
            </div>
            
            <p>Hello <strong>' . htmlspecialchars($adminName) . '</strong>,</p>
            <p>Great news! Your payment/purchase request for subscription plan has been approved by the System Administrator.</p>
            
            <div style="background-color: #f0fdf4; border: 1px solid #bbf7d0; border-radius: 12px; padding: 18px; margin: 20px 0;">
                <h4 style="margin-top: 0; margin-bottom: 12px; color: #15803d; font-size: 14px; text-transform: uppercase;">Plan Details:</h4>
                <table style="width: 100%; font-size: 13.5px; border-spacing: 0 6px;">
                    <tr>
                        <td style="color: #166534; width: 120px;">Active Package:</td>
                        <td style="font-weight: bold; color: #14532d;">' . htmlspecialchars($packageName) . '</td>
                    </tr>
                    <tr>
                        <td style="color: #166534;">Expires On:</td>
                        <td style="font-weight: bold; color: #14532d;">' . ($endDate === 'Lifetime' ? 'Lifetime Plan (Never Expires)' : date('M d, Y', strtotime($endDate))) . '</td>
                    </tr>
                    <tr>
                        <td style="color: #166534;">Account Status:</td>
                        <td><span style="background-color: #dcfce7; color: #166534; padding: 2px 8px; border-radius: 9999px; font-weight: bold; font-size: 12px; border: 1px solid #bbf7d0;">ACTIVE</span></td>
                    </tr>
                </table>
            </div>
            
            <p>All subscription limitations have been updated in your dashboard. You can continue managing your floors, tables, and staff limits seamlessly.</p>
            
            <hr style="border: 0; border-top: 1px solid #f1f5f9; margin: 25px 0;">
            <p style="font-size: 12px; color: #94a3b8; text-align: center; margin: 0;">&copy; ' . date('Y') . ' RestPO. All Rights Reserved.</p>
        </div>
        ';

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