{% extends 'base_admin.html' %}
{% block title %}Manage KPI Agency - CWN{% endblock %}
{% block content %}
<div class="container-fluid mt-4">

    <h2 class="text-center text-white p-3 rounded mb-4 mt-2 custom-bg">Manajemen Data KPI Agency</h2>

    <!-- Form Tambah KPI -->
    <form id="inputForm" class="border p-3 mb-4 rounded shadow-sm bg-light">
        <div class="row g-2">
            <div class="col-md-4">
                <label for="bulan">Bulan KPI</label>
                <select name="bulan" id="bulan" class="form-control" placeholder="Bulan" required>
                    <option value="">-- Pilih Bulan --</option>
                    <option value="01" {% if selected_bulan == "01" %}selected{% endif %}>Januari</option>
                    <option value="02" {% if selected_bulan == "02" %}selected{% endif %}>Februari</option>
                    <option value="03" {% if selected_bulan == "03" %}selected{% endif %}>Maret</option>
                    <option value="04" {% if selected_bulan == "04" %}selected{% endif %}>April</option>
                    <option value="05" {% if selected_bulan == "05" %}selected{% endif %}>Mei</option>
                    <option value="06" {% if selected_bulan == "06" %}selected{% endif %}>Juni</option>
                    <option value="07" {% if selected_bulan == "07" %}selected{% endif %}>Juli</option>
                    <option value="08" {% if selected_bulan == "08" %}selected{% endif %}>Agustus</option>
                    <option value="09" {% if selected_bulan == "09" %}selected{% endif %}>September</option>
                    <option value="10" {% if selected_bulan == "10" %}selected{% endif %}>Oktober</option>
                    <option value="11" {% if selected_bulan == "11" %}selected{% endif %}>November</option>
                    <option value="12" {% if selected_bulan == "12" %}selected{% endif %}>Desember</option>
                </select>
            </div>
            <div class="col-md-4">
                <label for="tahun">Tahun KPI</label>
                <select name="tahun" id="tahun" class="form-control" placeholder="Tahun" required>
                    <option value="">-- Pilih Tahun --</option>
                    <option value="2024" {% if selected_tahun == "2024" %}selected{% endif %}>2024</option>
                    <option value="2025" {% if selected_tahun == "2025" %}selected{% endif %}>2025</option>
                </select>
            </div>
            <div class="col-md-4">
                <label for="kategori">Kategori Penjualan</label>
                <select name="kategori" class="form-control" required>
                    <option value="">-- Pilih Kategori --</option>
                    <option value="Bilper">Billing Pertama</option>
                    <option value="Bildu">Billing Kedua </option>
                </select>
            </div>
            
        </div>

        <div class="row g-2 mt-2">
            <div class="col">
                <label for="target">Target</label>
                <input type="number" name="target" class="form-control" placeholder="Target" step="any">
            </div>
            <div class="col">
                <label for="real">Realisasi</label>
                <input type="number" name="real" class="form-control" placeholder="Real" step="any">
            </div>
            <!-- <div class="col">
                <input type="number" name="ach" class="form-control" placeholder="Ach" step="any">
            </div> -->
            <div class="col">
                <label for="bobot">Bobot</label>
                <input type="number" name="bobot" class="form-control" placeholder="Bobot" step="any">
            </div>
            <!-- <div class="col">
                <input type="number" name="nilai" class="form-control" placeholder="Nilai" step="any">
            </div> -->
            <div class="col mt-2">
                <button type="submit" class="btn btn-primary w-100 mt-4">Tambah KPI</button>
            </div>
        </div>
    </form>

    <!-- Form Filter Bulan/Tahun -->
    <form method="GET" action="{% url 'manage_kpi' %}" class="border p-3 mb-4 rounded shadow-sm bg-light">
        <div class="row">
            <div class="col-md-4">
                <label for="filter_bulan">Filter Bulan</label>
                <select name="filter_bulan" id="filter_bulan" class="form-control" placeholder="Bulan" required>
                    <option value="">-- Pilih Bulan --</option>
                    <option value="01" {% if selected_filter_bulan == "01" %}selected{% endif %}>Januari</option>
                    <option value="02" {% if selected_filter_bulan == "02" %}selected{% endif %}>Februari</option>
                    <option value="03" {% if selected_filter_bulan == "03" %}selected{% endif %}>Maret</option>
                    <option value="04" {% if selected_filter_bulan == "04" %}selected{% endif %}>April</option>
                    <option value="05" {% if selected_filter_bulan == "05" %}selected{% endif %}>Mei</option>
                    <option value="06" {% if selected_filter_bulan == "06" %}selected{% endif %}>Juni</option>
                    <option value="07" {% if selected_filter_bulan == "07" %}selected{% endif %}>Juli</option>
                    <option value="08" {% if selected_filter_bulan == "08" %}selected{% endif %}>Agustus</option>
                    <option value="09" {% if selected_filter_bulan == "09" %}selected{% endif %}>September</option>
                    <option value="10" {% if selected_filter_bulan == "10" %}selected{% endif %}>Oktober</option>
                    <option value="11" {% if selected_filter_bulan == "11" %}selected{% endif %}>November</option>
                    <option value="12" {% if selected_filter_bulan == "12" %}selected{% endif %}>Desember</option>
                </select>
            </div>
            <div class="col-md-4">
                <label for="filter_tahun">Filter Tahun</label>
                <select name="filter_tahun" id="filter_tahun" class="form-control" placeholder="Tahun" required>
                    <option value="">-- Pilih Tahun --</option>
                    <option value="2024" {% if selected_filter_tahun == "2024" %}selected{% endif %}>2024</option>
                    <option value="2025" {% if selected_filter_tahun == "2025" %}selected{% endif %}>2025</option>
                </select>
            </div>
            <div class="col-md-4 mt-2">
                <button type="submit" class="btn btn-primary w-100 mt-4">Filter</button>
            </div>
        </div>
    </form>

    <!-- Search Lokal -->
    <!-- <input type="text" id="searchInput" class="form-control mb-3" placeholder="Cari kategori atau angka..."> -->

    <!-- List KPI per AGENCY -->
    {% if kpi_data %}
    <div class="card shadow mb-5">
        <div class="card-header custom-bg text-white">
            <h4 class="m-0 font-weight-bold">KPI INDIHOME CWN</h4>
            <small>Periode: {{ selected_filter_bulan }}/{{ selected_filter_tahun }}</small>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-bordered table-hover" id="kpiTable">
                    <thead class="thead-dark">
                        <tr>
                            <th>Kategori Penjualan</th>
                            <th>Target</th>
                            <th>Real</th>
                            <th>Ach</th>
                            <th>Bobot</th>
                            <th>Nilai</th>
                            <th>Aksi</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for item in kpi_data %}
                            <tr data-id={{ item.kpi_id }}>
                                <td>{{ item.kategori }}</td>
                                <td class="editable" data-field="target">{{ item.target|floatformat:0 }}</td>
                                <td class="editable" data-field="real">{{ item.real|floatformat:0 }}</td>
                                <td>{{ item.ach|floatformat:0 }}%</td>
                                <td class="editable" data-field="bobot">{{ item.bobot|floatformat:0 }}%</td>
                                <td>{{ item.nilai|floatformat:0 }}%</td>
                                <td>
                                    <button class="btn btn-warning btn-sm edit-btn">Edit</button>
                                    <button class="btn btn-success btn-sm save-btn d-none">Simpan</button>
                                    <button class="btn btn-sm btn-secondary cancel-btn d-none">Cancel</button>
                                    <button class="btn btn-danger btn-sm delete-btn">Hapus</button>
                                </td>
                            </tr>
                        {% endfor %}
                        <tr class="table-success font-weight-bold">
                            <td colspan="4" class="text-center">SUMMARY KPI</td>
                            <td>{{ total_bobot|floatformat:0 }}%</td>
                            <td>{{ total_nilai|floatformat:0 }}%</td>
                            <td></td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    {% else %}
        <div class="alert alert-warning">
            Tidak ada data ditemukan untuk bulan dan tahun yang dipilih.
        </div>
    {% endif %}
