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

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

// Read JSON input
$postData = json_decode(file_get_contents('php://input'), true); 

// Check if JSON is valid
if (json_last_error() !== JSON_ERROR_NONE) {
    http_response_code(400);
    echo json_encode(['status' => 'error', 'message' => 'Invalid JSON input']);
    exit;
}

// Validate input
if (empty($postData['clientId']) || !is_numeric($postData['clientId'])) {
    http_response_code(400);
    echo json_encode(['status' => 'error', 'message' => 'Invalid or missing clientId']);
    exit;
}

if (empty($postData['recordId']) || !is_numeric($postData['recordId'])) {
    http_response_code(400);
    echo json_encode(['status' => 'error', 'message' => 'Invalid or missing recordId']);
    exit;
}

// Sanitize input
$clientId = (int) $postData['clientId'];
$recordId = (int) $postData['recordId'];

// Prepare DELETE statement to prevent SQL injection
$deleteQuery = "DELETE FROM client_templates WHERE id = ? AND client_id = ?";
$stmt = mysqli_prepare($db, $deleteQuery);

if ($stmt) {
    mysqli_stmt_bind_param($stmt, "ii", $recordId, $clientId);
    mysqli_stmt_execute($stmt);

    if (mysqli_stmt_affected_rows($stmt) > 0) {
        http_response_code(200);
        echo json_encode(['status' => 'success', 'message' => 'Template deleted successfully']);
    } else {
        http_response_code(404);
        echo json_encode(['status' => 'error', 'message' => 'Template not found']);
    }

    mysqli_stmt_close($stmt);
} else {
    http_response_code(500);
    echo json_encode(['status' => 'error', 'message' => 'Query preparation failed']);
}

// Close database connection
mysqli_close($db);
?>
