<?php
declare(strict_types=1);

/**
 * GetSolarPV actions endpoint
 * - Accepts POST form data (x-www-form-urlencoded)
 * - Adds CORS support so it can be called from the static site
 * - Fixes duplicate mail() and variable clobbering
 */

// ---- CORS (adjust if you call from more than one origin) ----
$allowedOrigins = [
    'https://getsolarpv.com',
    'https://www.getsolarpv.com',
];

$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
if ($origin && in_array($origin, $allowedOrigins, true)) {
    header("Access-Control-Allow-Origin: {$origin}");
    header("Vary: Origin");
}
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");
header("X-Content-Type-Options: nosniff");

if (($_SERVER['REQUEST_METHOD'] ?? '') === 'OPTIONS') {
    http_response_code(204);
    exit;
}

if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
    http_response_code(405);
    echo "Method Not Allowed";
    exit;
}

$action = $_POST['action'] ?? '';
$adminEmails = 'matt@pstructures.com, james@getmeaboiler.com';

// ---------- Helpers ----------
function test_input(string $data): string {
    $data = trim($data);
    $data = stripslashes($data);
    return htmlspecialchars($data, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

function send_html_mail(string $to, string $subject, string $html, string $from): bool {
    $headers  = "MIME-Version: 1.0\r\n";
    $headers .= "Content-type:text/html;charset=UTF-8\r\n";
    $headers .= "From: <{$from}>\r\n";
    return mail($to, $subject, $html, $headers);
}

// ---------- Actions ----------
if ($action === 'message') {

// --------------------
// CUSTOMER EMAIL (patched)
// --------------------
$toCustomer = trim($_POST['email'] ?? '');
$subjectCustomer = "Thanks for Getting a Quote with Get Solar PV";
$messageCustomer = "<html><body>
<p>Hi {$name},</p>
<p>We received your quote request and one of our installers will be in touch shortly.</p>
</body></html>";

// Validate recipient
if ($toCustomer === '' || !filter_var($toCustomer, FILTER_VALIDATE_EMAIL)) {
    print_r(['Invalid customer email address', $toCustomer]);
    exit;
}

// Headers
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type:text/html;charset=UTF-8\r\n";
$headers .= "From: <messages@getsolarpv.com>\r\n";

// Send
$okCustomer = mail($toCustomer, $subjectCustomer, $messageCustomer, $headers);

if ($okCustomer === false) {
    print_r(['Customer Email Not Sent', 'to' => $toCustomer]);
    exit;
}
// --------------------
// END CUSTOMER EMAIL
// --------------------
    // Admin email
    $html = "
    <html><head><title>New Contact Form</title></head><body>
    <p>You have received a new message from GetSolarPV. The details are below:</p>
    <table>
        <tr><th>Name</th><td>" . ($_POST['name'] ?? '') . "</td></tr>
        <tr><th>Email</th><td>" . ($_POST['email'] ?? '') . "</td></tr>
        <tr><th>Subject</th><td>" . ($_POST['subject'] ?? '') . "</td></tr>
        <tr><th>Message</th><td>" . ($_POST['message'] ?? '') . "</td></tr>
    </table>
    </body></html>";

    send_html_mail($adminEmails, "New Message Received from GetSolarPV.Com", $html, "messages@getsolarpv.com");

    echo "1";
    exit;
}

if ($action === 'tradePartner') {

    // Partner email
    $name = $_POST['name'] ?? '';
    $to = $_POST['email'] ?? '';

    $htmlCustomer = "
    <html><head><title>Thanks for getting in touch with us!</title></head><body>
    <p>Dear {$name},</p>
    <p>We have received your registration and will be in touch shortly to discuss your requirements.</p>
    <p>If you require further assistance, please give us a call free on 0800 292 6072.</p>
    <p>Many thanks,</p>
    <p>The GetSolarPV Team</p>
    </body></html>";

    send_html_mail($to, "Thanks for Registering with Getsolarpv.com", $htmlCustomer, "messages@getsolarpv.com");

    // Admin email
    $htmlAdmin = "
    <html><head><title>New Partner Request</title></head><body>
    <p>You have received a new partner request form from GetSolarPV. The details are below:</p>
    <table>
        <tr><th>Name</th><td>" . ($_POST['name'] ?? '') . "</td></tr>
        <tr><th>Business</th><td>" . ($_POST['business'] ?? '') . "</td></tr>
        <tr><th>Email</th><td>" . ($_POST['email'] ?? '') . "</td></tr>
        <tr><th>Telephone</th><td>" . ($_POST['telephone'] ?? '') . "</td></tr>
        <tr><th>Additional Details</th><td>" . ($_POST['additional'] ?? '') . "</td></tr>
    </table>
    </body></html>";

    send_html_mail($adminEmails, "New Partner Request from GetSolarPV.Com", $htmlAdmin, "messages@getsolarpv.com");

    echo "0";
    exit;
}

if ($action === 'quoteRequest') {

    $errors = [];

    $name = test_input((string)($_POST["name"] ?? ''));
    $email = test_input((string)($_POST["email"] ?? ''));
    $postcode = test_input((string)($_POST["postcode"] ?? ''));
    $telephone = test_input((string)($_POST["telephone"] ?? ''));

    if ($name === '') $errors[] = "Name is required";
    if ($email === '') $errors[] = "Email is required";
    if ($postcode === '') $errors[] = "Postcode is required";
    if ($telephone === '') $errors[] = "Telephone is required";

    if ($name !== '' && !preg_match("/^[a-zA-Z ]*$/", $name)) $errors[] = "Only letters and white space allowed";
    if ($email !== '' && !filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = "Invalid email format";
    if ($postcode !== '' && !preg_match("/([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9][A-Za-z]?))))\s?[0-9][A-Za-z]{2})/", $postcode)) {
        $errors[] = "Invalid Postcode";
    }
    if ($telephone !== '' && !preg_match("/^(?:0|\+?44)(?:\d\s?){9,10}$/", $telephone)) $errors[] = "Invalid Phone Number";

    if (!empty($errors)) {
        // Keep legacy behaviour (print_r array) so frontend doesn’t break
        print_r($errors);
        exit;
    }

// --------------------
// CUSTOMER EMAIL (patched)
// --------------------
$toCustomer = trim($_POST['email'] ?? '');
$subjectCustomer = "Thanks for Getting a Quote with Get Solar PV";
$messageCustomer = "<html><body>
<p>Hi {$name},</p>
<p>We received your quote request and one of our installers will be in touch shortly.</p>
</body></html>";

// Validate recipient
if ($toCustomer === '' || !filter_var($toCustomer, FILTER_VALIDATE_EMAIL)) {
    print_r(['Invalid customer email address', $toCustomer]);
    exit;
}

// Headers
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type:text/html;charset=UTF-8\r\n";
$headers .= "From: <messages@getsolarpv.com>\r\n";

// Send
$okCustomer = mail($toCustomer, $subjectCustomer, $messageCustomer, $headers);

if ($okCustomer === false) {
    print_r(['Customer Email Not Sent', 'to' => $toCustomer]);
    exit;
}
// --------------------
// END CUSTOMER EMAIL
// --------------------
    // Admin email
    $messageAdmin = "
    <html><head><title>New Quote Request</title></head><body>
    <p>You have received a new quote request form from GetSolarPV. The details are below:</p>
    <table>
        <tr><th>Name</th><td>" . ($_POST['name'] ?? '') . "</td></tr>
        <tr><th>PostCode</th><td>" . ($_POST['postcode'] ?? '') . "</td></tr>
        <tr><th>Email</th><td>" . ($_POST['email'] ?? '') . "</td></tr>
        <tr><th>Telephone</th><td>" . ($_POST['telephone'] ?? '') . "</td></tr>
        <tr><th>Looking For</th><td>" . ($_POST['lookingFor'] ?? '') . "</td></tr>
        <tr><th>Type of Quote</th><td>" . ($_POST['type'] ?? '') . "</td></tr>
        <tr><th>Type of Home</th><td>" . ($_POST['homeType'] ?? '') . "</td></tr>
        <tr><th>Timescale</th><td>" . ($_POST['timeScale'] ?? '') . "</td></tr>
    </table>
    </body></html>";

    $okAdmin = send_html_mail($adminEmails, "New Quote Request from Get Solar PV", $messageAdmin, "messages@getsolarpv.com");
    if (!$okAdmin) {
        print_r(['Admin Email Not Sent']);
        exit;
    }

    // Zapier webhook
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://hooks.zapier.com/hooks/catch/11422293/uqj5utu/");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $_POST);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = json_decode((string)curl_exec($ch), true);
    curl_close($ch);

    if (is_array($result) && ($result['status'] ?? '') === 'success') {
        echo "OK";
    } else {
        echo "There was an error with your Quote Request. We are aware of the issue and will be in contact shortly. This will not affect your service.";
    }

    // Facebook Conversion API (token via env)
    $fbToken = getenv('FB_ACCESS_TOKEN') ?: '';
    if ($fbToken !== '' && !empty($_POST['email'])) {
        $data = [
            'data' => [[
                'event_name' => 'Lead',
                'event_time' => time(),
                'action_source' => 'website',
                'user_data' => [
                    'em' => [hash('sha256', $_POST['email'])]
                ],
            ]]
        ];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://graph.facebook.com/v16.0/664496558030515/events?access_token=" . urlencode($fbToken));
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type:application/json']);
        curl_exec($ch);
        curl_close($ch);
    }

    exit;
}

// Unknown action
http_response_code(400);
echo "Unknown action";
exit;
