<?php
require_once '../includes/config.php'; // Include the database connection

if (!defined('ZEPTOMAIL_TOKEN') || empty(ZEPTOMAIL_TOKEN)) {
    throw new Exception('Email configuration missing');
}




function sendOTPEmail($email, $name, $otp)
{
    $htmlBody = "
<div style='margin:0;padding:0;background:#f4f6f8;font-family:Arial,Helvetica,sans-serif;'>
    <table width='100%' cellpadding='0' cellspacing='0' style='padding:30px 0;'>
        <tr>
            <td align='center'>
                <table width='100%' cellpadding='0' cellspacing='0' style='max-width:520px;background:#ffffff;border-radius:10px;box-shadow:0 10px 30px rgba(0,0,0,0.08);overflow:hidden;'>

                    <tr>
                        <td style='background:#2c5364;padding:20px;text-align:center;color:#ffffff;'>
                            <h2 style='margin:0;font-size:22px;'>Invoice360 Email Verification</h2>
                        </td>
                    </tr>

                    <tr>
                        <td style='padding:30px;color:#333333;'>
                            <p style='font-size:16px;'>Hello <strong>{$name}</strong>,</p>

                            <p style='font-size:14px;color:#555;line-height:1.6;'>
                                Use the verification code below to confirm your email address.
                            </p>

                            <div style='text-align:center;margin:30px 0;'>
                                <span style='font-size:32px;letter-spacing:6px;font-weight:bold;color:#2c5364;padding:12px 20px;border:1px dashed #2c5364;border-radius:8px;'>
                                    {$otp}
                                </span>
                            </div>

                            <p style='font-size:14px;color:#555;'>
                                This code expires in <strong>10 minutes</strong>.
                            </p>

                            <hr style='border:none;border-top:1px solid #eaeaea;margin:25px 0;'>

                            <p style='font-size:13px;color:#666;'>
                                Contact us at 
                                <a href='mailto:support@invoice360.ng' style='color:#2c5364;font-weight:bold;'>
                                    support@invoice360.ng
                                </a>
                            </p>
                        </td>
                    </tr>

                    <tr>
                        <td style='background:#f8f9fa;padding:15px;text-align:center;font-size:12px;color:#888;'>
                            If you did not request this verification, please ignore this email.
                        </td>
                    </tr>

                </table>
            </td>
        </tr>
    </table>
</div>
";


$payload = [
        "from" => [
            "address" => ZEPTOMAIL_FROM,
            "name" => "Invoice360 Support"
        ],
        "to" => [[
            "email_address" => [
                "address" => $email,
                "name" => $name
            ]
        ]],
        "subject" => "Email Verification OTP",
        "htmlbody" => "...",
        "textbody" => "Your OTP is {$otp}"
    ];

    $ch = curl_init("https://api.zeptomail.com/v1.1/email");
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_HTTPHEADER => [
            "Authorization: " . ZEPTOMAIL_TOKEN,
            "Content-Type: application/json"
        ],
        CURLOPT_POSTFIELDS => json_encode($payload),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 15
    ]);

    curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    return $httpCode === 201;
    
}


