<?php
$CI = &get_instance();
if (!isset($CI->sms) || empty($CI->sms)) {
    $CI->load->library('sms');
}
$gateways = $CI->sms->get_gateways();
$triggers = $CI->sms->get_available_triggers();
$total_gateways = count(array($gateways));
?>

<div class="space-y-6">
    <?= message_box('success'); ?>
    <?= message_box('error'); ?>

    <?php if ($total_gateways > 1) { ?>
        <div class="rounded-lg border border-blue-200 bg-blue-50 px-4 py-3 text-sm text-blue-800 dark:border-blue-900/50 dark:bg-blue-950/30 dark:text-blue-200">
            <?= lang('only_one_active_sms_gateway'); ?>
        </div>
    <?php } ?>

    <div class="rounded-2xl border border-border bg-card shadow-sm">
        <div class="px-6 py-4 border-b border-border flex flex-col gap-1 md:flex-row md:items-center md:justify-between">
            <div>
                <h2 class="text-lg font-semibold text-foreground"><?= lang('sms_settings') ?></h2>
                <p class="text-sm text-muted-foreground"><?= lang('settings') ?></p>
            </div>
        </div>
        <div class="p-6">
            <form action="<?= base_url() ?>admin/settings/save_sms_settings" method="post" class="space-y-6">
                
                <!-- SMS Gateways -->
                <div class="space-y-4">
                    <?php foreach ($gateways as $gname => $gateway) { 
                        $is_active = config_item($gname . '_status') == 1;
                    ?>
                        <div class="rounded-2xl border border-border bg-card shadow-sm">
                            <div class="px-5 py-4 border-b border-border cursor-pointer" onclick="document.getElementById('gateway_<?= $gname ?>').classList.toggle('hidden')">
                                <div class="flex items-center justify-between">
                                    <h3 class="text-sm font-semibold text-foreground"><?= $gateway['name'] ?></h3>
                                    <i class="text-muted-foreground" data-lucide="chevron-down"></i>
                                </div>
                            </div>
                            <div id="gateway_<?= $gname ?>" class="p-5 <?= ($is_active || $total_gateways == 1) ? '' : 'hidden' ?>">
                                <?php if (isset($gateway['info']) && $gateway['info'] != '') { ?>
                                    <div class="mb-4 rounded-lg border border-blue-200 bg-blue-50 px-4 py-3 text-sm text-blue-800 dark:border-blue-900/50 dark:bg-blue-950/30 dark:text-blue-200">
                                        <?= strip_tags($gateway['info'], '<a><strong><b><em><i>') ?>
                                    </div>
                                <?php } ?>
                                
                                <div class="grid grid-cols-1 gap-4 md:grid-cols-2">
                                    <?php foreach ($gateway['options'] as $g_option) { 
                                        $attrs = array();
                                        if (isset($g_option['info'])) {
                                            $attrs['data-info'] = $g_option['info'];
                                        }
                                        echo form_input_group(
                                            $g_option['name'], 
                                            $g_option['label'], 
                                            !empty($g_option['value']) ? $g_option['value'] : '', 
                                            'text', 
                                            true,
                                            $attrs
                                        );
                                    } ?>
                                </div>

								

                                <div class="mt-4 pt-4 border-t border-border">
                                    <label class="flex items-center gap-2 cursor-pointer">
                                        <input class="select_one h-4 w-4 rounded border-gray-300 text-primary focus:ring-primary" 
                                               type="checkbox" 
                                               value="1" 
                                               <?= $is_active ? 'checked' : '' ?> 
                                               name="<?= $gname . '_status' ?>">
                                        <span class="text-sm font-medium text-foreground"><?= lang('active') ?></span>
                                    </label>
                                </div>

                                <?php if ($is_active) { ?>
                                    <div class="mt-6 rounded-lg border border-border bg-muted/50 p-4">
                                        <h4 class="text-sm font-semibold text-foreground mb-4"><?= lang('test_sms_config') ?></h4>
                                        <div class="space-y-4">
                                            <?= form_input_group(
                                                'test_phone_' . $gname, 
                                                lang('enter') . ' ' . lang('phone') . ' ' . lang('number'), 
                                                '', 
                                                'text', 
                                                false,
                                                array('class' => 'test-phone', 'data-id' => $gname, 'placeholder' => lang('enter') . ' ' . lang('phone') . ' ' . lang('number'))
                                            ); ?>
                                            
                                            <?= form_editor(
                                                'test_message_' . $gname,
                                                lang('test_message'),
                                                'Hello',
                                                false,
                                                array('class' => 'sms-gateway-test-message', 'data-id' => $gname, 'placeholder' => lang('test_message'))
                                            ); ?>
                                            
                                            <div class="flex items-center gap-2">
                                                <button type="button" class="btn btn-sm btn-primary send-test-sms" data-id="<?= $gname ?>">
                                                    <?= lang('send_test_sms') ?>
                                                </button>
                                            </div>
                                            <div id="sms_test_response" data-id="<?= $gname ?>"></div>
                                        </div>
                                    </div>
                                <?php } ?>
                            </div>
                        </div>
                    <?php } ?>
                </div>

                <!-- SMS Templates -->
                <div class="rounded-2xl border border-border bg-card shadow-sm">
                    <div class="px-5 py-4 border-b border-border">
                        <h3 class="text-sm font-semibold text-foreground"><?= lang('SMS') . ' ' . lang('template') ?></h3>
                        <p class="text-xs text-muted-foreground mt-1">Leave contents blank to disable specific <?= lang('SMS') . ' ' . lang('template') ?>.</p>
                    </div>
                    <div class="p-5">
                        <div class="space-y-6">
                            <?php foreach ($triggers as $trigger_name => $trigger_opts) { ?>
                                <div class="space-y-2">
                                    <div class="flex items-start justify-between gap-2">
                                        <div class="flex-1">
                                            <label class="block text-sm font-medium text-foreground mb-1">
                                                <?= $trigger_opts['label'] ?>
                                            </label>
                                            <?php if (isset($trigger_opts['info']) && $trigger_opts['info'] != '') { ?>
                                                <p class="text-xs text-muted-foreground mb-2">
                                                    <?= $trigger_opts['info'] ?>
                                                    <?php if (!empty($trigger_opts['sms_number'])) { ?>
                                                        <input class="inline-block w-32 px-2 py-1 text-xs border border-border rounded ml-2" 
                                                               value="<?= $trigger_opts['sms_number'] ?>" 
                                                               type="text" 
                                                               name="<?= $trigger_name . '_sms_number' ?>">
                                                    <?php } ?>
                                                </p>
                                            <?php } ?>
                                        </div>
                                        <button type="button" 
                                                onclick="document.getElementById('sms_merge_fields_<?= $trigger_name ?>').classList.toggle('hidden'); return false;" 
                                                class="text-xs text-primary hover:underline whitespace-nowrap">
                                            <?= lang('available_merge_fields') ?>
                                        </button>
                                    </div>
                                    
                                    <?=
                                    form_textarea(
                                        $CI->sms->trigger_option_name($trigger_name),
                                        '',
                                        !empty($trigger_opts['value']) ? $trigger_opts['value'] : '',
                                        3,
                                        false,
                                        array('class' => 'w-full'),
                                        'horizontal'
                                    )
                                    ?>
                                    
                                    <?php
                                    $merge_fields = '';
                                    foreach ($trigger_opts['merge_fields'] as $merge_field) {
                                        $merge_fields .= $merge_field . ', ';
                                    }
                                    if ($merge_fields != '') { ?>
                                        <div id="sms_merge_fields_<?= $trigger_name ?>" class="hidden mt-2 p-3 rounded-lg bg-muted/50 border border-border">
                                            <p class="text-xs text-muted-foreground font-mono"><?= substr($merge_fields, 0, -2) ?></p>
                                        </div>
                                    <?php } ?>
                                </div>
                            <?php } ?>
                        </div>
                    </div>
                </div>

                <div class="flex items-center justify-end gap-2">
                    <button type="submit" class="btn btn-sm btn-primary"><?= lang('save_changes') ?></button>
                </div>
            </form>
        </div>
    </div>
</div>
<script type="text/javascript">
    $('.send-test-sms').on('click', function () {
        var id = $(this).data('id');
        var errorContainer = $('#sms_test_response[data-id="' + id + '"]');
        var message = $('textarea[data-id="' + id + '"]').val();
        var number = $('input.test-phone[data-id="' + id + '"]').val();
        var that = $(this);
        var URL = '<?= base_url('admin/settings/test_sms')?>';
        errorContainer.empty();
        message = message.trim();
        if (message != '' && number != '') {
            that.prop('disabled', true);
            $.post(URL, {
                message: message,
                number: number,
                id: id,
                sms_gateway_test: true
            }).done(function (response) {
                response = JSON.parse(response);
                if (response.success == true) {
                    errorContainer.html('<div style="margin-top: 40px !important;" class="p m-lg alert alert-success mt-lg">SMS Sent Successfully!</div>');
                } else {
                    errorContainer.html('<div style="margin-top: 40px !important;"  class="p m-lg alert alert-warning mt-lg">' + response.error + '</div>');
                }
            }).always(function () {
                that.prop('disabled', false);
            });
        }
    });
</script>

