<?php
session_start();
include "include.php";

$result = array('error' => 1, 'error_msg' => 'Something went wrong');

if(isset($_POST['updte']) && $_POST['updte'] == 1) {
    $template_id = mysqli_real_escape_string(connect_database(), $_POST['template_id']);
    $template_message = mysqli_real_escape_string(connect_database(), $_POST['template_message']);
    $is_active = isset($_POST['is_active']) ? intval($_POST['is_active']) : 0;

    if(empty($template_message)) {
        $result['error'] = 1;
        $result['error_msg'] = 'Template message cannot be empty';
    } else {
        $sql = "UPDATE whatsapp_templates SET
                template_message = '$template_message',
                is_active = $is_active,
                updated_at = NOW()
                WHERE id = $template_id";

        if(setXbyY($sql) !== false) {
            $result['error'] = 0;
            $result['error_msg'] = 'Template saved successfully!';
        } else {
            $result['error'] = 1;
            $result['error_msg'] = 'Failed to save template';
        }
    }
}

echo json_encode($result);
?>