function sendWelcomeEmail($email, $name) {

    $mail = new PHPMailer(true);

    try {
        $mail->isSMTP();
        $mail->Host       = 'smtppro.zoho.com';
        $mail->SMTPAuth   = true;
        $mail->Username   = 'docsupport@docadvisory.com';
        $mail->Password   = 'DegitechSolutions@2025'; // move to env later
        $mail->SMTPSecure = 'ssl';
        $mail->Port       = 465;

        $mail->setFrom('docsupport@docadvisory.com', 'Invoice360 Support');
        $mail->addAddress($email, $name);

        $mail->isHTML(true);
        $mail->Subject = 'Welcome to Invoice360';

        $mail->Body = '
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Welcome to Invoice360</title>
</head>
<body style="margin:0; padding:0; background-color:#f4f6f8; font-family:Arial, Helvetica, sans-serif;">

    <table width="100%" cellpadding="0" cellspacing="0" style="background-color:#f4f6f8; padding:30px 0;">
        <tr>
            <td align="center">
                <table width="600" cellpadding="0" cellspacing="0" style="background-color:#ffffff; border-radius:8px; overflow:hidden; box-shadow:0 4px 12px rgba(0,0,0,0.08);">

                    <!-- Header -->
                    <tr>
                        <td style="background-color:#2c5364; padding:25px; text-align:center;">
                            <h1 style="color:#ffffff; margin:0; font-size:24px; letter-spacing:0.5px;">
                                Welcome to Invoice360
                            </h1>
                        </td>
                    </tr>

                    <!-- Body -->
                    <tr>
                        <td style="padding:30px; color:#333333; font-size:15px; line-height:1.6;">
                            <p style="margin-top:0;">
                                Dear <strong>' . htmlspecialchars($name) . '</strong>,
                            </p>

                            <p>
                                We are pleased to inform you that your account has been successfully created on
                                <strong>Invoice360</strong>.
                            </p>

                            <p>
                                You can now log in using your registered email address and begin exploring our platform.
                                Invoice360 is designed to help you manage your documents and workflows efficiently and securely.
                            </p>

                            <p>
                                If you have any questions or require assistance, our support team is always here to help.
                            </p>

                            <p>
                                We’re excited to have you on board and look forward to supporting your success.
                            </p>

                            <p>
                                Contact us at 
                                <a href="mailto:support@invoice360.ng" style="color:#2c5364;text-decoration:none;font-weight:bold;">
                                    support@invoice360.ng
                                </a>
                                for swift assistance.
                            </p>
                            <p style="text-align:center;margin:30px 0">
                                <a href="www.invoice360.ng"
                                style="background:#2c5364;color:#ffffff;padding:14px 28px;
                                        text-decoration:none;border-radius:8px;
                                        font-weight:bold;display:inline-block">
                                    Start Now
                                </a>
                            </p>
                        </td>
                    </tr>

                    <!-- Footer -->
                    <tr>
                        <td style="background-color:#f0f3f6; padding:20px; text-align:center; font-size:13px; color:#666666;">
                            <p style="margin:0;">
                                <strong>Invoice360 Support Team</strong><br>
                                
                            </p>
                            <p style="margin:8px 0 0; font-size:12px; color:#999999;">
                                © ' . date('Y') . ' Invoice360. All rights reserved.
                            </p>
                        </td>
                    </tr>

                </table>
            </td>
        </tr>
    </table>

</body>
</html>
';

        $mail->send();
        return true;

    } catch (Exception $e) {
        error_log('Welcome Email Error: ' . $mail->ErrorInfo);
        return false;
    }
}




//using one function now;

