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

<?= $this->section('title') ?>Data Calon Nasabah - <?= 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">Data Calon Nasabah</li>
    <li class="breadcrumb-item"><?= empty($id) ? 'Tambah Data Calon Nasabah' : 'Edit Data Calon Nasabah' ?></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>Form</h2>
                <div class="panel-toolbar pr-3">
                    
                </div>
            </div>

            <div class="panel-container show">
                <div class="panel-content">
                    <div class="row">
                        <div class="col-12 col-sm-6">
                            
                            <?= form_open_multipart("", 'id="calonasabah_form"', ['id' => $id, 'foto_kegiatan_lama' => $foto_kegiatan]) ?>
                                <div class="row mb-3">
                                    <label class="col-3 col-sm-3 col-form-label text-right">Kegiatan:</label>
                                    <div class="col-9 col-sm-9">
                                        <select class="form-control select2 rounded-0 border-top-0 border-left-0 border-right-0 px-0 bg-transparent" id="id_kegiatan" name="id_kegiatan">
                                             <option value="">Pilih Kegiatan...</option>
                                             <?php foreach ($dd_kegiatan as $k) { ?>
                                             <option value="<?= $k->id ?>" <?= ($id_kegiatan == $k->id) ? 'selected' : '' ?>><?= $k->nama_giat ?></option>
                                             <?php } ?>
                                        </select>
                                        <div class="invalid-feedback" id="em_id_kegiatan"></div>
                                    </div>
                                </div>

                                <div class="row mb-3">
                                    <label class="col-3 col-sm-3 col-form-label text-right">Produk:</label>
                                    <div class="col-9 col-sm-9">
                                        <select class="form-control select2 rounded-0 border-top-0 border-left-0 border-right-0 px-0 bg-transparent" id="id_produk" name="id_produk">
                                             <option value="">Pilih Produk...</option>
                                             <?php foreach ($dd_produk as $k) { ?>
                                             <option value="<?= $k->id ?>" <?= ($id_produk == $k->id) ? 'selected' : '' ?>><?= $k->uraian ?></option>
                                             <?php } ?>
                                        </select>
                                        <div class="invalid-feedback" id="em_id_produk"></div>
                                    </div>
                                </div>

                                <div class="row mb-3">
                                    <label class="col-3 col-sm-3 col-form-label text-right">Tanggal Kegiatan:</label>
                                    <div class="col-9 col-sm-9">
                                        <input type="date" id="tgl_kegiatan" class="form-control rounded-0 border-top-0 border-left-0 border-right-0 px-0 bg-transparent" name="tgl_kegiatan" value="<?= $tgl_kegiatan ?>">
                                        <div class="invalid-feedback" id="em_tgl_kegiatan"></div>
                                    </div>
                                </div>

                                <div class="row mb-3">
                                    <label class="col-3 col-sm-3 col-form-label text-right">Nama Calon:</label>
                                    <div class="col-9 col-sm-9">
                                        <input type="text" id="nama_calon" class="form-control rounded-0 border-top-0 border-left-0 border-right-0 px-0 bg-transparent ginputx" name="nama_calon" value="<?= $nama_calon ?>" placeholder="Nama Calon Nasabah" maxlength="100">
                                        <div class="invalid-feedback" id="em_nama_calon"></div>
                                    </div>
                                </div>

                                <div class="row mb-3">
                                    <label class="col-3 col-sm-3 col-form-label text-right">Tanggal Lahir:</label>
                                    <div class="col-9 col-sm-9">
                                        <input type="date" id="tgl_lahir" class="form-control rounded-0 border-top-0 border-left-0 border-right-0 px-0 bg-transparent" name="tgl_lahir" value="<?= $tgl_lahir ?>">
                                        <div class="invalid-feedback" id="em_tgl_lahir"></div>
                                    </div>
                                </div>

                                <div class="row mb-3">
                                    <label class="col-3 col-sm-3 col-form-label text-right">Alamat:</label>
                                    <div class="col-9 col-sm-9">
                                        <textarea id="alamat" class="form-control rounded-0 border-top-0 border-left-0 border-right-0 px-0 bg-transparent" name="alamat" placeholder="Alamat" maxlength="200" rows="3"><?= $alamat ?></textarea>
                                        <div class="invalid-feedback" id="em_alamat"></div>
                                    </div>
                                </div>

                                <div class="row mb-3">
                                    <label class="col-3 col-sm-3 col-form-label text-right">No. WhatsApp:</label>
                                    <div class="col-9 col-sm-9">
                                        <input type="text" id="no_wa" class="form-control rounded-0 border-top-0 border-left-0 border-right-0 px-0 bg-transparent" name="no_wa" value="<?= $no_wa ?>" placeholder="Nomor WhatsApp" maxlength="15">
                                        <div class="invalid-feedback" id="em_no_wa"></div>
                                    </div>
                                </div>

                                <div class="row mb-3">
                                    <label class="col-3 col-sm-3 col-form-label text-right">NIK:</label>
                                    <div class="col-9 col-sm-9">
                                        <input type="text" id="nik" class="form-control rounded-0 border-top-0 border-left-0 border-right-0 px-0 bg-transparent" name="nik" value="<?= $nik ?>" placeholder="Nomor Induk Kependudukan" maxlength="16">
                                        <div class="invalid-feedback" id="em_nik"></div>
                                    </div>
                                </div>

                                <div class="row mb-3">
                                    <label class="col-3 col-sm-3 col-form-label text-right">Referal:</label>
                                    <div class="col-9 col-sm-9">
                                        <input type="text" id="referal" class="form-control rounded-0 border-top-0 border-left-0 border-right-0 px-0 bg-transparent" name="referal" value="<?= $referal ?>" placeholder="CIF Nasabah yg merekomendasikan" maxlength="16">
                                        <div class="invalid-feedback" id="em_referal"></div>
                                    </div>
                                </div>

                                <div class="row mb-3">
                                    <label class="col-3 col-sm-3 col-form-label text-right">Foto Kegiatan:</label>
                                    <div class="col-9 col-sm-9">
                                        <input type="file" id="foto_kegiatan" class="form-control rounded-0 border-top-0 border-left-0 border-right-0 px-0 bg-transparent" name="foto_kegiatan" accept="image/*">
                                        <?php if (!empty($foto_kegiatan)) { ?>
                                        <small class="text-muted">File saat ini: <?= $foto_kegiatan ?></small>
                                        <?php } ?>
                                        <div class="invalid-feedback" id="em_foto_kegiatan"></div>
                                    </div>
                                </div>
   
                                <hr>
                                <div class="invalid-feedback text-center" id="em_message"></div>
                                <div class="clearfix">
                                    <a href="<?= $back ?>" class="btn btn-secondary"><i class="fal fa-arrow-left"></i> KEMBALI</a>
                                    <?= form_submit('btn_calonasabah', $button, 'waves-effect waves-themed float-right') ?>
                                </div>
                            </form>

                        </div>
                        <div class="col-12 col-sm-6">
                            <div class="card">
                                <div class="card-header">Detail Kegiatan</div>
                                <div class="card-body" id="detail-kegiatan">
                                    <div class="text-muted">Pilih kegiatan untuk melihat detail</div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div><!-- end panel 1 -->
    </div><!-- end col-xl-6 -->
