<?php
include_once "../global.php";

$pageTitle = 'Add New Template - ';
include_once '../header.php';
?>

<!--breadcrumb-->
<div class="page-breadcrumb d-none d-sm-flex align-items-center mb-3">
    <div class="breadcrumb-title pe-3">WhatsApp Management</div>
    <div class="ps-3">
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb mb-0 p-0">
                <li class="breadcrumb-item"><a href="javascript:;"></a>
                </li>
                <li class="breadcrumb-item active" aria-current="page">Add New Template</li>
            </ol>
        </nav>
    </div>
</div>
<!--end breadcrumb-->
<div class="card">
    <div class="card-body p-4">
        <h5 class="mb-4">Add New Template</h5>
        <form id="tplForm" class="row g-3" method="post">
            <div class="col-md-12">
                <label for="tpl_name" class="form-label">Name <span>*</span></label>
                <input type="text" name="name" id="tpl_name" class="form-control" required>
            </div>
            <div class="col-md-12">
                <label for="tpl_body" class="form-label">Body</label>
                <textarea class="form-control" id="tpl_body" name="body"
                    placeholder="Hello {{name}}, thanks for contacting us!" rows="4" required></textarea>
            </div>
            <div class="col-md-12">
                <button type="submit" class="btn btn-grd-primary px-4">Submit</button>
            </div>
        </form>
    </div>
</div>

<script>
    $("#tplForm").submit(function(e) {
        e.preventDefault();
        var formData = new FormData(this);

        $.ajax({
            url: '<?php echo WEB_URL; ?>/ajax_call?page=saveWaTemplate',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            dataType: 'json',
            beforeSend: function() {
                $("#spinner-overlay").fadeIn('slow');
            },
            success: function(response) {
                showAlert(response.message);
                if (response.status === "success") {
                    setTimeout(() => {
                        window.location.href = '<?php echo WEB_URL; ?>/whatsapp/whatsapp_templates';
                    }, 1000);
                }
            },
            error: function(xhr, status, errorThrown) {
                console.log(xhr.responseText);
            },
            complete: function() {
                $("#spinner-overlay").fadeOut('slow');
            }
        });
    });
</script>

<?php
include_once '../footer.php';
?>