@extends('adminlte::page')

@section('title', 'Dashboard')

@section('content_header')
    <h1 class="m-0 text-dark"><i class="fas fa-tachometer-alt mr-2"></i>Dashboard</h1>
@stop

@section('content')
    @if (session('status'))
        <div class="alert alert-success alert-dismissible">
            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
            {{ session('status') }}
        </div>
    @endif

    {{-- Filter indicator --}}
    <div id="daerahFilterBar" class="alert alert-warning alert-dismissible py-2 d-none">
        <i class="fas fa-filter mr-1"></i>
        Menunjukkan statistik untuk daerah: <strong id="daerahFilterName"></strong>
        <button type="button" id="clearDaerahFilter" class="btn btn-sm btn-outline-secondary ml-2">
            <i class="fas fa-times mr-1"></i>Semua Daerah
        </button>
    </div>

    <div class="row">
        <div class="col-lg-3 col-6">
            <a id="card-pengguna" href="{{ route('admin.users.index') }}" class="info-box bg-info mb-3"
                style="min-height:auto">
                <div class="info-box-content">
                    <span class="info-box-number" id="stat-pengguna">{{ $stats['pengguna'] }}</span>
                    <span class="info-box-text">Pengguna</span>
                </div>
            </a>
        </div>
        <div class="col-lg-3 col-6">
            <a id="card-sekolah" href="{{ route('admin.users.index', ['role' => 'pemohon']) }}"
                class="info-box bg-success mb-3" style="min-height:auto">
                <div class="info-box-content">
                    <span class="info-box-number" id="stat-sekolah">{{ $stats['sekolah'] }}</span>
                    <span class="info-box-text">Sekolah</span>
                </div>
            </a>
        </div>
        <div class="col-lg-3 col-6">
            <a id="card-checker" href="{{ route('admin.users.index', ['role' => 'checker']) }}"
                class="info-box bg-warning mb-3" style="min-height:auto">
                <div class="info-box-content">
                    <span class="info-box-number" id="stat-checker">{{ $stats['checker'] }}</span>
                    <span class="info-box-text">Pemeriksa</span>
                </div>
            </a>
        </div>
        <div class="col-lg-3 col-6">
            <a id="card-supervisor" href="{{ route('admin.users.index', ['role' => 'supervisor']) }}"
                class="info-box bg-danger mb-3" style="min-height:auto">
                <div class="info-box-content">
                    <span class="info-box-number" id="stat-supervisor">{{ $stats['supervisor'] }}</span>
                    <span class="info-box-text">Penyelia</span>
                </div>
            </a>
        </div>
    </div>

    <div class="row">
        <div class="col-lg-3 col-6">
            <a id="card-sra" href="{{ route('admin.users.index', ['role' => 'pemohon', 'jenis_sekolah' => 'SRA']) }}"
                class="info-box bg-olive mb-3" style="min-height:auto">
                <div class="info-box-content">
                    <span class="info-box-number" id="stat-sra">{{ $stats['sra'] }}</span>
                    <span class="info-box-text">SRA</span>
                </div>
            </a>
        </div>
        <div class="col-lg-3 col-6">
            <a id="card-srai" href="{{ route('admin.users.index', ['role' => 'pemohon', 'jenis_sekolah' => 'SRAI']) }}"
                class="info-box bg-teal mb-3" style="min-height:auto">
                <div class="info-box-content">
                    <span class="info-box-number" id="stat-srai">{{ $stats['srai'] }}</span>
                    <span class="info-box-text">SRAI</span>
                </div>
            </a>
        </div>
        <div class="col-lg-3 col-6">
            <a id="card-kafai" href="{{ route('admin.users.index', ['role' => 'pemohon', 'jenis_sekolah' => 'KAFAI']) }}"
                class="info-box bg-indigo mb-3" style="min-height:auto">
                <div class="info-box-content">
                    <span class="info-box-number" id="stat-kafai">{{ $stats['kafai'] }}</span>
                    <span class="info-box-text">KAFAI</span>
                </div>
            </a>
        </div>
        <div class="col-lg-3 col-6">
            <a id="card-kkm" href="{{ route('admin.users.index', ['role' => 'pemohon', 'jenis_sekolah' => 'KKM']) }}"
                class="info-box bg-purple mb-3" style="min-height:auto">
                <div class="info-box-content">
                    <span class="info-box-number" id="stat-kkm">{{ $stats['kkm'] }}</span>
                    <span class="info-box-text">KKM</span>
                </div>
            </a>
        </div>
    </div>

    <div class="row">
        <div class="col-md-8">
            <div class="card card-outline card-primary">
                <div class="card-header">
                    <h3 class="card-title"><i class="fas fa-map-marked-alt mr-1"></i> Peta Daerah Selangor</h3>
                    <div class="card-tools">
                        <small class="text-muted">Klik daerah untuk lihat senarai sekolah</small>
                    </div>
                </div>
                <div class="card-body p-2 text-center">
                    <svg id="selangorMap" viewBox="0 0 800 600" style="max-width:100%;height:auto;cursor:pointer">

                        @php
                            $daerahIdMap = $senarai_daerah->pluck('id', 'nama_daerah');
                        @endphp

                        {{-- SABAK BERNAM - Top left (northwest) --}}
                        <path id="district-SABAK BERNAM" class="district"
                            d="M80,50 L180,30 L220,60 L240,120 L220,180 L170,200 L120,180 L70,140 L60,90 Z"
                            data-daerah="SABAK BERNAM" data-id="{{ $daerahIdMap['SABAK BERNAM'] ?? '' }}" />
                        <text class="district-label" x="150" y="110" data-daerah="SABAK BERNAM">Sabak Bernam</text>

                        {{-- HULU SELANGOR - Top center (north-central) --}}
                        <path id="district-HULU SELANGOR" class="district"
                            d="M240,120 L320,40 L440,30 L500,80 L490,160 L440,220 L360,230 L280,210 L220,180 Z"
                            data-daerah="HULU SELANGOR" data-id="{{ $daerahIdMap['HULU SELANGOR'] ?? '' }}" />
                        <text class="district-label" x="370" y="130" data-daerah="HULU SELANGOR">Hulu Selangor</text>

                        {{-- GOMBAK - Top right (northeast) --}}
                        <path id="district-GOMBAK" class="district"
                            d="M500,80 L590,50 L680,80 L700,160 L660,240 L580,270 L490,250 L440,220 L490,160 Z"
                            data-daerah="GOMBAK" data-id="{{ $daerahIdMap['GOMBAK'] ?? '' }}" />
                        <text class="district-label" x="580" y="165" data-daerah="GOMBAK">Gombak</text>

                        {{-- KUALA SELANGOR - Mid left (west) --}}
                        <path id="district-KUALA SELANGOR" class="district"
                            d="M70,140 L120,180 L170,200 L220,180 L280,210 L290,270 L250,320 L180,330 L100,300 L50,240 Z"
                            data-daerah="KUALA SELANGOR" data-id="{{ $daerahIdMap['KUALA SELANGOR'] ?? '' }}" />
                        <text class="district-label" x="170" y="260" data-daerah="KUALA SELANGOR">Kuala Selangor</text>

                        {{-- PETALING - Center --}}
                        <path id="district-PETALING" class="district"
                            d="M290,270 L360,230 L440,220 L490,250 L510,310 L480,370 L400,390 L330,370 L280,340 L250,320 Z"
                            data-daerah="PETALING" data-id="{{ $daerahIdMap['PETALING'] ?? '' }}" />
                        <text class="district-label" x="390" y="310" data-daerah="PETALING">Petaling</text>

                        {{-- HULU LANGAT - Right center (east) --}}
                        <path id="district-HULU LANGAT" class="district"
                            d="M490,250 L580,270 L660,240 L720,290 L730,380 L690,440 L600,460 L520,430 L480,370 L510,310 Z"
                            data-daerah="HULU LANGAT" data-id="{{ $daerahIdMap['HULU LANGAT'] ?? '' }}" />
                        <text class="district-label" x="610" y="360" data-daerah="HULU LANGAT">Hulu Langat</text>

                        {{-- KLANG - Mid left lower --}}
                        <path id="district-KLANG" class="district"
                            d="M100,300 L180,330 L250,320 L280,340 L330,370 L310,430 L240,450 L160,430 L90,390 L60,340 Z"
                            data-daerah="KLANG" data-id="{{ $daerahIdMap['KLANG'] ?? '' }}" />
                        <text class="district-label" x="195" y="385" data-daerah="KLANG">Klang</text>

                        {{-- KUALA LANGAT - Bottom left (southwest) --}}
                        <path id="district-KUALA LANGAT" class="district"
                            d="M90,390 L160,430 L240,450 L310,430 L320,490 L280,540 L200,560 L120,530 L70,470 Z"
                            data-daerah="KUALA LANGAT" data-id="{{ $daerahIdMap['KUALA LANGAT'] ?? '' }}" />
                        <text class="district-label" x="195" y="490" data-daerah="KUALA LANGAT">Kuala Langat</text>

                        {{-- SEPANG - Bottom center-right (south) --}}
                        <path id="district-SEPANG" class="district"
                            d="M310,430 L400,390 L480,370 L520,430 L540,500 L490,550 L400,570 L320,550 L280,540 L320,490 Z"
                            data-daerah="SEPANG" data-id="{{ $daerahIdMap['SEPANG'] ?? '' }}" />
                        <text class="district-label" x="410" y="480" data-daerah="SEPANG">Sepang</text>

                    </svg>
                </div>
            </div>
        </div>{{-- end col-md-8 --}}
        <div class="col-md-4">
            {{-- Info Panel --}}
            <div class="card card-outline card-secondary" id="mapInfoCard">
                <div class="card-header">
                    <h3 class="card-title"><i class="fas fa-info-circle mr-1"></i> <span id="infoTitle">Maklumat
                            Daerah</span></h3>
                </div>
                <div class="card-body" id="infoBody">
                    <p class="text-muted text-center mb-0"><i class="fas fa-mouse-pointer mr-1"></i> Arahkan tetikus ke
                        atas peta untuk lihat maklumat daerah</p>
                </div>
            </div>

            {{-- Legend --}}
            <div class="card card-outline card-secondary">
                <div class="card-header">
                    <h3 class="card-title"><i class="fas fa-palette mr-1"></i> Petunjuk</h3>
                </div>
                <div class="card-body p-3">
                    <div class="d-flex align-items-center mb-2">
                        <span
                            style="display:inline-block;width:20px;height:20px;background:#4dc9f6;border-radius:3px;margin-right:8px;border:1px solid #3aa8d0"></span>
                        <small>Daerah biasa</small>
                    </div>
                    <div class="d-flex align-items-center">
                        <span
                            style="display:inline-block;width:20px;height:20px;background:#ffc107;border-radius:3px;margin-right:8px;border:1px solid #d4a106"></span>
                        <small>Daerah yang dipilih (hover)</small>
                    </div>
                </div>
            </div>
        </div>{{-- end col-md-4 --}}
    </div>{{-- end row --}}
