$(document).ready(function () {

    // Initialize DataTable
    var table = $('#contactsTable').DataTable({
        "processing": true,
        "serverSide": true,
        "ajax": {
            "url": "../api/contacts.php",
            "type": "POST",
            "data": function (d) {
                d.action = "fetch_contacts";
            }
        },
        "columns": [
            {
                "data": "phone_number",
                "className": "d-flex align-items-center",
                "render": function (data, type, row) {
                    let html = '';
                    if (row.name) {
                        html += `<div class="fw-bold">${row.name}</div>`;
                        html += `<div class="small text-muted">${data}</div>`;
                    } else {
                        html += `<div class="fw-bold">${data}</div>`;
                    }

                    // Shared Count Badge (Global Usage)
                    // If more than 1 user has this number, show badge
                    if (row.shared_count && row.shared_count > 1) {
                        html += `<span class="badge bg-purple rounded-pill ms-2" title="Saved by ${row.shared_count} users">
                                    <i class="fe fe-users me-1"></i>${row.shared_count}
                                  </span>`;
                    }
                    return html;
                }
            },
            {
                "data": null,
                "orderable": false,
                "render": function (data, type, row) {

                    // Call Link
                    let callLink = `tel:${row.phone_number}`;

                    // WhatsApp Logic (From monitor.php)
                    let clean = row.phone_number.replace(/[^0-9]/g, '');
                    if (!clean.startsWith('88')) {
                        clean = '88' + clean;
                    }
                    let waLink = `https://wa.me/${clean}`;

                    return `
                        <div class="btn-list">
                             <a href="${callLink}" class="btn btn-sm btn-info" title="Call">
                                <i class="fe fe-phone"></i>
                            </a>
                            <a href="${waLink}" target="_blank" class="btn btn-sm btn-success" title="WhatsApp">
                                <i class="fab fa-whatsapp"></i>
                            </a>
                            <button class="btn btn-sm btn-primary btn-edit" data-id="${row.id}" data-phone="${row.phone_number}" data-name="${row.name || ''}" title="Edit">
                                <i class="fe fe-edit"></i>
                            </button>
                            <button class="btn btn-sm btn-danger btn-delete" data-id="${row.id}" title="Delete">
                                <i class="fe fe-trash"></i>
                            </button>
                        </div>
                    `;
                }
            }
        ],
        "order": [[0, "desc"]] // Sort by newest (pseudo - relying on ID usually or just no sort)
    });

    // Open Modal for New Contact
    $("#btnAddContact").click(function () {
        $("#modalTitle").text("New Contact");
        $("#action").val("add_contact");
        $("#contactId").val("");
        $("#contactForm")[0].reset();
        $("#contactModal").modal("show");
    });

    // Save Contact
    $("#btnSaveContact").click(function () {
        let formData = $("#contactForm").serialize();

        $.post("../api/contacts.php", formData, function (res) {
            if (res.status === 'success') {
                $("#contactModal").modal("hide");
                table.ajax.reload();
                // Optional: Toast or Alert
            } else {
                alert(res.message);
            }
        }, 'json');
    });

    // Open Modal for Edit
    $('#contactsTable tbody').on('click', '.btn-edit', function () {
        let id = $(this).data("id");
        let phone = $(this).data("phone");
        let name = $(this).data("name");

        $("#modalTitle").text("Edit Contact");
        $("#action").val("update_contact");
        $("#contactId").val(id);
        $("#phone").val(phone);
        $("#name").val(name);

        $("#contactModal").modal("show");
    });

    // Delete Contact
    $('#contactsTable tbody').on('click', '.btn-delete', function () {
        if (!confirm("Are you sure?")) return;

        let id = $(this).data("id");
        $.post("../api/contacts.php", { action: "delete_contact", id: id }, function (res) {
            if (res.status === 'success') {
                table.ajax.reload();
            } else {
                alert(res.message);
            }
        }, 'json');
    });

});
