<?= $this->extend('template/layout') ?>

<?= $this->section('title') ?>Kirim Pesan - <?= env('app.name') ?><?= $this->endSection() ?>

<!-- main section start-->
<?= $this->section('main') ?>
<?php
    $uri      = current_url(true);
    $segment1 = $uri->setSilent()->getSegment(1);
    $segment2 = $uri->setSilent()->getSegment(2);
    $segment3 = $uri->setSilent()->getSegment(3);
?>
<!-- Breadcumb -->
<ol class="breadcrumb page-breadcrumb">
    <li class="breadcrumb-item"><a href="javascript:void(0);"><?= env('app.name') ?></a></li>
    <li class="breadcrumb-item"><?= ucfirst($segment1) ?></li>
    <li class="breadcrumb-item">Kirim Pesan</li>
    <li class="position-absolute pos-top pos-right d-none d-sm-block"><span class="js-get-date"></span></li>
</ol>
<div class="row">
    <div class="col-xl-12">
        <div id="panel-1" class="panel">
            <div class="panel-hdr border-faded border-top-1 border-right-0 border-left-0 shadow-0">
                <h2>Kirim Pesan ke Nasabah</h2>
                <div class="panel-toolbar pr-3">
                    <ul class="nav nav-pills border-bottom-0" role="tablist">
                        <li class="nav-item">
                            <div class="btn-group" role="group">
                                <button type="button" class="btn btn-sm btn-outline-primary dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" id="filter-btn">
                                    <i class="fal fa-filter"></i> Semua Nasabah
                                </button>
                                <div class="dropdown-menu">
                                    <a class="dropdown-item" href="javascript:void(0)" onclick="filterData('all')">
                                        <i class="fal fa-users"></i> Semua Nasabah
                                    </a>
                                    <a class="dropdown-item" href="javascript:void(0)" onclick="filterData('closing')">
                                        <i class="fal fa-check-circle text-success"></i> Sudah Closing
                                    </a>
                                    <a class="dropdown-item" href="javascript:void(0)" onclick="filterData('belum_closing')">
                                        <i class="fal fa-clock text-warning"></i> Belum Closing
                                    </a>
                                </div>
                            </div>&nbsp;
                        </li>
                        <li class="nav-item">
                            <?= form_button('reload', '<i class="fal fa-sync"></i>', 'reload_datagrid()') ?>&nbsp;
                        </li>
                        <?php if ($rekam == 1) { ?>
                        <li class="nav-item">
                            <?= form_button('kirim', '<i class="fal fa-paper-plane"></i> Kirim Pesan', 'show_modal_kirim()') ?>
                        </li>
                        <?php } ?>
                    </ul>
                </div><!-- end toolbar -->
            </div><!-- end panel hdr -->

            <div class="panel-container show">
                <div class="panel-content">
                    <div id="panelfit" data-options="border:false">
                        <!-- grid start -->
                        <table id="datagrid" toolbar="#toolbar" url="<?= site_url('cusen/kirim_pesan/datagrid') ?>" data-options="nowrap:true,striped:false,ctrlSelect:true,rownumbers:true,pagination:true,multiSort:true,remoteFilter:true,remoteSort:true,pageSize:10,pageList:[10,20,50,100],clientPaging:false,fit:true">
                            <thead data-options="frozen:true">
                                <tr>
                                    <th data-options="field:'ck',checkbox:true"></th>
                                </tr>
                            </thead>
                            <thead>
                                <tr>
                                    <th data-options="field:'nama_calon',sortable:true,width:200">Nama Nasabah</th>
                                    <th data-options="field:'no_cif',sortable:true,width:100,align:'center'">No CIF</th>
                                    <th data-options="field:'nik',sortable:true,width:150,align:'center'">NIK</th>
                                    <th data-options="field:'no_wa',sortable:true,width:120">No WhatsApp</th>
                                    <th data-options="field:'emailx',sortable:true,width:150">Email</th>
                                    <th data-options="field:'closing_text',sortable:true,formatter:closingFormatter,align:'center',width:80">Status</th>
                                    <th data-options="field:'tgl_closing',sortable:true,width:100,align:'center'">Tgl Closing</th>
                                    <th data-options="field:'nama_giat',sortable:true,width:150">Kegiatan</th>
                                    <th data-options="field:'nama_lokasi',sortable:true,width:150">Lokasi</th>
                                    <th data-options="field:'username',sortable:true,width:120">Direkam Oleh</th>
                                    <th data-options="field:'wkt_rek',sortable:true,width:150,align:'center'">Waktu Rekam</th>
                                </tr>
                            </thead>
                        </table>
                        <!-- grid end -->
                    </div><!-- end panel fit -->
                </div><!-- end panel content -->
            </div><!-- end panel container -->
        </div><!-- end panel 1 -->
    </div><!-- end col-xl-12 -->
