@extends('layouts.master')

@push('style')
    <link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css"/>
    <script src="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
    
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/leaflet.css" integrity="sha512-Zcn6bjR/8RZbLEpLIeOwNtzREBAJnUKESxces60Mpoj+2okopSAcSUIUOseddDm0cxnGQzxIR7vJgsLZbdLE3w==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/leaflet.js" integrity="sha512-BwHfrr4c9kmRkLw6iXFdzcdWV/PGkVgiIyIWLLlTSXzWQzxuSg4DiQUCpauz/EWjgk5TYQqX/kvn9pG1NpYfqg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
@endpush

@section('content')
<div class="container-fluid">

    <!-- Content Row -->
    <div class="row">

        <!-- Area Chart -->
        <div class="col-xl-8 col-lg-7">
            <div class="card shadow mb-4">
                <!-- Card Header - Dropdown -->
                <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
                    <h5 class="m-0 font-weight-bold text-primary">Kasus DBD Setiap Tahun</h5>
                    <form action="{{ route('dashboard.index') }}" method="GET">
                        <label class="m-0 font-weight-bold text-primary" for="year">Pilih Tahun:</label>
                        <select class="m-0 font-weight-bold text-primary" name="year" id="year" onchange="this.form.submit()">
                            @foreach ($availableYears as $year)
                                <option value="{{ $year }}" {{ $selectedYear == $year ? 'selected' : '' }}>{{ $year }}</option>
                            @endforeach
                        </select>
                    </form>
                </div>
                <!-- Card Body -->
                <div class="card-body">
                    {!! $monthlyChart->container() !!}
                </div>
            </div>
        </div>

        <!-- Pie Chart -->
        <div class="col-xl-4 col-lg-5">
            <div class="card shadow mb-4">
                <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
                    <h5 class="m-0 font-weight-bold text-primary">Kasus DBD per Tahun (2019-2023)</h5>
                </div>
                <div class="card-body ">
                    {!! $yearlyChart->container() !!}
                </div>
            </div>
        </div>
    </div>

    <div class="card shadow mb-4">
        <!-- Card Header -->
        <div class="card-header py-3">
            <h5 class="m-0 font-weight-bold text-primary">Hasil Clustering</h5>
        </div>
        <!-- Card Body -->
        <div class="card-body">
            <table class="table table-bordered data-table">
                <thead>
                    <tr>
                        <th>ID Kecamatan</th>
                        <th>Nama Kecamatan</th>
                        <th>Cluster</th>
                    </tr>
                </thead>
                <tbody>
                    @if (isset($clusterResults))
                        @foreach ($clusterResults as $result)
                            <tr>
                                <td>{{ $result['id_kecamatan'] }}</td>
                                <td>{{ $result['nama_kecamatan'] }}</td>
                                <td>{{ $result['cluster'] }}</td>
                            </tr>
                        @endforeach
                    @else
                        <tr>
                            <td colspan="4">Tidak ada data clustering yang tersedia</td>
                        </tr>
                    @endif
                </tbody>
            </table>
        </div>
    </div>

    <div class="col-12">
        <div class="card shadow mb-4">
            <div class="card-header py-3">
                <h3 class="m-0 font-weight-bold text-primary">Plot Clustering</h3>
            </div>
            <div class="card-body">
                <div id="scatter-plot" style=" width: auto; height: 600px;"></div>
            </div>
        </div>
    </div>

    <div class="card shadow mb-4">
        <!-- Card Header -->
        <div class="card-header py-3">
            <h5 class="m-0 font-weight-bold text-primary">Peta Sebaran DBD Berdasarkan Cluster</h5>
        </div>
        <!-- Card Body -->
        <div class="card-body">
            <div id="map" style="height: 500px;"></div>
        </div>
    </div>
</div>
@endsection

