<?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 = ['destination','start_date','package','persons'];
foreach ($required as $field) {
    if (empty($_POST[$field])) {
        echo json_encode(["status"=>"failed","message"=>"All fields required"]);
        exit;
    }
}

$destination = htmlspecialchars($_POST['destination']);
$start_date  = htmlspecialchars($_POST['start_date']);
$package     = htmlspecialchars($_POST['package']);
$persons     = htmlspecialchars($_POST['persons']);

$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_STARTTLS;
    $mail->Port       = 587;

    $mail->SMTPOptions = [
        'ssl' => [
            'verify_peer' => false,
            'verify_peer_name' => false,
            'allow_self_signed' => true,
        ],
    ];

    // TEMP DEBUG
    // $mail->SMTPDebug = 2;

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

    $mail->isHTML(true);
    $mail->Subject = "New Package Enquiry";

    $mail->Body = "
        <h3>New Package Enquiry</h3>
        <table cellpadding='6'>
            <tr><td><b>Destination</b></td><td>$destination</td></tr>
            <tr><td><b>Start Date</b></td><td>$start_date</td></tr>
            <tr><td><b>Package</b></td><td>$package</td></tr>
            <tr><td><b>Persons</b></td><td>$persons</td></tr>
        </table>
    ";

    $mail->send();

    echo json_encode([
        "status"=>"success",
        "message"=>"Enquiry sent successfully!"
    ]);

} catch (Exception $e) {
    echo json_encode([
        "status"=>"failed",
        "message"=>$mail->ErrorInfo
    ]);
}
