{% extends "base_admin.html" %}
{% block title %}Manage Data Digital{% endblock %}
{% block content %}
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<style>
    table {
        width: 100%;
        border-collapse: collapse;
        margin-top: 20px;
    }
    th, td {
        padding: 8px 12px;
        border: 1px solid #ccc;
        text-align: center;
    }
    th {
        background-color: #f2f2f2;
    }
    tr:nth-child(even) {
        background-color: #fafafa;
    }
    input.editable-input, select.editable-select {
        width: 100%;
        box-sizing: border-box;
    }
</style>

<div class="container-fluid" style="max-width: 1300px; margin-left: auto; margin-right: auto;">
    <h2 class="text-center text-white p-3 rounded mb-4 mt-2 custom-bg">Manage Data Digital</h2>

    <!-- FORM UPLOAD VIA EXCEL -->
    <div class="card mb-4">
        <div class="card-header custom-bg py-2">
            <h6 class="m-0 font-weight-bold text-white">Upload Data Digital via Excel</h6>
        </div>
        <div class="card-body">
            <form id="form-upload-excel" method="POST" action="{% url 'upload_excel' %}" enctype="multipart/form-data">

                {% csrf_token %}
                <div class="row g-2 align-items-center">
                    <div class="col-md-6">
                        <input type="file" name="excel_file" accept=".xlsx,.xls" class="form-control" required>
                    </div>

                    <div class="col-md-2">
                        <button type="submit" class="btn btn-success">Upload</button>
                    </div>

                </div>
                <small class="text-muted">Format file harus Excel (.xlsx / .xls)</small>
                <a href="https://docs.google.com/spreadsheets/d/1WnlSfNtwRIPok1ZP6Qmd-jmSaneFufiY/edit?usp=sharing&ouid=113827974921353843070&rtpof=true&sd=true" target="_blank" download>
                    Download Contoh Format Excel
                </a>
            </form>
        </div>
    </div>

    <!-- TABEL DATA -->
    <div class="card shadow mb-4">
        <div class="card-header custom-bg py-3">
            <h6 class="m-0 font-weight-bold text-white">Data Digital</h6>
        </div>
        <div class="card-body">
            <div class="row g-2 mb-4">
                <!-- Area -->
                <div class="col-md-4">
                    <label for="filter-area" class="form-label">Area</label>
                    <select id="filter-area" class="form-control">
                        <option value="">Pilih Wilayah</option>
                        {% for area in area_list %}
                            <option value="{{ area }}">{{ area }}</option>
                        {% endfor %}
                    </select>
                </div>

                <!-- Nama Agen -->
                <div class="col-md-4">
                    <label for="filter-agent" class="form-label">Nama Agent</label>
                    <input type="text" id="filter-agent" name="agent" class="form-control" placeholder="Masukkan nama agent">
                </div>


                <!-- Branch -->
                <div class="col-md-2">
                    <label for="filter-branch" class="form-label">Branch</label>
                    <input type="text" id="filter-branch" class="form-control" placeholder="Branch...">
                </div>
                
                <div class="col-md-2">
                    <label for="filter-bulan" class="form-label">Bulan</label>
                    <select name="filter-bulan" class="form-control" id="filter-bulan">
                        <option value="">-- Pilih Bulan --</option>
                        {% for num, nama in bulan_list %}
                            <option value="{{ num }}" {% if selected_bulan == num %}selected{% endif %}>{{ nama }}</option>
                        {% endfor %}
                    </select>
                </div>

                <!-- Status Order -->
                <div class="col-md-4">
                    <label for="filter-status-order" class="form-label">Status Order</label>
                    <input type="text" id="filter-status-order" class="form-control" placeholder="Status order">
                </div>
              
                <!-- Status Case -->
                <div class="col-md-2">
                    <label for="filter-status-case" class="form-label">Case</label>
                    <select id="filter-status-case" class="form-control">
                        <option value="">-- Pilih Status --</option>
                        {% for status in status_case_list %}
                            <option value="{{ status }}">{{ status }}</option>
                        {% endfor %}
                    </select>
                </div>

                <!-- Channel -->
                <div class="col-md-2">
                    <label for="filter-channel" class="form-label">Channel</label>
                    <select id="filter-channel" class="form-control">
                        <option value="">-- Pilih Channel --</option>
                        {% for channel in channel_list %}
                            <option value="{{ channel }}">{{ channel }}</option>
                        {% endfor %}
                    </select>
                </div>

                <!-- Search Track Order -->
                <div class="col-md-4">
                    <label for="search-track-order" class="form-label">Cari Track Order</label>
                    <input type="text" id="search-track-order" class="form-control" placeholder="Ketik Track Order...">
                </div>
            </div>

            <div class="table-responsive">
                <table class="table table-bordered table-hover" id="data-table">
                    <thead class="thead-dark">
                        <tr>
                            <th>No</th>
                            <th>Tanggal Dibuat</th>
                            <th>Tanggal Update</th>
                            <th>Nama Sales</th>
                            <th>Nama Agent</th>
                            <th>Channel</th>
                            <th>Track Order</th>
                            <th>No Kontak</th>
                            <th>Branch</th>
                            <th>Area</th>
                            <th>Status Order</th>
                            <th>Kendala Fallout</th>
                            <th>Keterangan</th>
                            <th>Status Case</th>
                            <th>Nama Paket</th>
                            <th>ARPU</th>
                            <th>Aksi</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for item in data_ps %}
                        <tr data-id="{{ item.ps_id }}">
                            <td>{{ forloop.counter }}</td>
                            <td data-type="date">{{ item.tanggal_created_at|date:"d-m-Y" }}</td>
                            <td class="editable" data-field="tanggal_updated_at" data-type="date">{{ item.tanggal_updated_at|date:"d-m-Y" }}</td>
                            <td>{{ item.nama_sales }}</td>
                            <td class="editable" data-field="nama_agent" data-type="text">{{ item.nama_agent }}</td>
                            <td class="editable" data-field="channel" data-type="text">{{ item.channel }}</td>
                            <td class="editable" data-field="track_id" data-type="text">{{ item.track_id }}</td>
                            <td class="editable" data-field="kontak_pelanggan" data-type="text">{{ item.kontak_pelanggan }}</td>
                            <td>{{ item.nama_branch }}</td>
                            <td>{{ item.nama_area }}</td>
                            <td class="editable" data-field="status_order" data-type="text">{{ item.status_order }}</td>
                            <td class="editable" data-field="kendala_fallout" data-type="text">{{ item.kendala_fallout }}</td>
                            <td class="editable" data-field="keterangan" data-type="text">{{ item.keterangan }}</td>
                            <td class="editable" data-field="status_case" data-type="text">{{ item.status_case }}</td>
                            <td class="editable" data-field="nama_paket" data-type="text">{{ item.nama_paket }}</td>
                            <td class="editable" data-field="arpu" data-type="text">{{ item.arpu }}</td>
                            <td>
                                <button class="btn btn-sm btn-warning btn-edit">Edit</button>
                                <button class="btn btn-sm btn-success btn-save d-none">Simpan</button>
                                <button class="btn btn-sm btn-danger btn-cancel d-none">Batal</button>
                                <button class="btn btn-sm btn-danger btn-delete">Hapus</button>
                            </td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>

            <div id="pagination" class="d-flex justify-content-center align-items-center my-3"></div>
        </div>
    </div>