function sendExpiryReminderEmail(string $email, string $company, string $endsAt, string $plan): bool
{
    $mail = new PHPMailer(true);

    try {
        $mail->isSMTP();
        $mail->Host       = 'smtppro.zoho.com';
        $mail->SMTPAuth   = true;
        $mail->Username   = 'docsupport@docadvisory.com';
        $mail->Password   = 'DegitechSolutions@2025'; // move to env
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
        $mail->Port       = 465;

        $mail->setFrom('docsupport@docadvisory.com', 'Invoice360 Support');
        $mail->addAddress($email, $company);

        $mail->isHTML(true);

        $mail->Subject = "Your {$plan} plan expires in 7 days";

        $mail->Body = "
<!DOCTYPE html>
<html>
<body style='margin:0; padding:0; background-color:#f4f6fb; font-family:Arial, Helvetica, sans-serif;'>

<table width='100%' cellpadding='0' cellspacing='0' style='padding:40px 0;'>
    <tr>
        <td align='center'>

            <table width='100%' cellpadding='0' cellspacing='0' style='max-width:560px; background:#ffffff; border-radius:12px; box-shadow:0 12px 30px rgba(0,0,0,0.08); overflow:hidden;'>

                <!-- HEADER -->
                <tr>
                    <td style='background:#2c5364; padding:22px; text-align:center;'>
                        <h2 style='margin:0; font-size:20px; color:#ffffff; font-weight:600;'>
                            Subscription Expiry Reminder
                        </h2>
                    </td>
                </tr>

                <!-- CONTENT -->
                <tr>
                    <td style='padding:32px; color:#111827;'>

                        <p style='margin:0 0 14px; font-size:15px;'>
                            Hello <strong>{$company}</strong>,
                        </p>

                        <p style='margin:0 0 16px; font-size:14px; line-height:1.6; color:#374151;'>
                            This is a friendly reminder that your
                            <strong>{$plan}</strong> subscription will expire on:
                        </p>

                        <!-- EXPIRY DATE -->
                        <div style='
                            text-align:center;
                            font-size:20px;
                            font-weight:700;
                            color:#2c5364;
                            background:#eaf1f4;
                            padding:14px;
                            border-radius:10px;
                            margin:22px 0;
                        '>
                            {$endsAt}
                        </div>

                        <p style='margin:0 0 20px; font-size:14px; color:#374151;'>
                            To avoid any interruption to your services, please renew your plan before the expiration date.
                        </p>

                        <!-- CTA BUTTON -->
                        <div style='text-align:center; margin:28px 0;'>
                            <a href='https://yourdomain.com/billing'
                               style='
                                   display:inline-block;
                                   padding:14px 28px;
                                   background:#2c5364;
                                   color:#ffffff;
                                   font-size:14px;
                                   font-weight:600;
                                   text-decoration:none;
                                   border-radius:8px;
                               '>
                                Renew Subscription
                            </a>
                        </div>

                        <p style='margin:0; font-size:14px; color:#374151;'>
                            Thank you for choosing <strong>Invoice360</strong>.
                        </p>

                        <p style='margin:18px 0 0; font-size:13px; color:#6b7280;'>
                            If you have already renewed your subscription, please ignore this message.
                        </p>

                    </td>
                </tr>

                <!-- FOOTER -->
                <tr>
                    <td style='background:#f9fafb; padding:16px; text-align:center;'>
                        <p style='margin:0; font-size:12px; color:#6b7280;'>
                            © ".date('Y')." Invoice360 · Billing Team
                        </p>
                    </td>
                </tr>

            </table>

        </td>
    </tr>
</table>

</body>
</html>
";


        $mail->send();
        return true;

    } catch (Exception $e) {
        error_log('Reminder Email Error: ' . $e->getMessage());
        return false;
    }
}



