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

<?= $this->section('title') ?>Data SWOT Pesaing - <?= 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 SWOT Pesaing</li>
    <li class="breadcrumb-item"><?= empty($id) ? 'Tambah Data SWOT' : 'Edit Data SWOT' ?></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="dataswot_form"', ['id' => $id]) ?>
                                <div class="row mb-3">
                                    <label class="col-3 col-sm-3 col-form-label text-right">Pesaing:</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_pesaing" name="id_pesaing">
                                             <option value="">Pilih Pesaing...</option>
                                             <?php foreach ($dd_pesaing as $k) { ?>
                                             <option value="<?= $k->id ?>" <?= ($id_pesaing == $k->id) ? 'selected' : '' ?>><?= $k->nama_pesaing ?></option>
                                             <?php } ?>
                                        </select>
                                        <div class="invalid-feedback" id="em_id_pesaing"></div>
                                    </div>
                                </div>

                                <div class="row mb-3">
                                    <label class="col-3 col-sm-3 col-form-label text-right">Produk Serupa:</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">Kekuatan:</label>
                                    <div class="col-9 col-sm-9">
                                        <textarea id="kekuatan" class="form-control rounded-0 border-top-0 border-left-0 border-right-0 px-0 bg-transparent" name="kekuatan" rows="3" placeholder="Masukkan analisis kekuatan pesaing..." maxlength="500"><?= $kekuatan ?></textarea>
                                        <div class="invalid-feedback" id="em_kekuatan"></div>
                                    </div>
                                </div>

                                <div class="row mb-3">
                                    <label class="col-3 col-sm-3 col-form-label text-right">Kelemahan:</label>
                                    <div class="col-9 col-sm-9">
                                        <textarea id="kelemahan" class="form-control rounded-0 border-top-0 border-left-0 border-right-0 px-0 bg-transparent" name="kelemahan" rows="3" placeholder="Masukkan analisis kelemahan pesaing..." maxlength="500"><?= $kelemahan ?></textarea>
                                        <div class="invalid-feedback" id="em_kelemahan"></div>
                                    </div>
                                </div>

                                <div class="row mb-3">
                                    <label class="col-3 col-sm-3 col-form-label text-right">Kesempatan:</label>
                                    <div class="col-9 col-sm-9">
                                        <textarea id="kesempatan" class="form-control rounded-0 border-top-0 border-left-0 border-right-0 px-0 bg-transparent" name="kesempatan" rows="3" placeholder="Masukkan analisis kesempatan..." maxlength="500"><?= $kesempatan ?></textarea>
                                        <div class="invalid-feedback" id="em_kesempatan"></div>
                                    </div>
                                </div>

                                <div class="row mb-3">
                                    <label class="col-3 col-sm-3 col-form-label text-right">Ancaman:</label>
                                    <div class="col-9 col-sm-9">
                                        <textarea id="ancaman" class="form-control rounded-0 border-top-0 border-left-0 border-right-0 px-0 bg-transparent" name="ancaman" rows="3" placeholder="Masukkan analisis ancaman..." maxlength="500"><?= $ancaman ?></textarea>
                                        <div class="invalid-feedback" id="em_ancaman"></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_dataswot', $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 Pesaing</div>
                                <div class="card-body">
                                    <div id="map" style="height: 400px;"></div>
                                    <small class="text-muted mt-2 d-block">Peta akan menampilkan lokasi pesaing 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">
    $('.select2').select2({
        dropdownCssClass:'increasezindex'
    });

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

    $("#dataswot_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_dataswot"));
            },
            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_dataswot"));
            }
        });
    });
</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, pesaingName) {
        if (map && marker) {
            const position = { lat: lat, lng: lng };
            
            // Update posisi marker
            marker.setPosition(position);
            marker.setVisible(true);
            marker.setTitle(pesaingName || 'Pesaing yang dipilih');
            
            // Center peta ke lokasi
            map.setCenter(position);
            map.setZoom(15);
            
            // Tambah info window
            const infoWindow = new google.maps.InfoWindow({
                content: `<div><strong>${pesaingName || 'Pesaing'}</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_pesaing').val()) {
            $('#id_pesaing').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-->