</div><!-- end row -->

<!-- Modal Kirim Pesan -->
<div class="modal fade" id="modal-kirim" tabindex="-1" role="dialog" aria-labelledby="modalKirimLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="modalKirimLabel">Kirim Pesan WhatsApp</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <?= form_open("", 'id="form_kirim"') ?>
            <div class="modal-body">
                <input type="hidden" id="id_penerima" name="id_penerima">
                
                <div class="form-group">
                    <label for="judul">Judul Pesan</label>
                    <input type="text" class="form-control" id="judul" name="judul" maxlength="100" required>
                    <div class="invalid-feedback" id="em_judul"></div>
                </div>
                
                <div class="form-group">
                    <label for="pesan">Isi Pesan</label>
                    <textarea class="form-control" id="pesan" name="pesan" rows="5" maxlength="500" required></textarea>
                    <div class="invalid-feedback" id="em_pesan"></div>
                    <small class="form-text text-muted">Maksimal 500 karakter</small>
                </div>
                
                <div class="form-group">
                    <label>Penerima Terpilih:</label>
                    <div id="selected-recipients" class="border p-2 bg-light" style="max-height: 200px; overflow-y: auto;">
                        <p class="text-muted">Belum ada yang dipilih</p>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Batal</button>
                <button type="submit" class="btn btn-primary" id="btn-kirim">
                    <i class="fal fa-paper-plane"></i> Kirim Pesan
                </button>
            </div>
            </form>
        </div>
    </div>
</div>

<?= $this->endSection() ?>
<!-- main section end-->

<!-- pageScripts section start-->
<?= $this->section('pageScripts') ?>
<script type="text/javascript" src="<?= base_url('smart/dist/adlte/jquery-easyui-1.10.17/jquery.easyui.min.js') ?>"></script>
<script type="text/javascript" src="<?= base_url('smart/dist/adlte/jquery-easyui-1.10.17/datagrid-filter-1.0.6/datagrid-filter.js') ?>"></script>

<script type="text/javascript">
    var currentFilter = 'all';
    
    $(document).ready(function () {
        adjustpanelfit();
    })

    $(window).resize(function() {
        adjustpanelfit();
    });

    function adjustpanelfit() {
        var height = $(window).height();
        $('#panelfit').panel({
            height:height - 520
        });
    }
</script>

<script type="text/javascript">
/*datagrid*/
var datagrid = $('#datagrid').datagrid({
    queryParams: {
        "<?= csrf_token() ?>": "<?= csrf_hash() ?>",
        "filter_type": currentFilter
    }
});
datagrid.datagrid('enableFilter');

// Formatter untuk kolom closing
function closingFormatter(value, row, index) {
    if (value == 'Y') {
        return '<span class="badge badge-success">Closing</span>';
    } else {
        return '<span class="badge badge-warning">Belum</span>';
    }
}

