<?php
require_once('Mailer.php');
require_once('../db/model.php');

$mailer = new Mailer();
$db = new Model();

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

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

            switch ($t) {
                case 'bookingInfo':
                    $id = (int) (isset($_POST["id"]) ? $_POST["id"] : 0);
                    if ($id > 0) {
                        $data = $db->GetEventById($id);

                        if (!$data) {
                            echo json_encode([
                                "status" => "error",
                                "message" => "No found any data with this ID."
                            ]);
                            exit;
                        }

                        if (!file_exists('booking_info.php')) {
                            echo json_encode([
                                "status" => "error",
                                "message" => "Email template not found."
                            ]);
                            exit;
                        }

                        ob_start();
                        include 'booking_info.php';
                        $htmlBody = ob_get_clean();

                        // $toEmail = $data["email"];
                        $toEmail = 'shakikulislam625010@gmail.com';
                        $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."
    ]);
}