@section('js')
    <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
    <script src="{{ $monthlyChart->cdn() }}"></script>
    {{ $monthlyChart->script() }}

    <script src="{{ $yearlyChart->cdn() }}"></script>
    {{ $yearlyChart->script() }}

<script>
    var map = L.map('map').setView([-8.2192, 114.3692], 11); // Inisialisasi peta dengan koordinat yang sesuai

    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        maxZoom: 19,
        attribution: 'Map data © <a href="https://openstreetmap.org">OpenStreetMap</a> contributors'
    }).addTo(map);

    var clusterResults = {!! json_encode($clusterResults) !!}; 
    // Mendapatkan data klaster dari PHP
    // console.log(clusterResults);

    var data = [];

    Object.keys(clusterResults).forEach(function(key) {
        var kecamatan = clusterResults[key];
        if (kecamatan.latitude && kecamatan.longitude) {
            var icon;
            switch (kecamatan.cluster) {
                case 1:
                    icon = L.icon({
                        iconUrl: 'https://cdn.rawgit.com/pointhi/leaflet-color-markers/master/img/marker-icon-red.png',
                        shadowUrl: 'https://cdn.rawgit.com/pointhi/leaflet-color-markers/master/img/marker-shadow.png',
                        iconSize: [25, 41],
                        iconAnchor: [12, 41],
                        popupAnchor: [1, -34],
                        shadowSize: [41, 41]
                    });
                    break;
                case 2:
                    icon = L.icon({
                        iconUrl: 'https://cdn.rawgit.com/pointhi/leaflet-color-markers/master/img/marker-icon-yellow.png',
                        shadowUrl: 'https://cdn.rawgit.com/pointhi/leaflet-color-markers/master/img/marker-shadow.png',
                        iconSize: [25, 41],
                        iconAnchor: [12, 41],
                        popupAnchor: [1, -34],
                        shadowSize: [41, 41]
                    });
                    break;
                case 3:
                    icon = L.icon({
                        iconUrl: 'https://cdn.rawgit.com/pointhi/leaflet-color-markers/master/img/marker-icon-green.png',
                        shadowUrl: 'https://cdn.rawgit.com/pointhi/leaflet-color-markers/master/img/marker-shadow.png',
                        iconSize: [25, 41],
                        iconAnchor: [12, 41],
                        popupAnchor: [1, -34],
                        shadowSize: [41, 41]
                    });
                    break;
                default:
                    icon = L.iconDefault();
            }
            var marker = L.marker([parseFloat(kecamatan.latitude), parseFloat(kecamatan.longitude)], { icon: icon }).addTo(map);
            marker.bindPopup(kecamatan.nama_kecamatan + ' (Cluster ' + kecamatan.cluster + ')');
        }

        var colors = ['#cd3750', '#ccc334', '#34ab2b'];
        var trace = {
            x: [kecamatan.jumlah_kasus],
            y: [kecamatan.jumlah_penduduk],
            mode: 'markers',
            type: 'scatter',
            name: 'Cluster ' + kecamatan.cluster,
            text: kecamatan.nama_kecamatan,
            marker: { 
                size: 12,
                color: colors[kecamatan.cluster - 1] 
                // Sesuaikan indeks warna dengan cluster (cluster dimulai dari 1)
            }
        };
        data.push(trace);
    });
    // console.log(data);
    // Konfigurasi layout plot
    var layout = {
        xaxis: { 
            title: 'Jumlah Kasus',
            tickformat: ',.0f' // Format angka tanpa desimal dan dengan pemisah ribuan
        },
        yaxis: { 
            title: 'Jumlah Penduduk',
            tickformat: ',.0f' // Format angka tanpa desimal dan dengan pemisah ribuan
        },
        title: 'K-Means Clustering Berdasarkan Jumlah Kasus dan Jumlah Penduduk',
        showlegend: false,
    };
// Buat plot menggunakan Plotly
    Plotly.newPlot('scatter-plot', data, layout);
</script>
@endsection
