<?php
require __DIR__ . '/vendor/autoload.php';
require __DIR__ . '/functions/helper.php';

session_start();

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

$mail = new PHPMailer(true);
$secret = variables()["recaptcha"]["secret"];

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    if (!empty($_POST['g-recaptcha-response'])) {
        $recaptcha = new ReCaptcha($secret);
        $resp = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);

        if ($resp->isSuccess()) {
        } else {
            $_SESSION['error'] = 'Invalid reCAPTCHA!';
            header('Location: ' . $_SERVER['HTTP_REFERER']);
            exit;
        }
    } else {
        $_SESSION['error'] = 'Invalid reCAPTCHA!';
        header('Location: ' . $_SERVER['HTTP_REFERER']);
        exit;
    }

    try {
        // Konfigurasi server SMTP
        $mail->isSMTP();
        $mail->Host       = 'mail.kiranabaliwisata.com';
        $mail->SMTPAuth   = true;
        $mail->SMTPSecure = 'ssl';
        $mail->Port       = 465;
        $mail->Username   = 'webprogrammer2@kiranabaliwisata.com';
        $mail->Password   = '%KrnSyLj157#';

        // Pengirim & Penerima
        $mail->setFrom('webprogrammer2@kiranabaliwisata.com', 'Booknpay');
        $mail->addAddress('anik@kiranabaliwisata.com', 'Admin Booknpay'); // Set ini ke admin penerima email ya mbok onix

        // Konten Email
        $mail->isHTML(true);
        $mail->Subject = 'Email from Website';
        $mail->Body    = '<p>Nama: ' . $_POST['first-name'] . ' ' . $_POST['last-name'] . '</p>
        <p>Email: ' . $_POST['email'] . '</p>
        <p>Pesan: ' . $_POST['message'] . '</p>';

        $mail->send();
        $_SESSION['success'] = 'Successfully sent email!';
        header('Location: ' . $_SERVER['HTTP_REFERER']);
        exit;
    } catch (Exception $e) {
        $_SESSION['error'] = 'Failed to send email!';
        header('Location: ' . $_SERVER['HTTP_REFERER']);
        exit;
    }
}