function sendPlanExpiredEmail(string $email, string $company, string $plan): bool
{
    $mail = new PHPMailer(true);

    try {
        $mail->isSMTP();
        $mail->Host       = 'smtppro.zoho.com';
        $mail->SMTPAuth   = true;
        $mail->Username   = 'docsupport@docadvisory.com';
        $mail->Password   = 'DegitechSolutions@2025'; // move to env later
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
        $mail->Port       = 465;

        $mail->setFrom('docsupport@docadvisory.com', 'Invoice360 Support');
        $mail->addAddress($email, $company);

        $mail->isHTML(true);

        $mail->Subject = "Your {$plan} subscription has expired";

        $mail->Body = "
<!DOCTYPE html>
<html>
<body style='margin:0; padding:0; background-color:#f4f6fb; font-family:Arial, Helvetica, sans-serif;'>

<table width='100%' cellpadding='0' cellspacing='0' style='padding:40px 0;'>
    <tr>
        <td align='center'>

            <table width='100%' cellpadding='0' cellspacing='0' style='max-width:560px; background:#ffffff; border-radius:12px; box-shadow:0 12px 30px rgba(0,0,0,0.08); overflow:hidden;'>

                <!-- HEADER -->
                <tr>
                    <td style='background:#d9534f; padding:22px; text-align:center;'>
                        <h2 style='margin:0; font-size:20px; color:#ffffff; font-weight:600;'>
                            {$plan} Subscription Expired
                        </h2>
                    </td>
                </tr>

                <!-- CONTENT -->
                <tr>
                    <td style='padding:32px; color:#111827;'>

                        <p style='margin:0 0 14px; font-size:15px;'>
                            Hello <strong>{$company}</strong>,
                        </p>

                        <p style='margin:0 0 16px; font-size:14px; line-height:1.6; color:#374151;'>
                            We’re writing to inform you that your subscription has
                            <strong style='color:#d9534f;'>expired</strong>.
                        </p>

                        <!-- STATUS BOX -->
                        <div style='
                            text-align:center;
                            font-size:15px;
                            font-weight:600;
                            color:#b91c1c;
                            background:#fde8e8;
                            padding:14px;
                            border-radius:10px;
                            margin:22px 0;
                        '>
                            Access Limited — Renewal Required
                        </div>

                        <p style='margin:0 0 20px; font-size:14px; color:#374151;'>
                            Your access is currently limited. To restore full access and continue using our services without interruption, please renew your plan.
                        </p>

                        <!-- CTA BUTTON -->
                        <div style='text-align:center; margin:28px 0;'>
                            <a href='https://yourdomain.com/billing'
                               style='
                                   display:inline-block;
                                   padding:14px 28px;
                                   background:#d9534f;
                                   color:#ffffff;
                                   font-size:14px;
                                   font-weight:600;
                                   text-decoration:none;
                                   border-radius:8px;
                               '>
                                Renew Subscription
                            </a>
                        </div>

                        <p style='margin:0; font-size:14px; color:#374151;'>
                            We look forward to welcoming you back.
                        </p>

                        <p style='margin:18px 0 0; font-size:13px; color:#6b7280;'>
                            If you believe this message was sent in error, please contact our support team.
                        </p>

                    </td>
                </tr>

                <!-- FOOTER -->
                <tr>
                    <td style='background:#f9fafb; padding:16px; text-align:center;'>
                        <p style='margin:0; font-size:12px; color:#6b7280;'>
                            © ".date('Y')." Invoice360 · Billing Team
                        </p>
                    </td>
                </tr>

            </table>

        </td>
    </tr>
</table>

</body>
</html>
";


        $mail->AltBody = "Your subscription has expired. Please log in to renew.";

        $mail->send();
        return true;

    } catch (Exception $e) {
        error_log('Expired Email Error: ' . $mail->ErrorInfo);
        return false;
    }
}




