<!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;
        }

        @media (max-width: 600px) {
            .form-row {
                flex-direction: column;
            }
        }
    </style>
</head>
<body>

    <!-- Left Panel (Navigation) -->
    <div class="left-panel left-panel-show" id="left-panel"></div>

    <!-- Main Content Area -->
    <div class="main-content main-content-normal" id="main-content">

        <!-- Content Area -->
        <div id="content">
            <form id="generalSettingsForm">
                <h2>General Settings</h2>

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

                <h3>Mail Settings</h3>

                <div class="form-row">
                    <div>
                        <label for="smtpServer">SMTP Server</label>
                        <input type="text" id="smtpServer" name="smtpServer" placeholder="mail.squizee.in"/>
                    </div>
                    <div>
                        <label for="smtpPort">SMTP Port</label>
                        <input type="number" id="smtpPort" name="smtpPort" placeholder="587"/>
                    </div>
                </div>

                <label for="smtpFromEmail">SMTP From Email</label>
                <input type="email" id="smtpFromEmail" name="smtpFromEmail" placeholder="info@squizee.in"/>

                <h3>WhatsApp Settings</h3>
                <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">API Endpoint</label>
                <input type="text" id="whatsappApiEndpoint" name="whatsappApiEndpoint" placeholder="https://api.provider.com"/>

                <label for="whatsappFooterText">Default Footer Text</label>
                <textarea id="whatsappFooterText" name="whatsappFooterText" rows="2" placeholder="This is an automated message."></textarea>

                <label for="useAiModel">Use AI Model</label>
                <select id="useAiModel" name="useAiModel">
                    <option value="gemini" selected>Gemini</option>
                </select>

                <h3>Gemini Settings</h3>
                <label for="geminiApiKey">API Key</label>
                <input type="text" id="geminiApiKey" name="geminiApiKey" placeholder="Your Gemini API Key"/>

                <label for="geminiModel">Model</label>
                <select id="geminiModel" name="geminiModel">
                    <option value="gemini-2.5-flash" selected>gemini-2.5-flash (Recommended)</option>
                    <option value="gemini-2.5-pro">gemini-2.5-pro</option>
                    <option value="gemini-1.5-flash">gemini-1.5-flash (Legacy)</option>
                    <option value="gemini-1.0-pro">gemini-1.0-pro (Legacy)</option>
                </select>
                
                <label for="geminiApiEndpoint">API Endpoint</label>
                <input type="text" id="geminiApiEndpoint" name="geminiApiEndpoint" placeholder="https://generativelanguage.googleapis.com/..."/>

                <button type="button" id="save-button">Save Settings</button>
            </form>
        </div>

    </div>

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

    <script>

        document.addEventListener("DOMContentLoaded", function () {
        
            // Function to fetch settings and populate form fields
            function fetchAndPopulateSettings() {
                fetch('php/settings/fetch_settings.php')
                    .then(response => 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;
                                }
                            }
                        };
        
                        // General Settings
                        setField("timezone", "timezone");
        
                        // Mail Settings
                        setField("smtpServer", "mail_settings", "smtpServer");
                        setField("smtpPort", "mail_settings", "smtpPort");
                        setField("smtpFromEmail", "mail_settings", "smtpFromEmail");
        
                        // WhatsApp Settings
                        setField("whatsappApiProvider", "whatsapp_settings", "api_provider_name");  // you might need to handle 'api_provider_name' separately
                        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");
        
                        // Gemini Settings
                        setField("geminiApiKey", "gemini_settings", "api_key");
                        setField("geminiModel", "gemini_settings", "model");
                        setField("geminiApiEndpoint", "gemini_settings", "api_endpoint");
                    })
                    .catch(error => {
                        console.error("Error fetching settings:", error);
                        Swal.fire('Error', 'Failed to fetch settings.', 'error');
                    });
            }
        
            // Call the function to fetch and populate settings
            fetchAndPopulateSettings();
        
            // Handle manual save via button
            document.getElementById("save-button").addEventListener("click", function () {
                const form = document.getElementById("generalSettingsForm");
                const formData = new FormData(form);
        
                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
                })
                .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 and update form after saving
                            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');
                });
            });
        
        });


        // Expanded list of timezones
        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>
