
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>General Settings</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(); ?>" />
    <script src="js/main/main.js?ver=<?php echo time(); ?>" defer></script>
    <style>
        #content {
            margin: 20px auto;
            font-family: Arial, sans-serif;
            background: #fff;
            padding: 25px 30px;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }

        form#generalSettingsForm h2,
        form#generalSettingsForm h3 {
            margin-bottom: 20px;
            color: #333;
            font-weight: 600;
            border-bottom: 2px solid #ddd;
            padding-bottom: 5px;
        }

        form#generalSettingsForm h3 {
            margin-top: 30px;
        }

        form#generalSettingsForm label {
            display: block;
            margin-bottom: 6px;
            font-weight: 600;
            color: #555;
        }

        form#generalSettingsForm input[type="text"],
        form#generalSettingsForm input[type="email"],
        form#generalSettingsForm input[type="number"],
        form#generalSettingsForm input[type="tel"],
        form#generalSettingsForm textarea,
        form#generalSettingsForm select {
            width: 100%;
            padding: 10px 12px;
            margin-bottom: 18px;
            border: 1px solid #ccc;
            border-radius: 5px;
            font-size: 15px;
            transition: border-color 0.3s ease;
            box-sizing: border-box;
        }

        form#generalSettingsForm input:focus,
        form#generalSettingsForm select:focus,
        form#generalSettingsForm textarea:focus {
            border-color: #007BFF;
            outline: none;
        }

        form#generalSettingsForm textarea {
            resize: vertical;
        }

        form#generalSettingsForm button[type="button"] {
            background-color: #4CAF50; /* Green */
            color: white;
            padding: 12px 20px;
            font-size: 16px;
            font-weight: 600;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            transition: background-color 0.3s ease;
            width: 100%; /* Full width */
        }

        form#generalSettingsForm button[type="button"]:hover {
            background-color: #388E3C; /* Darker green on hover */
        }

        .form-row {
            display: flex;
            gap: 20px;
            margin-bottom: 18px;
            flex-wrap: wrap;
        }

        .form-row > div {
            flex: 1;
        }

        /* WhatsApp Status Styles */
        #whatsappStatusContainer {
            margin-bottom: 15px;
            padding: 10px 0;
            display: flex;
            align-items: center;
            gap: 10px;
            font-weight: bold;
        }
        #whatsappStatus {
            cursor: pointer; /* Indicate it's clickable for manual check */
            text-decoration: underline dotted;
        }
        .status-indicator {
            display: inline-block;
            width: 12px;
            height: 12px;
            border-radius: 50%;
            margin-right: 5px;
        }
        .status-indicator.connected {
            background-color: #4CAF50; /* Green */
        }
        .status-indicator.disconnected {
            background-color: #F44336; /* Red */
        }
        .status-indicator.needs-scan {
            background-color: #FF9800; /* Orange - QR available */
        }
        .status-indicator.checking {
            background-color: #2196F3; /* Blue - Checking */
        }


        @media (max-width: 600px) {
            .form-row {
                flex-direction: column;
            }
        }
    </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">
            <form id="generalSettingsForm">
                <h2>General Settings</h2>

                <label for="timezone">Timezone</label>
                <select id="timezone" name="timezone">
                    <option value="">Select a timezone</option> 
                </select>

                <h3>WhatsApp Settings</h3>
                
                <div id="whatsappStatusContainer">
                    <span>Connection Status: </span>
                    <span id="whatsappStatus" title="Click to manually re-check status">
                        <span class="status-indicator checking"></span> Checking...
                    </span>
                </div>
                <div class="form-row">
                    <div>
                        <label for="whatsappEnabled">Enable WhatsApp</label>
                        <select id="whatsappEnabled" name="whatsappEnabled">
                            <option value="yes">Yes</option>
                            <option value="no">No</option>
                        </select>
                    </div>
                    <div>
                        <label for="enableDefaultFooter">Enable Default Footer</label>
                        <select id="enableDefaultFooter" name="enableDefaultFooter">
                            <option value="yes">Yes</option>
                            <option value="no">No</option>
                        </select>
                    </div>
                </div>

                <div class="form-row">
                    <div>
                        <label for="whatsappApiKey">API Key</label>
                        <input type="text" id="whatsappApiKey" name="whatsappApiKey" placeholder="Your WhatsApp API Key"/>
                    </div>
                    <div>
                        <label for="whatsappSenderNumber">Sender Phone Number</label>
                        <input type="tel" id="whatsappSenderNumber" name="whatsappSenderNumber" placeholder="+1234567890"/>
                    </div>
                </div>

                <label for="whatsappApiEndpoint">QR/Status API Endpoint **(Must end with `generate-qr`)**</label>
                <input type="text" id="whatsappApiEndpoint" name="whatsappApiEndpoint" placeholder="https://wa.squizee.in/generate-qr"/>

                <label for="whatsappFooterText">Default Footer Text</label>
                <textarea id="whatsappFooterText" name="whatsappFooterText" rows="2" placeholder="This is an automated message."></textarea>
                
                                <button type="button" id="save-button">Save Settings</button>
            </form>
        </div>

    </div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
