<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Admin Panel</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
<link rel="stylesheet" href="css/main/main.css?ver=<?php echo time(); ?>">

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.all.min.js"></script>

<script src="js/main/main.js?ver=<?php echo time(); ?>" defer></script>
<style>
/* Existing styles */
table {
    width: 100%;
    border-collapse: collapse;
    margin-top: 20px;
    background-color: #fff;
    box-shadow: 0 2px 6px rgba(0,0,0,0.1);
}
th, td {
    padding: 12px;
    border: 1px solid #ddd;
    text-align: left;
}
th {
    background-color: #34495e;
    color: white;
}
tr:nth-child(even) {
    background-color: #f9f9f9;
}
.switch {
    position: relative;
    display: inline-block;
    width: 40px;
    height: 22px;
}
.switch input {
    opacity: 0;
    width: 0;
    height: 0;
}
.slider {
    position: absolute;
    cursor: pointer;
    top: 0; left: 0; right: 0; bottom: 0;
    background-color: #ccc;
    transition: 0.4s;
    border-radius: 22px;
}
.slider:before {
    position: absolute;
    content: "";
    height: 16px;
    width: 16px;
    left: 3px;
    bottom: 3px;
    background-color: white;
    transition: 0.4s;
    border-radius: 50%;
}
input:checked + .slider {
    background-color: #2ecc71;
}
input:checked + .slider:before {
    transform: translateX(18px);
}
td .switch, th .switch {
    margin: 0 auto;
}
table textarea {
    width: 200px;
    max-height: 100px;
    resize: none;
}

/* NEW: Style for the Edit icon button */
.edit-btn {
    padding: 5px 10px;
    background-color: #3498db;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    transition: background-color 0.2s;
}
.edit-btn:hover {
    background-color: #2980b9;
}


/* NEW Modal Styles */
.modal {
    position: fixed;
    top: 0; left: 0;
    width: 100%; height: 100%;
    background: rgba(0,0,0,0.6);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 9999;
}
.modal-content {
    background: #fff;
    padding: 30px;
    border-radius: 10px;
    width: 600px;
    max-height: 90vh;
    box-shadow: 0 10px 25px rgba(0,0,0,0.2);
    display: flex;
    flex-direction: column;
}
.modal-header {
    border-bottom: 1px solid #eee;
    padding-bottom: 15px;
    margin-bottom: 20px;
}
.modal-header h3 {
    margin: 0;
    color: #34495e;
}
.modal-textarea {
    width: 100%;
    /* INCREASED HEIGHT */
    height: 450px; 
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 5px;
    resize: vertical;
    font-size: 14px;
    margin-bottom: 15px;
}
.modal-instructions {
    background-color: #f4f7f6;
    padding: 15px;
    border-radius: 5px;
    margin-bottom: 20px;
    max-height: 200px;
    overflow-y: auto;
}
.modal-instructions h4 {
    margin-top: 0;
    margin-bottom: 10px;
    color: #2c3e50;
    font-size: 0.8em;
}
.modal-instructions code {
    /* REDUCED FONT SIZE AND CHANGED COLOR */
    background-color: #e8e8e8;
    color: #0056b3; /* Darker blue for code */
    padding: 3px 6px;
    border-radius: 4px;
    font-family: monospace;
    font-size: 10px;
    border: 1px solid #dcdcdc;
}
.modal-actions {
    text-align: right;
    padding-top: 15px;
    border-top: 1px solid #eee;
}
.modal-actions button {
    padding: 8px 16px;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    font-weight: bold;
    transition: background-color 0.3s;
}
.modal-actions .save-btn {
    background-color: #2ecc71;
    color: white;
    margin-left: 10px;
}
.modal-actions .save-btn:hover {
    background-color: #27ae60;
}
.modal-actions .cancel-btn {
    background-color: #ecf0f1;
    color: #34495e;
}
.modal-actions .cancel-btn:hover {
    background-color: #bdc3c7;
}
</style>
</head>
<body>

<div class="left-panel left-panel-show" id="left-panel"></div>
<div class="main-content main-content-normal" id="main-content">
    <div id="content"></div>
</div>