</div><!-- end row -->
<?= $this->endSection() ?>
<!-- main section end-->

<!-- pageScripts section start-->
<?= $this->section('pageScripts') ?>
<script type="text/javascript">
    $('.ginputx').inputmask({
        regex: "^[a-zA-Z0-9\\s.,@-]*$"
    });

    $('#no_wa').inputmask({
        regex: "^[0-9]*$"
    });

    $('#nik').inputmask({
        regex: "^[0-9]*$"
    });

    $('.select2').select2({
        dropdownCssClass:'increasezindex'
    });

    // Event handler untuk perubahan kegiatan (tampilkan detail)
    $('#id_kegiatan').on('change', function() {
        if (this.value) {
            $.ajax({
                type: "POST",
                url: "<?= base_url('potensiwilayah/calonasabah/get_kegiatan_detail') ?>",
                dataType: 'json',
                data: { 'id_kegiatan': this.value },
                success: function(data){
                    if (data) {
                        var html = '<div class="table-responsive">';
                        html += '<table class="table table-bordered table-sm">';
                        html += '<tr><td><strong>Nama Kegiatan:</strong></td><td>' + (data.nama_giat || '-') + '</td></tr>';
                        html += '<tr><td><strong>Tanggal Mulai:</strong></td><td>' + (data.tgl_1 || '-') + '</td></tr>';
                        html += '<tr><td><strong>Tanggal Selesai:</strong></td><td>' + (data.tgl_2 || '-') + '</td></tr>';
                        html += '<tr><td><strong>Jenis Promosi:</strong></td><td>' + (data.nama_kegiatan || '-') + '</td></tr>';
                        html += '<tr><td><strong>Nama Lokasi:</strong></td><td>' + (data.nama_lokasi || '-') + '</td></tr>';
                        html += '<tr><td><strong>Alamat:</strong></td><td>' + (data.alamat || '-') + '</td></tr>';
                        html += '<tr><td><strong>Kategori Lokasi:</strong></td><td>' + (data.nama_kat || '-') + '</td></tr>';
                        html += '</table>';
                        html += '</div>';
                        $('#detail-kegiatan').html(html);
                    } else {
                        $('#detail-kegiatan').html('<div class="text-muted">Data kegiatan tidak ditemukan</div>');
                    }
                },
                error: function() {
                    $('#detail-kegiatan').html('<div class="text-danger">Error loading detail kegiatan</div>');
                }
            });
        } else {
            $('#detail-kegiatan').html('<div class="text-muted">Pilih kegiatan untuk melihat detail</div>');
        }
    });

    $("#calonasabah_form").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();
                $("#em_message").html('').hide();
                
                // Show loading button
                BtnLoading($("#btn_calonasabah"));
            },
            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) {
                        $("#em_message").html(res.message).fadeIn();
                    }
                    
                } catch (e) {
                    console.error('Error parsing response:', e);
                    $("#em_message").html('Terjadi kesalahan sistem').fadeIn();
                }
            },
            success: function(res) {
                // Show success message
                toastr.success(res.message, 'Berhasil!', {
                    timeOut: 2000,
                    onHidden: function() {
                        // Redirect to list page after toast
                        window.location.href = '<?= $back ?>';
                    }
                });
            },
            complete: function() {
                // Reset button state
                BtnReset($("#btn_calonasabah"));
            }
        });
    });

    // Trigger event jika form sudah ada nilai (mode edit)
    $(document).ready(function() {
        if ($('#id_kegiatan').val()) {
            $('#id_kegiatan').trigger('change');
        }
    });
</script>
<?= $this->endSection() ?>
<!-- pageScripts section end-->
