<?php

// form-handler.php
require_once 'config.php';
require 'vendor/autoload.php'; // installed PHPMailer via Composer :composer require phpmailer/phpmailer
require 'includes/email-helper.php'; // Include the email helper

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

// Only process POST requests
if ($_SERVER["REQUEST_METHOD"] == "POST") {

    header('Content-Type: application/json');
    $errors = [];

    parse_str($_POST['formdata'], $input);

    // --- 1. Sanitize and Validate Form Inputs ---
    $name = strip_tags(trim($input["name"]));
    $email = filter_var(trim($input["email"]), FILTER_SANITIZE_EMAIL);
    $subject = strip_tags(trim($input["subject"]));
    $message = strip_tags(trim($input["message"]));



    if (empty($name)) $errors['name'] = 'Name is required.';
    if (empty($subject)) $errors['subject'] = 'Subject is required.';
    if (empty($message)) $errors['message'] = 'Message is required.';
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors['email'] = 'A valid email is required.';
    }

    // --- 2. Validate reCAPTCHA ---
    $recaptcha_secret = $_ENV['RECAPTCHA_SECRET_KEY'];
    $recaptcha_response = $input['g-recaptcha-response'];

    $verify_url = 'https://www.google.com/recaptcha/api/siteverify';
    $verify_data = http_build_query([
        'secret'   => $recaptcha_secret,
        'response' => $recaptcha_response,
        'remoteip' => $_SERVER['REMOTE_ADDR']
    ]);

    $options = ['http' => ['method'  => 'POST', 'header'  => "Content-type: application/x-www-form-urlencoded\r\n", 'content' => $verify_data]];
    $context  = stream_context_create($options);
    $verify_result = file_get_contents($verify_url, false, $context);
    $result_json = json_decode($verify_result);

    if (!$result_json->success) {
        $errors['recaptcha'] = 'reCAPTCHA verification failed. Please try again.';
    }

    // --- 3. Send Emails if No Errors ---
    if (empty($errors)) {
        // Initialize PHPMailer
        $mail = new PHPMailer(true);

        try {
            // Server settings
            $mail->isSMTP();
            $mail->Host = $_ENV['SMTP_HOST'];
            $mail->SMTPAuth = true;
            $mail->Username = $_ENV['SMTP_USERNAME'];
            $mail->Password = $_ENV['SMTP_PASSWORD'];
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
            $mail->Port = $_ENV['SMTP_PORT'];
            $mail->isHTML(true); // Enable HTML emails

            // Prepare data for templates
            $emailData = [
                'name' => $name,
                'email' => $email,
                'subject' => $subject,
                'message' => $message
            ];


            // Send to Admin
            $mail->setFrom($_ENV['FROM_EMAIL'], $_ENV['APP_NAME'] . ' Website');
            $mail->addAddress($_ENV['ADMIN_EMAIL']);
            $mail->Subject = "New Contact Form Submission";
            $mail->Body = renderTemplate('admin-notification', $emailData);
            $mail->AltBody = "Name: $name\nEmail: $email\nSubject: $subject\nMessage: $message";
            $mail->send();

            // Reset for user email
            $mail->clearAddresses();

            // Send to User
            $mail->addAddress($email, $name);
            $mail->Subject = "Thank you for contacting us";
            $mail->Body = renderTemplate('inquiry-response', $emailData);
            $mail->AltBody = "Dear $name,\n\nThank you for contacting us. We will get back to you shortly.\n\nBest regards,\n " . $_ENV['APP_NAME'] . " Team";
            $mail->send();

            echo json_encode([
                'success' => true,
                'message' => 'Thank you! Your message has been sent successfully.'
            ]);
        } catch (Exception $e) {
            echo json_encode([
                'success' => false,
                'errors' => ['mail' => "Message could not be sent. Mailer Error: {$mail->ErrorInfo}"]
            ]);
        }
    } else {
        echo json_encode(['success' => false, 'errors' => $errors]);
    }
} else {
    // Not a POST request
    http_response_code(403);
    echo "There was a problem with your submission, please try again.";
}
