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

<?= $this->section('title') ?>Data Promosi - <?= 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 Promosi</li>
    <li class="breadcrumb-item"><?= empty($id) ? 'Tambah Data Promosi' : 'Edit Data Promosi' ?></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("", 'id="datapromosi_form"', ['id' => $id]) ?>
                                <div class="row mb-3">
                                    <label class="col-3 col-sm-3 col-form-label text-right">Jenis Promosi:</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_jenis" name="id_jenis">
                                             <option value="">Pilih Jenis Promosi...</option>
                                             <?php foreach ($dd_jenis as $k) { ?>
                                             <option value="<?= $k->id ?>" <?= ($id_jenis == $k->id) ? 'selected' : '' ?>><?= $k->nama_kegiatan ?></option>
                                             <?php } ?>
                                        </select>
                                        <div class="invalid-feedback" id="em_id_jenis"></div>
                                    </div>
                                </div>

                                <div class="row mb-3">
                                    <label class="col-3 col-sm-3 col-form-label text-right">Kategori Lokasi:</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_katelok" name="id_katelok">
                                             <option value="">Pilih Kategori Lokasi...</option>
                                             <?php foreach ($dd_katelok as $k) { ?>
                                             <option value="<?= $k->id ?>" <?= ($id_katelok == $k->id) ? 'selected' : '' ?>><?= $k->nama_kat ?></option>
                                             <?php } ?>
                                        </select>
                                        <div class="invalid-feedback" id="em_id_katelok"></div>
                                    </div>
                                </div>

                                <div class="row mb-3">
                                    <label class="col-3 col-sm-3 col-form-label text-right">Lokasi:</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_lokasi" name="id_lokasi">
                                             <option value="">Pilih Lokasi...</option>
                                             <?php if (!empty($dd_lokasi)) { ?>
                                                 <?php foreach ($dd_lokasi as $k) { ?>
                                                 <option value="<?= $k->id ?>" <?= ($id_lokasi == $k->id) ? 'selected' : '' ?>><?= $k->nama_lokasi ?></option>
                                                 <?php } ?>
                                             <?php } ?>
                                        </select>
                                        <div class="invalid-feedback" id="em_id_lokasi"></div>
                                    </div>
                                </div>

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

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

                                <div class="row mb-3">
                                    <label class="col-3 col-sm-3 col-form-label text-right">Kontak PIC:</label>
                                    <div class="col-9 col-sm-9">
                                        <input type="text" id="piclok_kontak" class="form-control rounded-0 border-top-0 border-left-0 border-right-0 px-0 bg-transparent ginputx" name="piclok_kontak" value="<?= $piclok_kontak ?>" placeholder="Kontak PIC" maxlength="50">
                                        <div class="invalid-feedback" id="em_piclok_kontak"></div>
                                    </div>
                                </div>

                                <div class="row mb-3">
                                    <label class="col-3 col-sm-3 col-form-label text-right">Periode:</label>
                                    <div class="col-4 col-sm-4">
                                        <input type="date" id="tgl_1" class="form-control rounded-0 border-top-0 border-left-0 border-right-0 px-0 bg-transparent" name="tgl_1" value="<?= $tgl_1 ?>">
                                        <div class="invalid-feedback" id="em_tgl_1"></div>
                                    </div>
                                    <div class="col-1 col-sm-1 text-center">
                                        <label class="col-form-label">s/d</label>
                                    </div>
                                    <div class="col-4 col-sm-4">
                                        <input type="date" id="tgl_2" class="form-control rounded-0 border-top-0 border-left-0 border-right-0 px-0 bg-transparent" name="tgl_2" value="<?= $tgl_2 ?>">
                                        <div class="invalid-feedback" id="em_tgl_2"></div>
                                    </div>
                                </div>

                                <!-- Status Field (hanya muncul saat edit) -->
                                <?php if (!empty($id)) { ?>
                                <div class="row mb-3">
                                    <label class="col-3 col-sm-3 col-form-label text-right">Status:</label>
                                    <div class="col-9 col-sm-9">
                                        <select class="form-control rounded-0 border-top-0 border-left-0 border-right-0 px-0 bg-transparent" id="status" name="status">
                                            <option value="0" <?= ($status == 0) ? 'selected' : '' ?>>Aktif</option>
                                            <option value="1" <?= ($status == 1) ? 'selected' : '' ?>>Selesai</option>
                                        </select>
                                        <div class="invalid-feedback" id="em_status"></div>
                                    </div>
                                </div>
                                <?php } ?>
   
                                <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_datapromosi', $button, 'waves-effect waves-themed float-right') ?>
                                </div>
                            </form>

                        </div>
                        <div class="col-12 col-sm-6">
                            <div class="card">
                                <div class="card-header">Lokasi Peta</div>
                                <div class="card-body">
                                    <div id="map" style="height: 400px;"></div>
                                    <small class="text-muted mt-2 d-block">Peta akan menampilkan lokasi yang dipilih</small>
                                </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.,@-]*$"
    });

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

    // Event handler untuk perubahan kategori lokasi
    $('#id_katelok').on('change', function() {  
        $('#id_lokasi').empty().append('<option value="">Pilih Lokasi...</option>');
        
        if (this.value) {
            $.ajax({
                type: "POST",
                url: "<?= base_url('potensiwilayah/datapromosi/get_lokasi') ?>",
                dataType: 'json',
                data: { 'id_katelok': this.value },
                success: function(data){
                    $.each(data, function(i, d) {
                        $('#id_lokasi').append('<option value="' + d.id + '">' + d.nama_lokasi + '</option>');
                    });
                    $('#id_lokasi').trigger('change'); // Update Select2
                },
                error: function() {
                    console.log('Error loading lokasi data');
                }
            });
        }
    });

    // Event handler untuk perubahan lokasi (tampilkan di peta)
    $('#id_lokasi').on('change', function() {
        if (this.value) {
            $.ajax({
                type: "POST",
                url: "<?= base_url('potensiwilayah/datapromosi/get_lokasi_detail') ?>",
                dataType: 'json',
                data: { 'id_lokasi': this.value },
                success: function(data){
                    if (data && data.lati && data.longi) {
                        updateMapLocation(parseFloat(data.lati), parseFloat(data.longi), data.nama_lokasi);
                    }
                },
                error: function() {
                    console.log('Error loading lokasi detail');
                }
            });
        }
    });

    $("#datapromosi_form").submit(function(e) {
        e.preventDefault();
        var url = '<?= $action ?>';
        var formData = $(this).serialize();
        
        $.ajax({
            url: url,
            type: "POST",
            dataType: 'json',
            data: formData,
            beforeSend: function() {
                // Clear previous validation errors
                $(".form-control").removeClass("is-invalid");
                $(".invalid-feedback").html('').hide();
                $("#em_message").html('').hide();
                
                // Show loading button
                BtnLoading($("#btn_datapromosi"));
            },
            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_datapromosi"));
            }
        });
    });
