<?php

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

require 'vendor/autoload.php';
header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(["status" => "failed", "message" => "Invalid request"]);
    exit;
}

$required = ['car', 'name', 'phone', 'trip_date', 'days', 'message'];

foreach ($required as $f) {
    if (empty($_POST[$f])) {
        echo json_encode(["status" => "failed", "message" => "All fields are required"]);
        exit;
    }
}

$car      = htmlspecialchars(trim($_POST['car']));
$name     = htmlspecialchars(trim($_POST['name']));
$phone    = htmlspecialchars(trim($_POST['phone']));
$tripDate = htmlspecialchars(trim($_POST['trip_date']));
$days     = htmlspecialchars(trim($_POST['days']));
$message  = nl2br(htmlspecialchars(trim($_POST['message'])));

if (!preg_match('/^\d{10,15}$/', $phone)) {
    echo json_encode(["status" => "failed", "message" => "Invalid phone number"]);
    exit;
}

$mail = new PHPMailer(true);

try {
    $mail->isSMTP();
    $mail->Host       = 'mail.clouddreamstech.in';
    $mail->SMTPAuth   = true;
    $mail->Username   = 'info@clouddreamstech.in';
    $mail->Password   = 'y&Zvy.r2BFX8EQTn';
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
    $mail->Port       = 465;

    $mail->setFrom('info@clouddreamstech.in', 'MR.Taxi');
    $mail->addAddress('gokulnath@clouddreams.in');

    $mail->isHTML(true);
    $mail->Subject = "New Car Booking Request - $name";
    $mail->Body = "
        <h3>New Car Booking Request</h3>
        <p><b>Car:</b> $car</p>
        <p><b>Name:</b> $name</p>
        <p><b>Phone:</b> $phone</p>
        <p><b>Trip Date:</b> $tripDate</p>
        <p><b>Days:</b> $days</p>
        <p><b>Message:</b><br>$message</p>
    ";   // SSL options (recommended for shared hosting)
    $mail->SMTPOptions = [
        'ssl' => [
            'verify_peer'       => false,
            'verify_peer_name'  => false,
            'allow_self_signed' => true,
        ],
    ];

    $mail->send();
    echo json_encode(["status" => "success", "message" => "Booking sent successfully"]);
} catch (Exception $e) {
    error_log($mail->ErrorInfo);
    echo json_encode(["status" => "failed", "message" => "Failed to send booking"]);
}
