<?php
require_once('Mailer.php');

$mailer = new Mailer();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST["type"])) {
        $type = $_POST["type"] ?? null;

        if (!empty($type)) {
            $fileName = "";
            $data = "";
            $toEmail = "";
            $toName = "";
            $subject = "";
            $htmlBody = "";

            switch ($type) {
                case 'bookingInfo':
                    $fileName = "booking_info.php";

                    $id = (int) (isset($_POST["id"]) ? $_POST["id"] : 0);
                    if ($id > 0) {
                        if (!file_exists($fileName)) {
                            echo json_encode([
                                "status" => "error",
                                "message" => "Email template not found."
                            ]);
                            exit;
                        }

                        ob_start();
                        include $fileName;
                        $htmlBody = ob_get_clean();

                        $toEmail = $data["email"];
                        $toName = $data["client_name"];
                        $subject = "Booking Information ($id)";
                    }
                    break;
                
                default:
                    # code...
                    break;
            }

            if (!filter_var($data["email"], FILTER_VALIDATE_EMAIL)) {
                echo json_encode([
                    "status" => "error",
                    "message" => "Invalid email address: " . $data["email"]
                ]);
                exit;
            }

            $flag = $mailer->SendEmail($toEmail, $toName, $subject, $htmlBody);

            echo json_encode([
                "status" => $flag ? "success" : "error",
                "message" => $flag ? "Email sent successfully." : "Failed to send email."
            ]);
        }

    }
} else {
    http_response_code(400);
    echo json_encode([
        "status" => "error",
        "message" => "Invalid request or missing parameters."
    ]);
}