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

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

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

if(!is_array($postData) || empty($postData)){
    echo json_encode(['status'=> 'error', 'message' => 'Please provide the details']); 
    exit; 
}

// Required fields
$requiredFields = [
'clientId',
 'templateName',
  'templateCategory', 
  'templateLanguage',
   'templateType',
    'templateMediaType',
     'templateMediaContent', 
     'templateBody'];

foreach($requiredFields as $field){
    if (!isset($postData[$field]) || empty($postData[$field])) {
        echo json_encode([
            'status' => 'error',
            'message' => "Missing or empty field: $field"
        ]);
        exit;
    }
}

// Sanitize inputs
$clientId = mysqli_real_escape_string($db, $postData['clientId']);
$templateName = mysqli_real_escape_string($db, $postData['templateName']);
$templateCategory = (int) $postData['templateCategory'];
$templateLanguage = (int) $postData['templateLanguage'];
$templateType = mysqli_real_escape_string($db, $postData['templateType']);
$templateMediaType = mysqli_real_escape_string($db, $postData['templateMediaType']);
$templateBody = mysqli_real_escape_string($db, $postData['templateBody']);
$templateMediaContent = mysqli_real_escape_string($db, $postData['templateMediaContent']);
$templateFooter = isset($postData['footerMessage']) ? mysqli_real_escape_string($db, $postData['footerMessage']) : '';

// Update the existing template
$updateQuery = "UPDATE client_templates SET 
    template_category = '$templateCategory',
    template_language = '$templateLanguage',
    template_type = '$templateType',
    template_media_type = '$templateMediaType',
    template_media_content = '$templateMediaContent',
    template_body = '$templateBody',
    template_footer = '$templateFooter',
    updated_at = CURRENT_TIMESTAMP
    WHERE client_id = '$clientId' AND template_name = '$templateName'";

if (mysqli_query($db, $updateQuery)) {
    if (mysqli_affected_rows($db) > 0) {
        echo json_encode(['status' => 'success', 'message' => 'Template updated successfully']);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'No changes made or template not found']);
    }
} else {
    echo json_encode(['status' => 'error', 'message' => mysqli_error($db)]);
}

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