<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json");

include "dbconfig.php";
$conn = opencon();
if ($conn->connect_error) {
    die(json_encode(["message" => "Database connection failed"]));
}

// Fetch templates from the database
$result = $conn->query("SELECT * FROM templates");
$templates = [];

$templateFolder = "templates/";

if (!is_dir($templateFolder)) {
    mkdir($templateFolder, 0777, true); // Ensure the folder exists
}

while ($row = $result->fetch_assoc()) {
    // Create a valid HTML filename from the database "content" column
    $fileName = $row["content"];
    $filePath = $templateFolder . $fileName;

   

    // Determine the image path
    $imagePath = !empty($row["image"]) ? $templateFolder . $row["image"] : null;

    $templates[] = [
        "id" => $row["id"],
        "html_file" => $filePath,
        "image" => $imagePath
    ];
}

echo json_encode($templates);
$conn->close();
?>