</div>

<!-- REAL-TIME FILTER SCRIPT -->
<script>
document.addEventListener('DOMContentLoaded', function () {
    const filters = {
        area: document.getElementById('filter-area'),
        agent: document.getElementById('filter-agent'),
        branch: document.getElementById('filter-branch'),
        statusOrder: document.getElementById('filter-status-order'),
        channel: document.getElementById('filter-channel'),
        bulan: document.getElementById('filter-bulan'),
        statusCase: document.getElementById('filter-status-case'),
        trackOrder: document.getElementById('search-track-order'),
    };

    const rows = Array.from(document.querySelectorAll('#data-table tbody tr'));
    const rowsPerPage = 10;
    let currentPage = 1;

    function filterTable() {
        const agent = filters.agent.value.toLowerCase();
        const area = filters.area.value.toLowerCase();
        const branch = filters.branch.value.toLowerCase();
        const bulanFilter = filters.bulan.value;
        const statusOrder = filters.statusOrder.value.toLowerCase();
        const statusCase = filters.statusCase.value.toLowerCase();
        const channel = filters.channel.value.toLowerCase();
        const track = filters.trackOrder.value.toLowerCase();

        rows.forEach(row => {
            const rawDate = row.children[1].textContent.trim(); // misal "08-06-2025"
            let rowBulan = "";
            if (rawDate.includes("-")) {
                const [day, month, year] = rawDate.split("-");
                const dateObj = new Date(`${year}-${month}-${day}`);
                rowBulan = (dateObj.getMonth() + 1).toString();
            }

            const rowData = {
                agent: row.children[4].textContent.toLowerCase(),
                area: row.children[9].textContent.toLowerCase(),
                branch: row.children[8].textContent.toLowerCase(),
                bulan: rowBulan, // Tanggal Dibuat, bisa diambil bulannya
                statusOrder: row.children[10].textContent.toLowerCase(),
                statusCase: row.children[13].textContent.toLowerCase(),
                channel: row.children[5].textContent.toLowerCase(),
                track: row.children[6].textContent.toLowerCase()
            };


            const matches =
                (!agent || rowData.agent.includes(agent)) &&
                (!area || rowData.area.includes(area)) &&
                (!branch || rowData.branch.includes(branch)) &&
                (!bulanFilter || rowData.bulan === bulanFilter) &&
                (!statusOrder || rowData.statusOrder.includes(statusOrder)) &&
                (!statusCase || rowData.statusCase.includes(statusCase)) &&
                (!channel || rowData.channel.includes(channel)) &&
                (!track || rowData.track.includes(track));

            row.dataset.filtered = matches ? "true" : "false";
        });

        currentPage = 1;
        displayRows(currentPage);
    }

    function displayRows(page) {
        const filteredRows = rows.filter(row => row.dataset.filtered !== "false");
        const totalPages = Math.max(1, Math.ceil(filteredRows.length / rowsPerPage));

        if (page < 1) page = 1;
        if (page > totalPages) page = totalPages;
        currentPage = page;

        rows.forEach(row => row.style.display = "none");

        const start = (page - 1) * rowsPerPage;
        const end = start + rowsPerPage;
        filteredRows.slice(start, end).forEach(row => row.style.display = "");

        updatePagination(totalPages);
    }

    function updatePagination(totalPages) {
        const paginationContainer = document.getElementById("pagination");
        paginationContainer.innerHTML = "";

        const prevBtn = document.createElement("button");
        prevBtn.textContent = "Prev";
        prevBtn.className = "btn btn-sm btn-outline-primary mx-1";
        prevBtn.disabled = currentPage === 1;
        prevBtn.addEventListener("click", () => displayRows(currentPage - 1));
        paginationContainer.appendChild(prevBtn);

        let startPage = Math.max(1, currentPage - 2);
        let endPage = Math.min(totalPages, startPage + 4);
        if ((endPage - startPage) < 4) startPage = Math.max(1, endPage - 4);

        for (let i = startPage; i <= endPage; i++) {
            const btn = document.createElement("button");
            btn.textContent = i;
            btn.className = "btn btn-sm mx-1 " + (i === currentPage ? "btn-primary" : "btn-outline-primary");
            btn.addEventListener("click", () => displayRows(i));
            paginationContainer.appendChild(btn);
        }

        const nextBtn = document.createElement("button");
        nextBtn.textContent = "Next";
        nextBtn.className = "btn btn-sm btn-outline-primary mx-1";
        nextBtn.disabled = currentPage === totalPages;
        nextBtn.addEventListener("click", () => displayRows(currentPage + 1));
        paginationContainer.appendChild(nextBtn);
    }

    Object.values(filters).forEach(input => {
        input.addEventListener('input', filterTable);
        input.addEventListener('change', filterTable);
    });

    filterTable(); // Initial render


    // Inline Edit
    const bulanOptions = {
        '1': 'Januari', '2': 'Februari', '3': 'Maret', '4': 'April', '5': 'Mei', '6': 'Juni',
        '7': 'Juli', '8': 'Agustus', '9': 'September', '10': 'Oktober', '11': 'November', '12': 'Desember'
    };

    function createSelect(options, selectedValue) {
        const select = document.createElement('select');
        select.className = 'editable-select form-control form-control-sm';
        for (const [value, label] of Object.entries(options)) {
            const option = document.createElement('option');
            option.value = value;
            option.textContent = label;
            if (value === selectedValue) option.selected = true;
            select.appendChild(option);
        }
        return select;
    }

    function createSelectFromArray(arr, selectedValue) {
        const select = document.createElement('select');
        select.className = 'editable-select form-control form-control-sm';
        arr.forEach(val => {
            const option = document.createElement('option');
            option.value = val;
            option.textContent = val;
            if (val === selectedValue) option.selected = true;
            select.appendChild(option);
        });
        return select;
    }

    function createInput(value) {
        const input = document.createElement('input');
        input.type = 'text';
        input.className = 'editable-input form-control form-control-sm';
        input.value = value;
        return input;
    }

    document.querySelectorAll('.btn-delete').forEach(btn => {
        btn.addEventListener('click', function () {
            const tr = this.closest('tr');
            const id = tr.dataset.id;

            Swal.fire({
                title: 'Yakin ingin menghapus data ini?',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: 'Ya, hapus',
                cancelButtonText: 'Batal'
            }).then(result => {
                if (result.isConfirmed) {
                    fetch("{% url 'delete_data_ps' %}", {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRFToken': '{{ csrf_token }}',
                        },
                        body: JSON.stringify({ id: id })
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            // Hapus baris dari DOM langsung tanpa reload
                            tr.remove();
                            Swal.fire('Terhapus!', 'Data sudah dihapus', 'success');
                        } else {
                            Swal.fire('Error', data.error || 'Gagal menghapus data', 'error');
                        }
                    })
                    .catch(() => {
                        Swal.fire('Error', 'Terjadi kesalahan jaringan', 'error');
                    });
                }
            });
        });
    });

});
</script>
<script>
document.addEventListener("DOMContentLoaded", function () {
    const form = document.getElementById("form-upload-excel");

    form.addEventListener("submit", function (e) {
        e.preventDefault();

        const formData = new FormData(form);
        const csrfToken = document.querySelector('[name=csrfmiddlewaretoken]').value;

        fetch(form.action, {
            method: "POST",
            headers: {
                'X-CSRFToken': csrfToken,
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.status === "success") {
                alert(data.message);
                form.reset();
                location.reload(); 
            } else {
                alert("Error: " + data.message);
            }
        })
        .catch(error => {
            console.error("Upload failed:", error);
            alert("Terjadi kesalahan saat mengupload file.");
        });
    });
});
</script>

