<?php
include '../db_connect.php';
require '../vendor/autoload.php';

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

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = mysqli_real_escape_string($conn, $_POST['name']);
    $email = mysqli_real_escape_string($conn, $_POST['email']);
    $message = mysqli_real_escape_string($conn, $_POST['message']);

    $sql = "INSERT INTO sidebar_bookings (name, email, message) VALUES ('$name', '$email', '$message')";

    if (mysqli_query($conn, $sql)) {
        // ✅ Send email to you
        $mail = new PHPMailer(true);

        try {
            $mail->isSMTP();
            $mail->Host = 'smtp.gmail.com';
            $mail->SMTPAuth = true;
            $mail->Username = 'benjamindanieljr11@gmail.com'; // your Gmail
            $mail->Password = 'tvvvkzlylfgdmcys'; // Gmail App Password
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
            $mail->Port = 587;

            $mail->setFrom('benjamindanieljr11@gmail.com', 'Zemaraim Technology');
            $mail->addAddress('benjamindanieljr11@gmail.com'); // send to yourself

            $mail->isHTML(true);
            $mail->Subject = "New Booking Request - Zemaraim Technology";
            $mail->Body = "
                <h2>New Booking Received</h2>
                <p><strong>Name:</strong> {$name}</p>
                <p><strong>Email:</strong> {$email}</p>
                <p><strong>Message:</strong> {$message}</p>
                <p><strong>Submitted On:</strong> " . date('Y-m-d H:i:s') . "</p>
            ";

            $mail->send();
        } catch (Exception $e) {
            error_log('Email Error: ' . $mail->ErrorInfo);
        }

        echo "<script>alert('Booking request sent successfully!'); window.location.href='../frontend/checkout.php';</script>";
    } else {
        echo "Error: " . mysqli_error($conn);
    }
}
?>