/*reload datagrid*/
function reload_datagrid()
{
    $('#datagrid').datagrid('removeFilterRule');
    $('#datagrid').datagrid('load', {
        "<?= csrf_token() ?>": "<?= csrf_hash() ?>",
        "filter_type": currentFilter
    });
}

// Filter data berdasarkan status closing
function filterData(type) {
    currentFilter = type;
    var buttonText = '';
    
    switch(type) {
        case 'all':
            buttonText = '<i class="fal fa-filter"></i> Semua Nasabah';
            break;
        case 'closing':
            buttonText = '<i class="fal fa-filter"></i> Sudah Closing';
            break;
        case 'belum_closing':
            buttonText = '<i class="fal fa-filter"></i> Belum Closing';
            break;
    }
    
    $('#filter-btn').html(buttonText);
    
    $('#datagrid').datagrid('load', {
        "<?= csrf_token() ?>": "<?= csrf_hash() ?>",
        "filter_type": type
    });
}

// Show modal kirim pesan
function show_modal_kirim() {
    var rows = $('#datagrid').datagrid('getSelections');
    
    if (rows.length == 0) {
        $.messager.alert('Peringatan', 'Pilih minimal 1 nasabah untuk dikirim pesan', 'warning');
        return;
    }
    
    // Kumpulkan ID penerima
    var ids = [];
    var recipientsList = '';
    
    for(var i = 0; i < rows.length; i++) {
        ids.push(rows[i].id);
        recipientsList += '<span class="badge badge-primary mr-1 mb-1">' + rows[i].nama_calon + '</span>';
    }
    
    $('#id_penerima').val(ids.join(','));
    $('#selected-recipients').html(recipientsList);
    $('#modal-kirim').modal('show');
}

// Form kirim pesan
$("#form_kirim").submit(function(e) {
    e.preventDefault();
    var url = '<?= $action ?>';
    var formData = new FormData(this);
    
    $.ajax({
        url: url,
        type: "POST",
        dataType: 'json',
        data: formData,
        processData: false,
        contentType: false,
        beforeSend: function() {
            // Clear previous validation errors
            $(".form-control").removeClass("is-invalid");
            $(".invalid-feedback").html('').hide();
            
            // Show loading button
            $("#btn-kirim").prop('disabled', true).html('<i class="fal fa-spinner fa-spin"></i> Mengirim...');
        },
        error: function(xhr, status, message) {
            try {
                var res = JSON.parse(xhr.responseText);
                
                // Handle validation errors
                if (res.messages) {
                    $(res.messages).each(function(i, val) {
                        var inputname = Object.keys(val)[0];
                        $.each(val, function(k, v) {
                            $("#" + k).addClass("is-invalid");
                            $("#em_" + k).html(v).fadeIn();
                            $("#" + inputname).focus();
                        });
                    });
                }
                
                // Handle general error message
                if (res.message) {
                    toastr.error(res.message, 'Error!');
                }
                
            } catch (e) {
                console.error('Error parsing response:', e);
                toastr.error('Terjadi kesalahan sistem', 'Error!');
            }
        },
        success: function(res) {
            // Show success message
            toastr.success(res.message, 'Berhasil!', {
                timeOut: 3000,
                onHidden: function() {
                    $('#modal-kirim').modal('hide');
                    $('#form_kirim')[0].reset();
                    $('#datagrid').datagrid('reload');
                }
            });
        },
        complete: function() {
            // Reset button state
            $("#btn-kirim").prop('disabled', false).html('<i class="fal fa-paper-plane"></i> Kirim Pesan');
        }
    });
});

// Clear modal when closed
$('#modal-kirim').on('hidden.bs.modal', function () {
    $('#form_kirim')[0].reset();
    $(".form-control").removeClass("is-invalid");
    $(".invalid-feedback").html('').hide();
    $('#selected-recipients').html('<p class="text-muted">Belum ada yang dipilih</p>');
});
</script>
<?= $this->endSection() ?>
<!-- pageScripts section end-->
