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

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

$name = $_POST['name'];
$mobile = $_POST['mobile'];
$vehicle_type = $_POST['vehicle_type'] ?? '';
$transmission = $_POST['transmission'] ?? '';
$fuel_type = $_POST['fuel_type'] ?? '';
$rental_duration = $_POST['rental_duration'] ?? '';

// Save to database
$sql = "INSERT INTO car_booking (name, mobile, vehicle_type, transmission, fuel_type, rental_duration)
        VALUES ('$name', '$mobile', '$vehicle_type', '$transmission', '$fuel_type', '$rental_duration')";

if ($conn->query($sql) === TRUE) {
    // Send email to admin
    $mail = new PHPMailer(true);

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

        // Recipients
        $mail->setFrom('benjamindanieljr11@gmail.com', 'Car Rental Website');
        $mail->addAddress('benjamindanieljr11@gmail.com', 'Car Rental Website'); // your receiving email


        // Content
        $mail->isHTML(true);
        $mail->Subject = 'New Car Booking Received';
        $mail->Body    = "
            <h2>New Booking Details</h2>
            <p><strong>Name:</strong> $name</p>
            <p><strong>Mobile:</strong> $mobile</p>
            <p><strong>Vehicle Type:</strong> $vehicle_type</p>
            <p><strong>Transmission:</strong> $transmission</p>
            <p><strong>Fuel Type:</strong> $fuel_type</p>
            <p><strong>Rental Duration:</strong> $rental_duration</p>
        ";

        $mail->send();

        echo "<script>alert('Booking submitted successfully! Admin notified.'); window.location.href='../frontend/index.php';</script>";

    } catch (Exception $e) {
        echo "<script>alert('Booking saved but email failed: {$mail->ErrorInfo}'); window.location.href='../frontend/index.php';</script>";
    }

} else {
    echo "Error: " . $conn->error;
}

$conn->close();
?>