</div>

<!-- SweetAlert -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
document.addEventListener('DOMContentLoaded', () => {

    const inputForm = document.getElementById('inputForm');

    inputForm.addEventListener('submit', function(e){
        e.preventDefault();

        const formData = new FormData(this);
        const jsonData = Object.fromEntries(formData.entries());

        fetch("{% url 'input_kpi_agency' %}", {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': '{{ csrf_token }}',
            },
            body: JSON.stringify(jsonData),
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                Swal.fire('Berhasil', 'Data KPI berhasil ditambahkan!', 'success').then(() => {
                    location.reload();
                });
                document.getElementById('inputForm').reset();
            } else {
                Swal.fire('Gagal', data.error || 'Terjadi kesalahan.', 'error');
            }
        })
        .catch(error => {
            Swal.fire('Gagal', 'Terjadi kesalahan jaringan.', 'error');
            console.error(error);
        });
    });

    // Search dalam seluruh tabel
    // document.getElementById('searchInput').addEventListener('keyup', function() {
    //     const filter = this.value.toLowerCase();
    //     document.querySelectorAll('#kpiTable tbody tr').forEach(row => {
    //         row.style.display = row.innerText.toLowerCase().includes(filter) ? '' : 'none';
    //     });
    // });

    // Edit/Save/Delete di dalam tabel
    document.querySelectorAll('#kpiTable tbody').forEach(tableBody => {
        tableBody.querySelectorAll('tr').forEach(row => {
            const editBtn = row.querySelector('.edit-btn');
            const saveBtn = row.querySelector('.save-btn');
            const cancelBtn = row.querySelector('.cancel-btn');
            const deleteBtn = row.querySelector('.delete-btn');

            if (!editBtn || !saveBtn || !cancelBtn || !deleteBtn) return;

            editBtn.addEventListener('click', () => {
                row.querySelectorAll('.editable').forEach(cell => {
                    const input = document.createElement('input');
                    input.className = 'form-control';
                    input.value = cell.innerText.trim().replace('%', '');
                    cell.innerHTML = '';
                    const originalValue = cell.textContent.trim().replace('%', '');
                    cell.dataset.originalValue = originalValue;
                    cell.appendChild(input);
                });

                editBtn.classList.add('d-none');
                deleteBtn.classList.add('d-none');
                saveBtn.classList.remove('d-none');
                cancelBtn.classList.remove('d-none');
            });

            cancelBtn.addEventListener('click', () => {
                row.querySelectorAll('.editable').forEach(cell => {
                    const originalValue = cell.dataset.originalValue; // Ambil nilai asli yang disimpan
                    cell.textContent = originalValue; // Kembalikan ke nilai asli
                });

                editBtn.classList.remove('d-none');
                deleteBtn.classList.remove('d-none');
                saveBtn.classList.add('d-none');
                cancelBtn.classList.add('d-none');

                location.reload()
            });

            saveBtn.addEventListener('click', () => {
                const kpi_id = row.dataset.id;
                let updates = {};

                row.querySelectorAll('.editable').forEach(cell => {
                    const field = cell.dataset.field;
                    const input = cell.querySelector('input');
                    if (input) {
                        updates[field] = input.value.trim();
                    }
                });

                fetch("{% url 'update_kpi_agency' %}", {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRFToken': '{{ csrf_token }}',
                    },
                    body: JSON.stringify({ kpi_id, ...updates }),
                })
                .then(res => res.json())
                .then(data => {
                    if (data.success) {
                        Swal.fire('Berhasil', 'Data berhasil diperbarui.', 'success').then(() => {
                            location.reload();
                        });
                    } else {
                        let errorMsg = data.error || 'Gagal update data. Coba lagi.';
                        Swal.fire('Error', errorMsg, 'error');
                    }
                })
                .catch(error => {
                    console.error('Update Error:', error);
                    Swal.fire('Error', 'Terjadi kesalahan jaringan atau server.', 'error');
                });
            });

            deleteBtn.addEventListener('click', () => {
                const kpi_id = row.dataset.id;
                Swal.fire({
                    title: 'Yakin hapus data ini?',
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonText: 'Ya, hapus',
                }).then(result => {
                    if (result.isConfirmed) {
                        fetch("{% url 'delete_kpi_agency' %}", {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRFToken': '{{ csrf_token }}',
                            },
                            body: JSON.stringify({ kpi_id }),
                        })
                        .then(res => res.json())
                        .then(data => {
                            if (data.success) {
                                location.reload();
                            } else {
                                Swal.fire('Error', 'Gagal hapus data.', 'error');
                            }
                        });
                    }
                });
            });
        });
    });
});
</script>
{% endblock %}