// Global variable for polling interval ID
let statusPollingInterval = null;
// Variables to store WhatsApp API settings globally or pass them (optional, relies on input values primarily)
let globalWhatsappSettings = {
    apiKey: '',
    sender: '',
    apiEndpoint: 'https://wa.squizee.in/'
};

document.addEventListener("DOMContentLoaded", function () {

    // Utility to set the status indicator appearance
    function updateStatusIndicator(status, message = '', qrcodeData = null) {
        const statusElement = document.getElementById('whatsappStatus');
        let indicatorClass = '';
        let text = '';
        let title = 'Click to manually re-check status';

        if (status === 'connected') {
            indicatorClass = 'connected';
            text = 'Connected';
        } else if (status === 'needs-scan') {
            indicatorClass = 'needs-scan';
            text = 'Needs Scan (QR Ready)';
            if (message) title = `QR code available: ${message}`;
        } else { // 'disconnected' or 'checking'
            indicatorClass = (status === 'checking') ? 'checking' : 'disconnected';
            text = (status === 'checking') ? 'Checking...' : 'Disconnected';
            if (message) text += `: ${message}`;
        }

        statusElement.innerHTML = `<span class="status-indicator ${indicatorClass}"></span> ${text}`;
        statusElement.setAttribute('title', title);
    }

    // Function to check the WhatsApp connection status via XHR GET API
    function checkWhatsappStatus() {
        // Use the values from the input fields
        const apiKey = document.getElementById('whatsappApiKey').value;
        const senderNumber = document.getElementById('whatsappSenderNumber').value;
        let apiEndpoint = document.getElementById('whatsappApiEndpoint').value;
    
        // Clean the sender number for the 'device' parameter
        const device = senderNumber.replace(/[^0-9]/g, '');
    
        if (!apiKey || !device || !apiEndpoint) {
            updateStatusIndicator('disconnected', 'Missing API Key, Sender, or Endpoint.');
            return;
        }
    
        updateStatusIndicator('checking');
    
        // --- XHR GET Implementation ---
    
        const xhr = new XMLHttpRequest();
    
        // Prepare data as URL-encoded query string
        const postData = `api_key=${encodeURIComponent(apiKey)}&device=${encodeURIComponent(device)}`;
    
        // Safely construct the base endpoint (ensuring 'generate-qr' is at the end)
        let full_endpoint = apiEndpoint;
        if (!full_endpoint.endsWith('generate-qr') && !full_endpoint.endsWith('generate-qr/')) {
            full_endpoint = apiEndpoint.endsWith('/') ? apiEndpoint + 'generate-qr' : apiEndpoint + '/generate-qr';
        }
    
        // Append all data to the URL for the GET request
        const final_url = full_endpoint + '?' + postData;
    
        // Use GET method
        xhr.open('GET', final_url, true);
    
        // Explicitly set Accept header to ensure server sends JSON
        xhr.setRequestHeader('Accept', 'application/json');
    
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
    
                // CRITICAL FIX: Allow 2xx status codes (standard success) OR 400 (this API's specific quirk)
                if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 400) {
                    let data;
                    try {
                        data = JSON.parse(xhr.responseText);
                    } catch (e) {
                        updateStatusIndicator('disconnected', 'API returned non-JSON data. Check Console.');
                        console.error("Non-JSON response received:", xhr.responseText);
                        return;
                    }
    
                    // Process the API response
                    if (data.msg && data.msg.includes("Device already connected!")) {
                        updateStatusIndicator('connected');
                    } else if (data.qrcode) {
                        updateStatusIndicator('needs-scan', data.message || 'Scan the QR code to connect.', data.qrcode);
                    } else if (data.msg) {
                        updateStatusIndicator('disconnected', data.msg);
                    } else {
                        updateStatusIndicator('disconnected', `Unknown API status. Response status: ${data.status}`);
                    }
    
                } else {
                    // Handle actual HTTP errors
                    updateStatusIndicator('disconnected', `HTTP Error ${xhr.status}. API is unreachable or invalid.`);
                    console.error(`Unexpected HTTP Error ${xhr.status}. API response: ${xhr.responseText}`);
                }
            }
        };
    
        xhr.onerror = function () {
            // Handle network errors
            updateStatusIndicator('disconnected', 'Network error during API check. Check Console.');
            console.error("WhatsApp status check XHR failed (Network Error).");
        };
    
        xhr.send(null);
    }
    
    
    // Function to start the periodic check
    function startStatusPolling() {
        // Clear any existing interval before starting a new one
        if (statusPollingInterval) {
            clearInterval(statusPollingInterval);
        }
        // Check immediately and then every 10 seconds
        checkWhatsappStatus();
        statusPollingInterval = setInterval(checkWhatsappStatus, 10000); // 10 seconds
    }

    // Function to fetch settings and populate form fields
    function fetchAndPopulateSettings() {
        fetch('php/settings/fetch_settings.php')
            .then(response => {
                if (!response.ok) {
                    throw new Error('Failed to fetch settings from server.');
                }
                return response.json();
            })
            .then(data => {
                if (!data || typeof data !== 'object') return;

                // Helper function to set a field's value
                const setField = (id, key, nestedKey = null) => {
                    const el = document.getElementById(id);
                    if (el) {
                        let value = nestedKey ? (data[key] && data[key][nestedKey]) : data[key];
                        if (value !== undefined) {
                            el.value = value;
                            // Update global settings for use in checkWhatsappStatus if input fields are empty
                            if (key === 'whatsapp_settings' && nestedKey === 'api_key') globalWhatsappSettings.apiKey = value;
                            if (key === 'whatsapp_settings' && nestedKey === 'sender') globalWhatsappSettings.sender = value;
                            if (key === 'whatsapp_settings' && nestedKey === 'api_endpoint') globalWhatsappSettings.apiEndpoint = value;
                        }
                    }
                };

                // General Settings
                setField("timezone", "timezone");

                // WhatsApp Settings
                setField("whatsappApiKey", "whatsapp_settings", "api_key");
                setField("whatsappSenderNumber", "whatsapp_settings", "sender");
                setField("whatsappApiEndpoint", "whatsapp_settings", "api_endpoint");
                setField("whatsappFooterText", "whatsapp_settings", "default_footer_text");
                setField("whatsappEnabled", "whatsapp_settings", "enable_autoreply");
                // *** This line correctly fetches and sets the 'Enable Default Footer' field value. ***
                setField("enableDefaultFooter", "whatsapp_settings", "enable_default_footer"); 
                // NOTE: Removed setField for 'whatsappSendCodeArea' here as well.

                // Start polling after settings are loaded and fields are populated
                startStatusPolling();
            })
            .catch(error => {
                console.error("Error fetching settings:", error);
                Swal.fire('Error', 'Failed to fetch settings. Polling started with current form values.', 'error');
                // Start polling even if fetch fails, using current (possibly empty) form values
                startStatusPolling();
            });
    }

    // Call the function to fetch and populate settings
    fetchAndPopulateSettings();

    // Set up manual recheck listener
    document.getElementById("whatsappStatus").addEventListener("click", checkWhatsappStatus);

    // Handle manual save via button
    document.getElementById("save-button").addEventListener("click", function () {
        const form = document.getElementById("generalSettingsForm");
        const formData = new FormData(form);
        
        // formData will automatically include all fields with a 'name' attribute:
        // 'timezone', 'whatsappEnabled', 'enableDefaultFooter', 'whatsappApiKey', 
        // 'whatsappSenderNumber', 'whatsappApiEndpoint', 'whatsappFooterText'

        Swal.fire({
            title: 'Saving Settings...',
            didOpen: () => {
                Swal.showLoading();
            },
            allowOutsideClick: false,
            allowEscapeKey: false,
            allowEnterKey: false,
            showConfirmButton: false
        });

        fetch('php/settings/save_settings.php', {
            method: 'POST',
            body: formData // *** The 'enableDefaultFooter' is included here via FormData. ***
        })
        .then(response => response.json())
        .then(result => {
            Swal.close();

            if (result.status === 'success' || result.success === true) {
                Swal.fire('Success', 'Settings saved successfully.', 'success').then(() => {
                    // Re-fetch to update global settings and restart polling after a successful save
                    fetchAndPopulateSettings();
                });
            } else {
                Swal.fire('Error', result.message || 'Failed to save settings.', 'error');
            }
        })
        .catch(error => {
            console.error("Error saving settings:", error);
            Swal.close();
            Swal.fire('Error', 'An error occurred while saving settings.', 'error');
        });
    });

    // Re-start polling when API/Sender fields change
    document.getElementById('whatsappApiKey').addEventListener('input', startStatusPolling);
    document.getElementById('whatsappSenderNumber').addEventListener('input', startStatusPolling);
    document.getElementById('whatsappApiEndpoint').addEventListener('input', startStatusPolling);
});