function sendLoginOtpEmail(string $email, string $name, string $otp): void
{
   
    $mail = new PHPMailer(true);

    try {
        /* =========================
           SMTP CONFIGURATION
        ========================== */
        $mail->isSMTP();
        $mail->Host       = 'smtppro.zoho.com';
        $mail->SMTPAuth   = true;
        $mail->Username   = 'docsupport@docadvisory.com';
        $mail->Password   = 'DegitechSolutions@2025'; // move to env later
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port       = 587;

        $mail->setFrom('docsupport@docadvisory.com', 'Invoice360 Support');
        $mail->addAddress($email, $name);

        $mail->isHTML(true);
        $mail->Subject = 'Email Verification OTP';

        
        $mail->Body = "
<!DOCTYPE html>
<html>
<body style='margin:0; padding:0; background-color:#f4f6fb; font-family:Arial, Helvetica, sans-serif;'>

<table width='100%' cellpadding='0' cellspacing='0' style='padding:40px 0;'>
    <tr>
        <td align='center'>

            <table width='100%' cellpadding='0' cellspacing='0' style='max-width:520px; background:#ffffff; border-radius:12px; box-shadow:0 12px 30px rgba(0,0,0,0.08); overflow:hidden;'>

                <!-- HEADER -->
                <tr>
                    <td style='background:#4f46e5; padding:22px; text-align:center;'>
                        <h2 style='margin:0; font-size:20px; color:#ffffff; font-weight:600;'>
                            Login Verification
                        </h2>
                    </td>
                </tr>

                <!-- CONTENT -->
                <tr>
                    <td style='padding:30px; color:#111827;'>

                        <p style='margin:0 0 14px; font-size:15px;'>
                            Hello <strong>{$name}</strong>,
                        </p>

                        <p style='margin:0 0 16px; font-size:14px; line-height:1.6; color:#374151;'>
                            We detected a login attempt from a new device.
                            To continue, please enter the verification code below.
                        </p>

                        <!-- OTP -->
                        <div style='text-align:center; margin:24px 0;'>
                            <span style='
                                display:inline-block;
                                font-size:28px;
                                font-weight:700;
                                letter-spacing:8px;
                                color:#4f46e5;
                                background:#eef2ff;
                                padding:14px 22px;
                                border-radius:10px;
                            '>
                                {$otp}
                            </span>
                        </div>

                        <p style='margin:0 0 14px; font-size:14px; color:#374151;'>
                            This code will expire in <strong>10 minutes</strong>.
                        </p>

                        <p style='margin:0 0 20px; font-size:14px; color:#374151;'>
                            If you did not attempt to log in, please secure your account immediately.
                        </p>

                        <hr style='border:none; border-top:1px solid #e5e7eb; margin:24px 0;'>

                        <p style='margin:0; font-size:12px; color:#6b7280;'>
                            For your security, never share this code with anyone.
                        </p>

                    </td>
                </tr>

                <!-- FOOTER -->
                <tr>
                    <td style='background:#f9fafb; padding:16px; text-align:center;'>
                        <p style='margin:0; font-size:12px; color:#6b7280;'>
                            © ".date('Y')." Your Company · Security Team
                        </p>
                    </td>
                </tr>

            </table>

        </td>
    </tr>
</table>

</body>
</html>
";


        /* =========================
           PLAIN TEXT FALLBACK
        ========================== */
        $mail->AltBody = "Hello {$name},

Your login verification code is: {$otp}

This code expires in 10 minutes.

If this wasn’t you, please secure your account.";

        $mail->send();

    } catch (Exception $e) {
        error_log("OTP Email Error: {$mail->ErrorInfo}");
        error_log("Exception: {$e->getMessage()}");

        echo "
        <script>
            alert(\"We’re having trouble sending emails. Please try again in a moment.\");
            window.location.href = '../sign-in.php';
        </script>
        ";
        exit;
   }
}






function sendEmailToAdmins(
    mysqli $mysqli,
    int $company_id,
    string $subject,
    string $htmlBody,
    string $replyToEmail = null,
    string $replyToName = null
): bool {

    // Fetch admin emails
    $stmt = $mysqli->prepare("
        SELECT email, name
        FROM users
        WHERE company_id = ?
          AND role = 'admin'
          AND email_verified = '1'
    ");
    $stmt->bind_param("i", $company_id);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows === 0) {
        return false; // No admins found
    }

    $mail = new PHPMailer(true);

    try {
        // SMTP settings (reuse your existing config)
        $mail->isSMTP();
        $mail->Host       = 'smtppro.zoho.com';
        $mail->SMTPAuth   = true;
        $mail->Username   = 'docsupport@docadvisory.com';
        $mail->Password   = 'DegitechSolutions@2025'; // move to env later
        $mail->SMTPSecure = 'ssl';
        $mail->Port       = 465;

        $mail->setFrom('docsupport@docadvisory.com', 'Invoice360 Support');

        // Reply-To (optional)
        if ($replyToEmail) {
            $mail->addReplyTo($replyToEmail, $replyToName ?? $replyToEmail);
        }

        // Add all admins as recipients
        while ($row = $result->fetch_assoc()) {
            $mail->addAddress($row['email'], $row['name'] ?? '');
        }

        // Email content
        $mail->isHTML(true);
        $mail->Subject = $subject;
        $mail->Body    = $htmlBody;
        $mail->AltBody = strip_tags($htmlBody);

        $mail->send();
        return true;

    } catch (Exception $e) {
        error_log('Admin mail error: ' . $mail->ErrorInfo);
        return false;
    }
}



?>