@stop

@section('css')
    <style>
        .district {
            fill: #4dc9f6;
            stroke: #fff;
            stroke-width: 2.5;
            transition: fill 0.2s, stroke 0.2s, filter 0.2s;
            cursor: pointer;
        }

        .district:hover,
        .district.active {
            fill: #ffc107;
            stroke: #d4a106;
            stroke-width: 3;
            filter: drop-shadow(0 0 6px rgba(255, 193, 7, .5));
        }

        .district-label {
            font-size: 13px;
            font-weight: 600;
            fill: #1a1a2e;
            text-anchor: middle;
            pointer-events: none;
            text-shadow: 0 1px 2px rgba(255, 255, 255, .8);
        }

        #mapInfoCard .info-stat {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 6px 0;
            border-bottom: 1px solid #f0f0f0;
        }

        #mapInfoCard .info-stat:last-child {
            border-bottom: none;
        }

        #mapInfoCard .info-stat .badge {
            min-width: 40px;
            font-size: 14px;
        }

        .badge-purple {
            background-color: #6f42c1;
            color: #fff;
        }

        .btn-outline-purple {
            color: #6f42c1;
            border-color: #6f42c1;
        }

        .btn-outline-purple:hover {
            background-color: #6f42c1;
            color: #fff;
        }
    </style>
