<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Allow-Headers: Content-Type");
header('Content-Type: application/json');

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

require __DIR__ . '/PHPMailer/Exception.php';
require __DIR__ . '/PHPMailer/PHPMailer.php';
require __DIR__ . '/PHPMailer/SMTP.php';

// Configuration
$SMTP_HOST = 'premium133.web-hosting.com';
$SMTP_PORT = 465;
$SMTP_USER = 'info@ghadget.com';
$SMTP_PASS = 'Ogaminan2####';
$FROM_EMAIL = 'info@ghadget.com';
$FROM_NAME  = 'GadgetGo Security';

// Simple Logging
function log_msg($msg)
{
    $logFile = __DIR__ . "/mail_log.txt";
    file_put_contents($logFile, date('Y-m-d H:i:s') . " - " . $msg . "\n", FILE_APPEND);
}

// Main Sending Wrapper
function get_email_template($subject, $bodyContent)
{
    return "
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset='UTF-8'>
        <title>$subject</title>
        <style>
            body { font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; background-color: #f4f6f8; margin: 0; padding: 0; }
            .container { max-width: 600px; margin: 40px auto; background-color: #ffffff; border-radius: 16px; overflow: hidden; box-shadow: 0 4px 12px rgba(0,0,0,0.05); }
            .header { background-color: #ffffff; padding: 30px 40px; text-align: center; border-bottom: 1px solid #edf2f7; }
            .logo { font-size: 24px; font-weight: 800; color: #135bec; text-transform: uppercase; letter-spacing: -1px; }
            .content { padding: 40px; color: #4a5568; line-height: 1.6; }
            .content h1 { font-size: 24px; color: #2d3748; margin-bottom: 20px; text-align: center; }
            .content p { margin-bottom: 20px; font-size: 16px; }
            .otp-box { background-color: #ebf8ff; color: #2b6cb0; font-size: 32px; font-weight: bold; letter-spacing: 5px; text-align: center; padding: 20px; border-radius: 12px; margin: 30px 0; border: 1px dashed #bee3f8; }
            .footer { background-color: #f7fafc; padding: 30px; text-align: center; color: #a0aec0; font-size: 12px; border-top: 1px solid #edf2f7; }
            .footer p { margin: 5px 0; }
            .btn { display: inline-block; background-color: #135bec; color: #ffffff !important; padding: 14px 28px; text-decoration: none; border-radius: 8px; font-weight: bold; margin-top: 20px; transition: background-color 0.3s; }
            .btn:hover { background-color: #0f4bcc; }
        </style>
    </head>
    <body>
        <div class='container'>
            <div class='header'>
                <div class='logo'>GadgetGo</div>
            </div>
            <div class='content'>
                $bodyContent
            </div>
            <div class='footer'>
                <p>&copy; " . date('Y') . " GadgetGo. All rights reserved.</p>
                <p>Abuja, Nigeria • support@ghadget.com</p>
                <p>You received this email because you signed up on GadgetGo.</p>
            </div>
        </div>
    </body>
    </html>";
}

function send_gadget_email($to, $subject, $htmlBody)
{
    global $SMTP_HOST, $SMTP_PORT, $SMTP_USER, $SMTP_PASS, $FROM_EMAIL, $FROM_NAME;

    $mail = new PHPMailer(true);
    $finalBody = get_email_template($subject, $htmlBody); // Wrap content

    try {
        // Server settings
        // $mail->SMTPDebug = SMTP::DEBUG_SERVER;
        $mail->isSMTP();
        $mail->Host       = $SMTP_HOST;
        $mail->SMTPAuth   = true;
        $mail->Username   = $SMTP_USER;
        $mail->Password   = $SMTP_PASS;
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
        $mail->Port       = $SMTP_PORT;

        // Recipients
        $mail->setFrom($FROM_EMAIL, $FROM_NAME);
        $mail->addAddress($to);

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

        $mail->send();
        log_msg("Email sent successfully to $to");
        return true;
    } catch (Exception $e) {
        $errorMsg = "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
        log_msg($errorMsg);

        // Fallback
        $headers  = "MIME-Version: 1.0" . "\r\n";
        $headers .= "Content-type: text/html; charset=utf-8" . "\r\n";
        $headers .= "From: $FROM_NAME <$FROM_EMAIL>" . "\r\n";

        if (mail($to, $subject, $finalBody, $headers)) {
            log_msg("Fallback mail() success.");
            return true;
        } else {
            log_msg("Fallback mail() failed.");
            return $errorMsg;
        }
    }
}

// --- API ENTRY POINT (Only run if accessed directly) ---
if (basename($_SERVER['PHP_SELF']) == 'mail.php') {
    if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
        http_response_code(200);
        exit;
    }

    $input = json_decode(file_get_contents('php://input'), true);
    if (!$input || !isset($input['type'])) {
        return;
    }

    $type = $input['type'];
    $data = $input['data'] ?? [];
    $toEmail = $data['userEmail'] ?? 'info@ghadget.com';

    // Content Builders
    $subject = "Notification";
    $body = "Content";

    if ($type === 'otp') {
        // Legacy OTP Handler (Can ideally remove or keep for older requests?)
        // Let's keep distinct
        $subject = "Verify GadgetGo Account";
        $code = $data['otp'] ?? '000000';
        $body = "<h2>Your OTP Code</h2><p>Here is your code:</p><h1>$code</h1>";
    } elseif ($type === 'login') {
        $subject = "New Login Detected";
        $username = $data['user']['username'] ?? 'User';
        $body = "<p>User <strong>$username</strong> just logged in.</p>";
    } elseif ($type === 'message') {
        $subject = "New Message";
        $body = "<p>You have a new message on GadgetGo.</p>";
    }

    // Send
    $res = send_gadget_email($toEmail, $subject, $body);
    if ($res === true) {
        echo json_encode(['status' => 'success']);
    } else {
        echo json_encode(['status' => 'error', 'message' => $res]);
    }
}