</script>

<script>
    // Variabel global untuk marker dan map
    let map, marker;
    
    // Fungsi inisialisasi peta
    function initMap() {
        // Inisialisasi peta (centered di Indonesia)
        map = new google.maps.Map(document.getElementById('map'), {
            zoom: 5,
            center: { lat: -2.5489, lng: 118.0149 } // Pusat Indonesia
        });
        
        // Marker awal (tersembunyi)
        marker = new google.maps.Marker({
            map: map,
            visible: false
        });
    }
    
    // Fungsi untuk update lokasi peta
    function updateMapLocation(lat, lng, locationName) {
        if (map && marker) {
            const position = { lat: lat, lng: lng };
            
            // Update posisi marker
            marker.setPosition(position);
            marker.setVisible(true);
            marker.setTitle(locationName || 'Lokasi yang dipilih');
            
            // Center peta ke lokasi
            map.setCenter(position);
            map.setZoom(15);
            
            // Tambah info window
            const infoWindow = new google.maps.InfoWindow({
                content: `<div><strong>${locationName || 'Lokasi'}</strong><br>Lat: ${lat}<br>Lng: ${lng}</div>`
            });
            
            marker.addListener('click', function() {
                infoWindow.open(map, marker);
            });
        }
    }
    
    // Trigger event jika form sudah ada nilai (mode edit)
    $(document).ready(function() {
        if ($('#id_lokasi').val()) {
            $('#id_lokasi').trigger('change');
        }
    });
</script>

<!-- Load Google Maps API -->
<script src="https://maps.googleapis.com/maps/api/js?key=<?= $map_api ?>&callback=initMap&libraries=geometry,places" async defer></script>

<style>
    #map {
        height: 400px;
        width: 100%;
        border: 1px solid #ddd;
        border-radius: 5px;
    }
</style>
<?= $this->endSection() ?>
<!-- pageScripts section end-->