@stop

@section('js')
    <script>
        (function() {
            var daerahStats = @json($daerahStats);
            var globalStats = @json($stats);
            var routeBase = "{{ route('admin.users.index') }}";
            var routeKkmPesan = "{{ route('admin.laporan.kkm-pesan-buku') }}";
            var routeKkmLebih = "{{ route('admin.laporan.kkm-lebih-buku') }}";
            var routeKkmRosak = "{{ route('admin.laporan.kkm-buku-rosak') }}";
            var districts = document.querySelectorAll('.district');
            var infoTitle = document.getElementById('infoTitle');
            var infoBody = document.getElementById('infoBody');
            var filterBar = document.getElementById('daerahFilterBar');
            var filterName = document.getElementById('daerahFilterName');
            var clearBtn = document.getElementById('clearDaerahFilter');
            var defaultHtml =
                '<p class="text-muted text-center mb-0"><i class="fas fa-mouse-pointer mr-1"></i> Arahkan tetikus ke atas peta untuk lihat maklumat daerah</p>';

            var selectedDaerah = null;

            // Stat card elements
            var statEls = {
                pengguna: document.getElementById('stat-pengguna'),
                sekolah: document.getElementById('stat-sekolah'),
                checker: document.getElementById('stat-checker'),
                supervisor: document.getElementById('stat-supervisor'),
                sra: document.getElementById('stat-sra'),
                srai: document.getElementById('stat-srai'),
                kafai: document.getElementById('stat-kafai'),
                kkm: document.getElementById('stat-kkm'),
            };

            // Card link elements (for updating href on filter)
            var cardEls = {
                pengguna: document.getElementById('card-pengguna'),
                sekolah: document.getElementById('card-sekolah'),
                checker: document.getElementById('card-checker'),
                supervisor: document.getElementById('card-supervisor'),
                sra: document.getElementById('card-sra'),
                srai: document.getElementById('card-srai'),
                kafai: document.getElementById('card-kafai'),
                kkm: document.getElementById('card-kkm'),
            };

            var globalHrefs = {
                pengguna: cardEls.pengguna.href,
                sekolah: cardEls.sekolah.href,
                checker: cardEls.checker.href,
                supervisor: cardEls.supervisor.href,
                sra: cardEls.sra.href,
                srai: cardEls.srai.href,
                kafai: cardEls.kafai.href,
                kkm: cardEls.kkm.href,
            };

            function updateStatCards(daerah) {
                var s;
                if (daerah) {
                    s = daerahStats[daerah] || {
                        pengguna: 0,
                        sekolah: 0,
                        checker: 0,
                        supervisor: 0,
                        sra: 0,
                        srai: 0,
                        kafai: 0
                    };
                    var enc = encodeURIComponent(daerah);
                    cardEls.pengguna.href = routeBase + '?daerah=' + enc;
                    cardEls.sekolah.href = routeBase + '?role=pemohon&daerah=' + enc;
                    cardEls.checker.href = routeBase + '?role=checker&daerah=' + enc;
                    cardEls.supervisor.href = routeBase + '?role=supervisor&daerah=' + enc;
                    cardEls.sra.href = routeBase + '?role=pemohon&jenis_sekolah=SRA&daerah=' + enc;
                    cardEls.srai.href = routeBase + '?role=pemohon&jenis_sekolah=SRAI&daerah=' + enc;
                    cardEls.kafai.href = routeBase + '?role=pemohon&jenis_sekolah=KAFAI&daerah=' + enc;
                    cardEls.kkm.href = routeBase + '?role=pemohon&jenis_sekolah=KKM&daerah=' + enc;
                } else {
                    s = globalStats;
                    cardEls.pengguna.href = globalHrefs.pengguna;
                    cardEls.sekolah.href = globalHrefs.sekolah;
                    cardEls.checker.href = globalHrefs.checker;
                    cardEls.supervisor.href = globalHrefs.supervisor;
                    cardEls.sra.href = globalHrefs.sra;
                    cardEls.srai.href = globalHrefs.srai;
                    cardEls.kafai.href = globalHrefs.kafai;
                    cardEls.kkm.href = globalHrefs.kkm;
                }
                statEls.pengguna.textContent = s.pengguna || 0;
                statEls.sekolah.textContent = s.sekolah || 0;
                statEls.checker.textContent = s.checker || 0;
                statEls.supervisor.textContent = s.supervisor || 0;
                statEls.sra.textContent = s.sra || 0;
                statEls.srai.textContent = s.srai || 0;
                statEls.kafai.textContent = s.kafai || 0;
                statEls.kkm.textContent = s.kkm || 0;
            }

            function selectDaerah(daerah) {
                if (selectedDaerah === daerah) {
                    // Deselect
                    clearSelection();
                    return;
                }
                // Deselect previous
                districts.forEach(function(el) {
                    el.classList.remove('active');
                });
                selectedDaerah = daerah;
                document.getElementById('district-' + daerah).classList.add('active');
                filterName.textContent = daerah.charAt(0) + daerah.slice(1).toLowerCase();
                filterBar.classList.remove('d-none');
                updateStatCards(daerah);
            }

            function clearSelection() {
                districts.forEach(function(el) {
                    el.classList.remove('active');
                });
                selectedDaerah = null;
                filterBar.classList.add('d-none');
                updateStatCards(null);
                infoTitle.textContent = 'Maklumat Daerah';
                infoBody.innerHTML = defaultHtml;
            }

            clearBtn.addEventListener('click', clearSelection);

            function buildInfo(daerah) {
                var s = daerahStats[daerah] || {
                    sekolah: 0,
                    pemohon: 0,
                    checker: 0,
                    supervisor: 0,
                    jumlah_pesan: 0,
                    jumlah_lebih: 0,
                    jumlah_rosak: 0
                };
                return '<div class="info-stat"><span><i class="fas fa-school text-success mr-2"></i>Jumlah Sekolah</span><span class="badge badge-success">' +
                    (s.sekolah || 0) + '</span></div>' +
                    '<div class="info-stat"><span><i class="fas fa-user text-primary mr-2"></i>Pemohon</span><span class="badge badge-primary">' +
                    (s.pemohon || 0) + '</span></div>' +
                    '<div class="info-stat"><span><i class="fas fa-user-check text-warning mr-2"></i>Pemeriksa</span><span class="badge badge-warning">' +
                    (s.checker || 0) + '</span></div>' +
                    '<div class="info-stat"><span><i class="fas fa-user-tie text-danger mr-2"></i>Penyelia</span><span class="badge badge-danger">' +
                    (s.supervisor || 0) + '</span></div>' +
                    '<div class="info-stat"><span><i class="fas fa-book text-info mr-2"></i>Jumlah Pesan Buku</span><span class="badge badge-info">' +
                    (s.jumlah_pesan || 0).toLocaleString() + '</span></div>' +
                    '<div class="info-stat"><span><i class="fas fa-book-open mr-2" style="color:#e74c3c"></i>Lebih Buku</span><span class="badge ' +
                    ((s.jumlah_lebih || 0) < 0 ? 'badge-danger' : 'badge-success') + '">' +
                    (s.jumlah_lebih || 0).toLocaleString() + '</span></div>' +
                    '<div class="info-stat"><span><i class="fas fa-book-dead mr-2" style="color:#dc3545"></i>Buku Rosak</span><span class="badge badge-danger">' +
                    (s.jumlah_rosak || 0).toLocaleString() + '</span></div>' +
                    '<hr class="my-2">' +
                    '<div class="mb-1"><strong><i class="fas fa-mosque mr-1 text-purple"></i>Kelas Kafa Menengah (KKM)</strong></div>' +
                    '<div class="info-stat"><span><i class="fas fa-book text-purple mr-2"></i>Pesanan Buku KKM</span><span class="badge badge-purple">' +
                    (s.kkm_pesan || 0).toLocaleString() + '</span></div>' +
                    '<div class="info-stat"><span><i class="fas fa-boxes mr-2" style="color:#6f42c1"></i>Lebih Buku KKM</span><span class="badge badge-purple">' +
                    (s.kkm_lebih || 0).toLocaleString() + '</span></div>' +
                    '<div class="info-stat"><span><i class="fas fa-book-dead mr-2" style="color:#6f42c1"></i>Buku Rosak KKM</span><span class="badge badge-purple">' +
                    (s.kkm_rosak || 0).toLocaleString() + '</span></div>' +
                    '<hr class="my-2">' +
                    '<div class="d-flex flex-column" style="gap:4px">' +
                    '<a href="' + routeBase + '?daerah=' + encodeURIComponent(daerah) +
                    '" class="btn btn-sm btn-primary btn-block"><i class="fas fa-users mr-1"></i>Senarai Pengguna</a>' +
                    '<a href="' + routeKkmPesan + '?daerah=' + encodeURIComponent(daerah) +
                    '" class="btn btn-sm btn-outline-purple btn-block"><i class="fas fa-book mr-1"></i>Laporan Pesan Buku KKM</a>' +
                    '<a href="' + routeKkmLebih + '?daerah=' + encodeURIComponent(daerah) +
                    '" class="btn btn-sm btn-outline-purple btn-block"><i class="fas fa-boxes mr-1"></i>Laporan Lebih Buku KKM</a>' +
                    '<a href="' + routeKkmRosak + '?daerah=' + encodeURIComponent(daerah) +
                    '" class="btn btn-sm btn-outline-purple btn-block"><i class="fas fa-book-dead mr-1"></i>Laporan Buku Rosak KKM</a>' +
                    '</div>';
            }

            districts.forEach(function(el) {
                var daerah = el.getAttribute('data-daerah');

                el.addEventListener('mouseenter', function() {
                    infoTitle.textContent = daerah;
                    infoBody.innerHTML = buildInfo(daerah);
                });

                el.addEventListener('mouseleave', function() {
                    if (selectedDaerah) {
                        infoTitle.textContent = selectedDaerah;
                        infoBody.innerHTML = buildInfo(selectedDaerah);
                    } else {
                        infoTitle.textContent = 'Maklumat Daerah';
                        infoBody.innerHTML = defaultHtml;
                    }
                });

                el.addEventListener('click', function() {
                    selectDaerah(daerah);
                });
            });
        })();
    </script>
@stop
