<?php
require('../config.php');
header('Content-Type: application/json');


if (!$db) {
    echo json_encode(['status' => 'error', 'message' => 'Database connection failed']);
    exit;
}

// Validate template_id
if (!isset($_GET['template_id']) || empty($_GET['template_id']) || !is_numeric($_GET['template_id'])) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid or missing template_id']);
    exit;
}

$template_id = (int)$_GET['template_id'];

// Fetch template details securely
$sql = "SELECT * FROM client_templates WHERE id = ?";
$sql_btn_query = "SELECT * FROM template_buttons WHERE template_id = ?";

// Prepare and execute template query for specific template
$stmt = mysqli_prepare($db, $sql);
mysqli_stmt_bind_param($stmt, "i", $template_id);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);

// prepare and execute query to fetch template buttons
$stmt_btn = mysqli_prepare($db, $sql_btn_query);
mysqli_stmt_bind_param($stmt_btn, 'i', $template_id);
mysqli_stmt_execute($stmt_btn);
$btn_result = mysqli_stmt_get_result($stmt_btn);

$row = mysqli_fetch_assoc($result);
$temp_btn = [];

while($btn_row = mysqli_fetch_assoc($btn_result)){
    $temp_btn[] = $btn_row;
}

if ($row) {
    $row['template_buttons'] = $temp_btn ?: []; // Handle no buttons gracefully
    echo json_encode(['status' => 'success', 'data' => $row]);
} else {
    echo json_encode(['status' => 'error', 'message' => 'Template not found']);
}

mysqli_stmt_close($stmt);
mysqli_close($db);
?>