<script>
document.addEventListener("DOMContentLoaded", function() {
    const content = document.getElementById("content");
    const statuses = ["Create", "Cancelled", "Failed", "Processing", "Pending", "Completed"];

    // ... (Existing table creation code remains the same) ...
    const table = document.createElement("table");
    const thead = document.createElement("thead");
    const headerRow = document.createElement("tr");

    const thEvent = document.createElement("th"); thEvent.textContent = "Event";
    const thToggle = document.createElement("th"); thToggle.style.textAlign = "center";
    const masterLabel = document.createElement("label"); masterLabel.classList.add("switch");
    const masterInput = document.createElement("input"); masterInput.type = "checkbox";
    const masterSlider = document.createElement("span"); masterSlider.classList.add("slider");
    masterLabel.appendChild(masterInput); masterLabel.appendChild(masterSlider); thToggle.appendChild(masterLabel);

    const thMessage = document.createElement("th"); thMessage.textContent = "Message Format";
    const thAction = document.createElement("th"); thAction.textContent = "Action"; thAction.style.textAlign = "center";

    headerRow.appendChild(thEvent);
    headerRow.appendChild(thToggle);
    headerRow.appendChild(thMessage);
    headerRow.appendChild(thAction);
    thead.appendChild(headerRow); table.appendChild(thead);

    const tbody = document.createElement("tbody");

    statuses.forEach(status => {
        const row = document.createElement("tr");

        const tdEvent = document.createElement("td"); tdEvent.textContent = status;

        const tdToggle = document.createElement("td"); tdToggle.style.textAlign = "center";
        const switchLabel = document.createElement("label"); switchLabel.classList.add("switch");
        const checkbox = document.createElement("input"); checkbox.type = "checkbox"; checkbox.classList.add("row-toggle");
        const slider = document.createElement("span"); slider.classList.add("slider");
        switchLabel.appendChild(checkbox); switchLabel.appendChild(slider); tdToggle.appendChild(switchLabel);

        const tdMessage = document.createElement("td");
        const textarea = document.createElement("textarea"); textarea.rows = 3; textarea.readOnly = true; textarea.dataset.event = status;
        tdMessage.appendChild(textarea);

        const tdAction = document.createElement("td"); tdAction.style.textAlign = "center";
        const editBtn = document.createElement("button");
        editBtn.classList.add("edit-btn"); 
        editBtn.innerHTML = '<i class="fas fa-pencil-alt"></i>'; // Font Awesome pencil icon
        editBtn.dataset.event = status;
        tdAction.appendChild(editBtn);

        row.appendChild(tdEvent); row.appendChild(tdToggle); row.appendChild(tdMessage); row.appendChild(tdAction);
        tbody.appendChild(row);
    });

    table.appendChild(tbody); content.appendChild(table);
    // ... (End of existing table creation code) ...

    const rowToggles = tbody.querySelectorAll(".row-toggle");

    // MODIFIED saveData function to return a Promise for SweetAlert
    function saveData() {
        const data = {};
        tbody.querySelectorAll("tr").forEach(row => {
            const eventName = row.querySelector("td:first-child").textContent;
            const checkbox = row.querySelector(".row-toggle");
            const textarea = row.querySelector("textarea");
            data[eventName] = { enabled: checkbox.checked, message: textarea.value };
        });
        return fetch("../php/save_whatsapp_toggles_settings.php", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify(data)
        });
    }

    // Function to show SweetAlert success message
    function showSuccessAlert() {
        Swal.fire({
            icon: 'success',
            title: 'Saved!',
            text: 'WhatsApp settings have been successfully updated.',
            toast: true,
            position: 'top-end',
            showConfirmButton: false,
            timer: 3000,
            timerProgressBar: true
        });
    }

    function loadData() {
        const initialData = {
            "Create": { "enabled": true, "message": "👋 Hello {{order.billing.first_name}},\n\nYour order **#{{order.id}}** has been successfully placed!\n\n**Total:** {{order.currency_symbol}}{{order.total}}\n\nWe'll notify you as soon as it moves to the next stage. Thank you for shopping with us!" },
            "Pending": { "enabled": true, "message": "⏳ Action Required for Order #{{order.id}}.\n\nYour order is currently **Pending Payment**.\n\n**Total:** {{order.currency_symbol}}{{order.total}}\n\nPlease complete your payment at the link below to continue:\n{{order.payment_url}}" },
            "Processing": { "enabled": true, "message": "🛠️ Great News, {{order.billing.first_name}}!\n\nYour order **#{{order.id}}** is now **Processing**.\n\nOur team is actively working on preparing your items:\n{{order.line_items_list}}\n\nWe appreciate your patience!" },
            "Completed": { "enabled": true, "message": "✅ Success! Your order **#{{order.id}}** has been **Completed**.\n\n**Items:** {{order.line_items_list}}\n\nThank you for your purchase. We hope to see you again soon!" },
            "Cancelled": { "enabled": true, "message": "❌ Update on Order #{{order.id}}.\n\nYour order, placed by {{order.billing.first_name}}, has been **Cancelled**.\n\nIf you believe this is an error, please contact us." },
            "Failed": { "enabled": true, "message": "🚨 Payment Failed for Order #{{order.id}}.\n\nWe were unable to process the payment for {{order.currency_symbol}}{{order.total}}.\n\nPlease try again here:\n{{order.payment_url}}\n\nIf the issue persists, contact our support team immediately." }
        };

        fetch("../php/fetch_whatsapp_settings.php")
            .then(res => res.json())
            .then(result => {
                let dataToUse = initialData;
                if (result.success && result.data) {
                    dataToUse = {...initialData, ...result.data};
                }
                
                tbody.querySelectorAll("tr").forEach(row => {
                    const eventName = row.querySelector("td:first-child").textContent;
                    const checkbox = row.querySelector(".row-toggle");
                    const textarea = row.querySelector("textarea");
                    
                    if(dataToUse[eventName]) {
                        checkbox.checked = dataToUse[eventName].enabled;
                        textarea.value = dataToUse[eventName].message;
                    }
                });
                masterInput.checked = Array.from(rowToggles).every(cb => cb.checked);

            })
            .catch(() => {
                tbody.querySelectorAll("tr").forEach(row => {
                    const eventName = row.querySelector("td:first-child").textContent;
                    const checkbox = row.querySelector(".row-toggle");
                    const textarea = row.querySelector("textarea");
                    if(initialData[eventName]) {
                        checkbox.checked = initialData[eventName].enabled;
                        textarea.value = initialData[eventName].message;
                    }
                });
                masterInput.checked = Array.from(rowToggles).every(cb => cb.checked);
            });
    }

    // UPDATED masterInput listener to show alert
    masterInput.addEventListener("change", function() {
        rowToggles.forEach(cb => cb.checked = masterInput.checked);
        saveData().then(showSuccessAlert).catch(() => {
             Swal.fire('Error', 'Failed to save changes.', 'error');
        });
    });

    // UPDATED rowToggles listener to show alert
    rowToggles.forEach(cb => {
        cb.addEventListener("change", function() {
            masterInput.checked = Array.from(rowToggles).every(chk => chk.checked);
            saveData().then(showSuccessAlert).catch(() => {
                 Swal.fire('Error', 'Failed to save changes.', 'error');
            });
        });
    });

    // --- MODIFIED MODAL CREATION LOGIC (Updated Variables) ---
    const availableVariables = [
        // Core Order Details
        "{{order.id}}",
        "{{order.status}}",
        "{{order.total}}",
        "{{order.currency}}",
        "{{order.currency_symbol}}",
        "{{order.order_key}}", // Unique key for payment links
        "{{order.date_created}}",
        
        // Billing Details
        "{{order.billing.first_name}}",
        "{{order.billing.last_name}}",
        "{{order.billing.company}}",
        "{{order.billing.address_1}}",
        "{{order.billing.city}}",
        "{{order.billing.state}}",
        "{{order.billing.postcode}}",
        "{{order.billing.country}}",
        "{{order.billing.email}}",
        "{{order.billing.phone}}",
        
        // Shipping Details
        "{{order.shipping.first_name}}",
        "{{order.shipping.last_name}}",
        "{{order.shipping.address_1}}",
        "{{order.shipping.city}}",
        "{{order.shipping.state}}",
        "{{order.shipping.postcode}}",
        "{{order.shipping.country}}",
    
        // Financial/Payment Details
        "{{order.payment_method_title}}",
        "{{order.discount_total}}",
        "{{order.shipping_total}}",
        "{{order.total_tax}}",
        "{{order.payment_url}}", // Direct payment link
        
        // Custom/Processed Variables
        "{{order.line_items_list}}" // Custom variable for a list of items (requires server-side processing)
    ];
    // --- END OF MODIFIED MODAL CREATION LOGIC ---

    tbody.querySelectorAll("button").forEach(btn => {
        btn.addEventListener("click", function() {
            const eventName = btn.dataset.event;
            const row = btn.closest("tr");
            const textarea = row.querySelector("textarea");

            // 1. Create Modal Container
            const modal = document.createElement("div");
            modal.classList.add("modal");

            // 2. Create Modal Content
            const modalContent = document.createElement("div");
            modalContent.classList.add("modal-content");

            // 3. Header
            const modalHeader = document.createElement("div");
            modalHeader.classList.add("modal-header");
            const modalTitle = document.createElement("h3");
            modalTitle.textContent = `Edit Message Format for '${eventName}'`;
            modalHeader.appendChild(modalTitle);

            // 4. Message Textarea
            const modalTextarea = document.createElement("textarea");
            modalTextarea.classList.add("modal-textarea");
            modalTextarea.value = textarea.value;

            // 5. Instructions Section
            const instructions = document.createElement("div");
            instructions.classList.add("modal-instructions");
            const instructionsTitle = document.createElement("h4");
            instructionsTitle.textContent = "Available Variables (Use **{{variable}}** in the message)";
            instructions.appendChild(instructionsTitle);

            const variablesList = document.createElement("div");
            variablesList.style.display = "flex";
            variablesList.style.flexWrap = "wrap";
            variablesList.style.gap = "8px";

            availableVariables.forEach(variable => {
                const codeElement = document.createElement("code");
                codeElement.textContent = variable;
                codeElement.title = `Click to copy ${variable}`;
                codeElement.style.cursor = "copy";
                codeElement.addEventListener('click', () => {
                    navigator.clipboard.writeText(variable).then(() => {
                        // Simple visual feedback
                        const originalText = codeElement.textContent;
                        codeElement.textContent = "Copied!";
                        setTimeout(() => { codeElement.textContent = originalText; }, 800);
                    });
                });
                variablesList.appendChild(codeElement);
            });
            instructions.appendChild(variablesList);


            // 6. Action Buttons
            const modalActions = document.createElement("div");
            modalActions.classList.add("modal-actions");

            const saveBtn = document.createElement("button");
            saveBtn.textContent = "Save Changes";
            saveBtn.classList.add("save-btn");

            const cancelBtn = document.createElement("button");
            cancelBtn.textContent = "Cancel";
            cancelBtn.classList.add("cancel-btn");

            modalActions.appendChild(cancelBtn);
            modalActions.appendChild(saveBtn);

            // 7. Assemble Modal
            modalContent.appendChild(modalHeader);
            modalContent.appendChild(instructions);
            modalContent.appendChild(modalTextarea);
            modalContent.appendChild(modalActions);
            modal.appendChild(modalContent);

            // Append to body and add event listeners
            document.body.appendChild(modal);
            modalTextarea.focus(); // Focus on the textarea

            // UPDATED saveBtn listener to show alert
            saveBtn.addEventListener("click", function() {
                textarea.value = modalTextarea.value;
                saveData().then(() => {
                    document.body.removeChild(modal);
                    showSuccessAlert();
                }).catch(() => {
                    document.body.removeChild(modal);
                    Swal.fire('Error', 'Failed to save message template.', 'error');
                });
            });

            cancelBtn.addEventListener("click", function() { document.body.removeChild(modal); });

            // Close on escape key
            modal.addEventListener('keydown', (e) => {
                if (e.key === 'Escape') {
                    document.body.removeChild(modal);
                }
            });
            // Close on outside click
            modal.addEventListener('click', (e) => {
                if (e.target === modal) {
                    document.body.removeChild(modal);
                }
            });
        });
    });
    // --- END OF MODIFIED MODAL CREATION LOGIC ---

    loadData();
});
</script>

</body>
</html>