// Expanded list of timezones (kept the original list)
const timezones = [
    "Africa/Abidjan", "Africa/Accra", "Africa/Addis_Ababa", "Africa/Algiers",
    "Africa/Cairo", "Africa/Casablanca", "Africa/Harare", "Africa/Johannesburg",
    "Africa/Lagos", "Africa/Nairobi", "Africa/Tunis", "America/Anchorage",
    "America/Argentina/Buenos_Aires", "America/Chicago", "America/Denver", "America/Edmonton",
    "America/Los_Angeles", "America/New_York", "America/Chicago", "America/Denver",
    "America/Los_Angeles", "America/Mexico_City", "America/Montevideo", "America/New_York",
    "America/Toronto", "Asia/Almaty", "Asia/Amman", "Asia/Baghdad", "Asia/Baku",
    "Asia/Bangkok", "Asia/Chennai", "Asia/Dhaka", "Asia/Ho_Chi_Minh", "Asia/Hong_Kong",
    "Asia/Kolkata", "Asia/Kuala_Lumpur", "Asia/Macau", "Asia/Muscat", "Asia/Novosibirsk",
    "Asia/Seoul", "Asia/Singapore", "Asia/Tokyo", "Asia/Ulaanbaatar", "Australia/Adelaide",
    "Australia/Brisbane", "Australia/Darwin", "Australia/Hobart", "Australia/Melbourne",
    "Australia/Sydney", "Europe/Amsterdam", "Europe/Athens", "Europe/Belgrade", "Europe/Berlin",
    "Europe/Brussels", "Europe/Bucharest", "Europe/Budapest", "Europe/Copenhagen", "Europe/Dublin",
    "Europe/Helsinki", "Europe/Lisbon", "Europe/London", "Europe/Madrid", "Europe/Paris",
    "Europe/Prague", "Europe/Rome", "Europe/Sofia", "Europe/Stockholm", "Europe/Vienna",
    "Europe/Zurich", "Indian/Antananarivo", "Indian/Chagos", "Indian/Maldives", "Indian/Reunion",
    "Pacific/Apia", "Pacific/Auckland", "Pacific/Chatham", "Pacific/Fiji", "Pacific/Guadalcanal",
    "Pacific/Honolulu", "Pacific/Kwajalein", "Pacific/Majuro", "Pacific/Nauru", "Pacific/Pago_Pago",
    "Pacific/Port_Moresby", "Pacific/Samoa", "Pacific/Tarawa", "Pacific/Tongatapu", "Pacific/Wake",
    "UTC", "Asia/Jerusalem", "Europe/Minsk", "Europe/Kiev", "Africa/Khartoum", "America/Lima"
];

// Function to populate the dropdown with the timezone options
function updateTimezoneOptions() {
    const timezoneSelect = document.getElementById('timezone');

    // Clear existing options except the first (default option)
    timezoneSelect.innerHTML = '<option value="">Select a timezone</option>';

    // Loop through the array of timezones and create an option element for each
    timezones.forEach(function(timezone) {
        const option = document.createElement('option');
        option.value = timezone;
        option.textContent = timezone;

        // Append the option to the select element
        timezoneSelect.appendChild(option);
    });
}

// Call the function to populate the dropdown
updateTimezoneOptions();
</script>
</body>
</html>


