<?php
function sendSGEmail($fname, $lname, $site, $customerEmail) {
    $sgAPI = "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"; 

    $subject = "Export All Wishlists (Pro)";

    $contentHTML = "

        <p>A new request has been submitted for <strong>Export All Wishlists (Pro)</strong>. The details are below:</p>
        <p><strong>First Name:</strong> {$fname}</p>
        <p><strong>Last Name:</strong> {$lname}</p>
        <p><strong>Email:</strong> {$customerEmail}</p>
        <p><strong>Site URL:</strong> {$site}</p>
        <br/>
        <p>Regards,<br/>Support System</p>
    ";

    $params = [
        "personalizations" => [[
            "to" => [[ "email" => "ali@webecommercepros.com" ]],
            "subject" => $subject
        ]],
        "content" => [[
            "type" => "text/html",
            "value" => $contentHTML
        ]],
        "from" => [
            "email" => "no-reply@webecommercepros.com", 
            "name"  => "Web Ecommerce Pros Support"
        ],
        "reply_to" => [
            "email" => $customerEmail,
            "name"  => $fname . " " . $lname
        ]
    ];

    $curl = curl_init();
    curl_setopt_array($curl, [
        CURLOPT_URL => "https://api.sendgrid.com/v3/mail/send",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => json_encode($params),
        CURLOPT_HTTPHEADER => [
            "Authorization: Bearer " . $sgAPI,
            "Content-Type: application/json"
        ],
    ]);

    $response = curl_exec($curl);
    $err = curl_error($curl);
    curl_close($curl);

    if ($err) {
        return ["status" => "error", "message" => $err];
    } else {
        return ["status" => "success", "message" => $response];
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $fname  = $_POST['fname'] ?? '';
    $lname  = $_POST['lname'] ?? '';
    $site   = $_POST['site'] ?? '';
    $email  = $_POST['email'] ?? '';

    $result = sendSGEmail($fname, $lname, $site, $email);
    echo json_encode($result);
    exit;
}

echo json_encode(["status" => "error", "message" => "Invalid request"]);
exit;
?>