<?php
header('Content-Type: application/json');

$config = require __DIR__ . '/phpmailer/mailer_config.php';


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

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

$mail = new PHPMailer(true);

function sendEmail($to, $subject, $body)
{
    $logFile = __DIR__ . '/log.txt';
    global $mail, $config;

    try {
        $mail->IsSMTP();
        $mail->Host = $config['smtp_host'];
        $mail->SMTPAuth = $config['smtp_auth'];
        $mail->Username = $config['smtp_username'];
        $mail->Password = $config['smtp_password'];
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;

        $mail->Port = $config['smtp_port'];

        $mail->setFrom($config['sender_email'], $config['sender_name']);
        $mail->addAddress($to);

        $mail->isHTML(true);
        $mail->Subject = $subject;
        $mail->Body = $body;

        $mail->send();
        return true;
    } catch (Exception $e) {
        $errorMessage = 'Mail Error: ' . $mail->ErrorInfo . "\n" . 'Exception: ' . $e->getMessage();
        file_put_contents($logFile, $errorMessage . "\n", FILE_APPEND);
        return false;
    }
}

$response = array();

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $requestBody = file_get_contents('php://input');
    $formData = json_decode($requestBody, true);

    if (!isset($formData['g-recaptcha-response']) || empty($formData['g-recaptcha-response'])) {
        $response['status'] = 'error';
        $response['message'] = 'reCAPTCHA verification failed.';
    } else {
        $recaptcha_secret = $config['recaptcha_secret'];
        $recaptcha_response = $formData['g-recaptcha-response'];
        $url = 'https://www.google.com/recaptcha/api/siteverify';
        $data = array(
            'secret' => $recaptcha_secret,
            'response' => $recaptcha_response
        );

        $options = array(
            'http' => array(
                'header' => "Content-Type: application/x-www-form-urlencoded\r\n",
                'method' => 'POST',
                'content' => http_build_query($data)
            )
        );
        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        $responseCaptcha = json_decode($result);

        if ($responseCaptcha->success) {
            $name = $formData['name'];
            $email = $formData['email'];
            $phone = $formData['phone'];
            $subject1 = $formData['subject'];
            $message = $formData['message'];

            $to = $config['recipient_email'];
            $subject = 'New Quote Request';
            $body = "<p>Name: $name</p>";
            $body .= "<p>Email: $email</p>";
            $body .= "<p>Phone: $phone</p>";
            $body .= "<p>Subject: $subject1</p>";
            $body .= "<p>Message: $message</p>";

            $mail_sent = sendEmail($to, $subject, $body);

            if ($mail_sent) {
                $response['status'] = 'success';
                $response['message'] = 'Quote request submitted successfully.';
            } else {
                $response['status'] = 'error';
                $response['message'] = 'Failed to send email.';
            }
        } else {
            $response['status'] = 'error';
            $response['message'] = 'reCAPTCHA verification failed.';
        }
    }
} else {
    $response['status'] = 'error';
    $response['message'] = 'Invalid request method.';
}

echo json_encode($response);