<script>
document.addEventListener('DOMContentLoaded', function () {
    // EDIT MODE
    document.querySelectorAll('.btn-edit').forEach(btn => {
        btn.addEventListener('click', function () {
            const tr = this.closest('tr');
            tr.querySelectorAll('.editable').forEach(td => {
                const field = td.dataset.field;
                const type = td.dataset.type;
                const value = td.textContent.trim();
                td.dataset.original = value;

                if (type === 'text' || type === 'num') {
                    td.innerHTML = `<input type="text" class="form-control form-control-sm" name="${field}" value="${value}">`;
                } else if (type === 'select') {
                    td.innerHTML = `
                        <select class="form-control form-control-sm" name="${field}">
                            <option value="Open" ${value === 'Open' ? 'selected' : ''}>Open</option>
                            <option value="Closed" ${value === 'Closed' ? 'selected' : ''}>Closed</option>
                            <option value="Pending" ${value === 'Pending' ? 'selected' : ''}>Pending</option>
                        </select>`;
                } else if (type === 'date') {
                    td.innerHTML = `<input type="date" class="form-control form-control-sm" name="${field}" value="${value}">`;
                }
            });

            tr.querySelector('.btn-edit').classList.add('d-none');
            tr.querySelector('.btn-save').classList.remove('d-none');
            tr.querySelector('.btn-cancel').classList.remove('d-none');
        });
    });

    // CANCEL EDIT
    document.querySelectorAll('.btn-cancel').forEach(btn => {
        btn.addEventListener('click', function () {
            const tr = this.closest('tr');
            tr.querySelectorAll('.editable').forEach(td => {
                td.textContent = td.dataset.original || td.textContent;
            });

            tr.querySelector('.btn-edit').classList.remove('d-none');
            tr.querySelector('.btn-save').classList.add('d-none');
            tr.querySelector('.btn-cancel').classList.add('d-none');
        });
    });

    // SAVE DATA
    document.querySelectorAll('.btn-save').forEach(btn => {
        btn.addEventListener('click', function () {
            const tr = this.closest('tr');
            const id = tr.dataset.id;
            const data = { id: id };
            let isValid = true;

            tr.querySelectorAll('.editable').forEach(td => {
                const field = td.dataset.field;
                const input = td.querySelector('input, select');
                if (input) {
                    const value = input.value.trim();
                    if (!value) {
                        isValid = false;
                        input.classList.add('is-invalid');
                    } else {
                        input.classList.remove('is-invalid');
                        data[field] = value;
                    }
                }
            });

            if (!isValid) {
                Swal.fire('Gagal', 'Mohon lengkapi semua data sebelum menyimpan.', 'warning');
                return;
            }

            fetch("{% url 'edit_data_ps' %}", {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': '{{ csrf_token }}',
                },
                body: JSON.stringify(data)
            })
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    // UPDATE tampilan baris langsung, tanpa reload
                    tr.querySelectorAll('.editable').forEach(td => {
                        const input = td.querySelector('input, select');
                        if (input.tagName === 'SELECT') {
                            td.textContent = input.options[input.selectedIndex].text;
                        } else {
                            td.textContent = input.value;
                        }
                    });

                    tr.querySelector('.btn-edit').classList.remove('d-none');
                    tr.querySelector('.btn-save').classList.add('d-none');
                    tr.querySelector('.btn-cancel').classList.add('d-none');

                    Swal.fire('Berhasil', 'Data berhasil diupdate', 'success');
                } else {
                    Swal.fire('Gagal', result.error || 'Terjadi kesalahan saat menyimpan data', 'error');
                }
            })
            .catch(() => {
                Swal.fire('Error', 'Gagal menghubungi server', 'error');
            });
        });
    });
});
</script>






{% endblock %}
