<!DOCTYPE html>
<html>
<head>
    <?php include"comman/code_css.php"; ?>
</head>

<body class="hold-transition skin-blue sidebar-mini">
<div class="wrapper">
    <?php include"sidebar.php"; ?>
    
    <div class="content-wrapper">
        <section class="content-header">
            <h1>
                Send WhatsApp Message
                <small>Compose and send WhatsApp messages</small>
            </h1>
            <ol class="breadcrumb">
                <li><a href="<?php echo $base_url; ?>dashboard"><i class="fa fa-dashboard"></i> Home</a></li>
                <li><a href="<?php echo $base_url; ?>whatsapp"><i class="fa fa-whatsapp"></i> WhatsApp</a></li>
                <li class="active">Compose Message</li>
            </ol>
        </section>

        <section class="content">
            <div class="row">
                <?php include"comman/code_flashdata.php"; ?>
                
                <div class="col-md-8">
                    <div class="box box-primary">
                        <div class="box-header with-border">
                            <h3 class="box-title">Compose WhatsApp Message</h3>
                        </div>
                        
                        <form id="whatsapp-compose-form" onkeypress="return event.keyCode != 13;">
                            <input type="hidden" name="<?php echo $this->security->get_csrf_token_name();?>" value="<?php echo $this->security->get_csrf_hash();?>">
                            <input type="hidden" id="base_url" value="<?php echo $base_url; ?>">
                            
                            <div class="box-body">
                                <div class="form-group">
                                    <label>Select Customer</label>
                                    <select class="form-control select2" name="customer_id" id="customer_id" style="width: 100%;">
                                        <option value="">Select Customer</option>
                                        <?php if(isset($customers)) { foreach($customers as $customer) { ?>
                                            <option value="<?php echo $customer->id; ?>" data-phone="<?php echo $customer->mobile; ?>">
                                                <?php echo $customer->customer_name . ' - ' . $customer->mobile; ?>
                                            </option>
                                        <?php } } ?>
                                    </select>
                                </div>

                                <div class="form-group">
                                    <label>Phone Number <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" name="phone_number" id="phone_number" 
                                           placeholder="Enter phone number with country code" required>
                                    <span id="phone_number_msg" style="display:none" class="text-danger"></span>
                                </div>

                                <div class="form-group">
                                    <label>Use Template (Optional)</label>
                                    <select class="form-control" name="template_id" id="template_id">
                                        <option value="">Select Template</option>
                                        <?php if(isset($templates)) { foreach($templates as $template) { ?>
                                            <option value="<?php echo $template->id; ?>" data-content="<?php echo htmlspecialchars($template->template_content); ?>">
                                                <?php echo $template->template_name; ?>
                                            </option>
                                        <?php } } ?>
                                    </select>
                                </div>

                                <div class="form-group">
                                    <label>Message <span class="text-danger">*</span></label>
                                    <textarea class="form-control" name="message" id="message" rows="6" 
                                              placeholder="Type your message here..." required></textarea>
                                    <span id="message_msg" style="display:none" class="text-danger"></span>
                                    <small class="text-muted">Character count: <span id="char_count">0</span></small>
                                </div>
                            </div>
                            
                            <div class="box-footer">
                                <button type="button" id="send_message" class="btn btn-success">
                                    <i class="fa fa-paper-plane"></i> Send Message
                                </button>
                                <button type="button" onclick="clear_form()" class="btn btn-default">
                                    <i class="fa fa-refresh"></i> Clear
                                </button>
                            </div>
                        </form>
                    </div>
                </div>

                <div class="col-md-4">
                    <div class="box box-info">
                        <div class="box-header with-border">
                            <h3 class="box-title">Quick Tips</h3>
                        </div>
                        <div class="box-body">
                            <ul>
                                <li>Enter phone number with country code (e.g., 91XXXXXXXXXX)</li>
                                <li>You can select a customer to auto-fill phone number</li>
                                <li>Use templates for quick message composition</li>
                                <li>Variables in templates will be replaced automatically</li>
                            </ul>
                        </div>
                    </div>

                    <div class="box box-success">
                        <div class="box-header with-border">
                            <h3 class="box-title">Available Variables</h3>
                        </div>
                        <div class="box-body">
                            <small>
                                <strong>Customer Variables:</strong><br>
                                {CUSTOMER_NAME}, {CUSTOMER_CODE}<br><br>
                                <strong>Business Variables:</strong><br>
                                {BUSINESS_NAME}, {STORE_NAME}<br>
                                {STORE_ADDRESS}, {STORE_PHONE}
                            </small>
                        </div>
                    </div>
                </div>
            </div>
        </section>
    </div>

    <?php include"footer.php"; ?>
    <div class="control-sidebar-bg"></div>
</div>

<?php include"comman/code_js_sound.php"; ?>
<?php include"comman/code_js.php"; ?>

<script type="text/javascript">
$(document).ready(function() {
    // Initialize Select2
    $('.select2').select2();

    // Auto-fill phone number when customer is selected
    $('#customer_id').change(function() {
        var selectedOption = $(this).find('option:selected');
        var phone = selectedOption.data('phone');
        if(phone) {
            $('#phone_number').val(phone);
        }
    });

    // Load template content
    $('#template_id').change(function() {
        var selectedOption = $(this).find('option:selected');
        var content = selectedOption.data('content');
        if(content) {
            $('#message').val(content);
            updateCharCount();
        }
    });

    // Character count
    $('#message').on('input', function() {
        updateCharCount();
    });

    function updateCharCount() {
        var count = $('#message').val().length;
        $('#char_count').text(count);
    }

    // Send Message
    $('#send_message').on("click", function(e) {
        e.preventDefault();
        var base_url = $("#base_url").val();
        var flag = true;

        function check_field(id) {
            if(!$("#"+id).val()) {
                $('#'+id+'_msg').fadeIn(200).show().html('Required Field').addClass('required');
                flag = false;
            } else {
                $('#'+id+'_msg').fadeOut(200).hide();
            }
        }

        check_field("phone_number");
        check_field("message");

        if(flag == false) {
            toastr["warning"]("Please fill all required fields!");
            return;
        }

        $(this).attr('disabled', true);
        $(this).html('<i class="fa fa-spinner fa-spin"></i> Sending...');
        $(".box").append('<div class="overlay"><i class="fa fa-refresh fa-spin"></i></div>');

        var formData = new FormData($('#whatsapp-compose-form')[0]);
        
        $.ajax({
            type: 'POST',
            url: base_url + 'whatsapp/send_message',
            data: formData,
            cache: false,
            contentType: false,
            processData: false,
            dataType: 'json',
            success: function(result) {
                if(result.status == "success") {
                    toastr["success"]("Message sent successfully!");
                    clear_form();
                } else {
                    toastr["error"](result.message || "Failed to send message!");
                }
                $("#send_message").attr('disabled', false);
                $("#send_message").html('<i class="fa fa-paper-plane"></i> Send Message');
                $(".overlay").remove();
            },
            error: function() {
                toastr["error"]("An error occurred. Please try again!");
                $("#send_message").attr('disabled', false);
                $("#send_message").html('<i class="fa fa-paper-plane"></i> Send Message');
                $(".overlay").remove();
            }
        });
    });
});

function clear_form() {
    $('#customer_id').val('').trigger('change');
    $('#phone_number').val('');
    $('#template_id').val('');
    $('#message').val('');
    $('#char_count').text('0');
    $('.text-danger').hide();
}
</script>

<script>$(".whatsapp-compose-active-li").addClass("active");</script>
</body>
</html>
