{% extends "base_config.html" %}
{% block content %}

<div class="page">
    <div id="content" class="section">
        <h2 class="section-title">Profile</h2>
        <div class="section-cards">
            <div class="card">
                <div class="card-title-row">
                    <img class="card-icon" src="/static/assets/icons/user-silhouette.svg" alt="Profile Name">
                    <h3 class="card-title">
                        Name
                    </h3>
                </div>
                <div class="card-description-row">
                    <input type="text" id="profile_given_name" class="form-control" placeholder="Enter your name here" value="{% if given_name %}{{given_name}}{% endif %}">
                </div>
                <div class="card-action-row">
                    <button id="save-model" class="card-button happy" onclick="saveProfileGivenName()">
                        Save
                    </button>
                </div>
            </div>
        </div>
        <h2 class="section-title" style="margin-top: 48px; padding-bottom: 8px;">Content</h2>
        <button id="compute-index-size" class="card-button" onclick="getIndexedDataSize()">
            Data Usage
        </button>
        <p id="indexed-data-size" class="card-description"></p>
        <div class="section-cards">
            <div class="card">
                <div class="card-title-row">
                    <img class="card-icon" src="/static/assets/icons/computer.png" alt="Computer">
                    <h3 id="card-title-computer" class="card-title">
                        <span>Files</span>
                        <img id="configured-icon-computer"
                            style="display: {% if not current_model_state.computer %}none{% endif %}"
                            class="configured-icon"
                            src="/static/assets/icons/confirm-icon.svg"
                            alt="Configured">
                    </h3>
                </div>
                <div class="card-description-row">
                <p class="card-description">Manage files from your computer</p>
                </div>
                <div class="card-action-row">
                    <a class="card-button" href="/config/content-source/computer">
                        {% if current_model_state.computer %}
                            Update
                        {% else %}
                            Setup
                        {% endif %}
                        <svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14M12 5l7 7-7 7"></path></svg>
                    </a>
                    <div id="clear-computer" class="card-action-row"
                        style="display: {% if not current_model_state.computer %}none{% endif %}">
                        <button class="card-button" onclick="clearContentType('computer')">
                            Disable
                        </button>
                    </div>
                </div>
            </div>
             <div class="card">
                <div class="card-title-row">
                    <img class="card-icon" src="/static/assets/icons/github.svg" alt="Github">
                    <h3 class="card-title">
                        <span>Github</span>
                        <img id="configured-icon-github"
                            class="configured-icon"
                            src="/static/assets/icons/confirm-icon.svg"
                            alt="Configured"
                            style="display: {% if not current_model_state.github %}none{% endif %}">
                    </h3>
                </div>
                <div class="card-description-row">
                <p class="card-description">Set repositories to index</p>
                </div>
                <div class="card-action-row">
                    <a class="card-button" href="/config/content-source/github">
                        {% if current_model_state.github %}
                            Update
                        {% else %}
                            Setup
                        {% endif %}
                        <svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14M12 5l7 7-7 7"></path></svg>
                    </a>
                    <div id="clear-github"
                        class="card-action-row"
                        style="display: {% if not current_model_state.github %}none{% endif %}">
                        <button class="card-button" onclick="clearContentType('github')">
                            Disable
                        </button>
                    </div>
                </div>
            </div>
            <div class="card">
                <div class="card-title-row">
                    <img class="card-icon" src="/static/assets/icons/notion.svg" alt="Notion">
                    <h3 class="card-title">
                        <span>Notion</span>
                        <img id="configured-icon-notion"
                            class="configured-icon"
                            src="/static/assets/icons/confirm-icon.svg"
                            alt="Configured"
                            style="display: {% if not current_model_state.notion %}none{% endif %}">
                    </h3>
                </div>
                <div class="card-description-row">
                    <p class="card-description">Sync your Notion pages</p>
                </div>
                <div class="card-action-row">
                    {% if current_model_state.notion %}
                    <a class="card-button" href="/config/content-source/notion">
                            Update
                        <svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14M12 5l7 7-7 7"></path></svg>
                    </a>
                    {% elif notion_oauth_url %}
                    <a class="card-button" href="{{ notion_oauth_url }}">
                            Connect
                        <svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14M12 5l7 7-7 7"></path></svg>
                    </a>
                    {% else %}
                    <a class="card-button" href="/config/content-source/notion">
                            Setup
                        <svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14M12 5l7 7-7 7"></path></svg>
                    </a>
                    {% endif %}

                    <div id="clear-notion"
                        class="card-action-row"
                        style="display: {% if not current_model_state.notion %}none{% endif %}">
                        <button class="card-button" onclick="clearContentType('notion')">
                            Disable
                        </button>
                    </div>
                </div>
            </div>
            <div class="card">
                <div class="card-title-row">
                    <img class="card-icon" src="/static/assets/icons/web.svg" alt="Language">
                    <h3 class="card-title">
                        <span>Language</span>
                    </h3>
                </div>
                <div class="card-description-row">
                    <select id="search-models">
                        {% for option in search_model_options %}
                            <option value="{{ option.id }}" {% if option.id == selected_search_model_config %}selected{% endif %}>{{ option.name }}</option>
                        {% endfor %}
                    </select>
                </div>
                <div class="card-action-row">
                    <button id="save-search-model" class="card-button happy" onclick="updateSearchModel()">
                        Save
                    </button>
                </div>
            </div>
        </div>
        <div class="general-settings section">
            <div id="status" style="display: none;"></div>
        </div>
        <div class="section finalize-actions general-settings">
            <div class="section-cards">
                <div class="finalize-buttons">
                    <button id="sync" type="submit" title="Regenerate index from scratch for Notion, GitHub configuration" style="display: flex; justify-content: center;">
                        <img class="card-icon" src="/static/assets/icons/sync.svg" alt="Sync">
                        <h3 class="card-title">
                            Sync
                        </h3>
                    </button>
                </div>
            </div>
        </div>
    </div>
    <div id ="features" class="section">
        <h2 class="section-title">Features</h2>
        <div id="features-hint-text"></div>
        <div class="section-cards">
            <div class="card">
                <div class="card-title-row">
                    <img class="card-icon" src="/static/assets/icons/chat.svg" alt="Chat">
                    <h3 class="card-title">
                        <span>Chat</span>
                    </h3>
                </div>
                <div class="card-description-row">
                    <select id="chat-models">
                        {% for option in conversation_options %}
                            <option value="{{ option.id }}" {% if option.id == selected_conversation_config %}selected{% endif %}>{{ option.chat_model }}</option>
                        {% endfor %}
                    </select>
                </div>
                <div class="card-action-row">
                    {% if (not billing_enabled) or (subscription_state != 'unsubscribed' and subscription_state != 'expired') %}
                    <button id="save-model" class="card-button happy" onclick="updateChatModel()">
                        Save
                    </button>
                    {% else %}
                    <button id="save-model" class="card-button" disabled>
                        Subscribe to use different models
                    </button>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>
    {% if not anonymous_mode or is_twilio_enabled %}
    <div id="clients" class="section">
        <h2 class="section-title">Clients</h2>
        {% if not anonymous_mode %}
        <div id="clients-api" class="api-settings">
            <div class="card-title-row">
                <img class="card-icon" src="/static/assets/icons/key.svg" alt="API Key">
                <h3 class="card-title">
                    <span>API Keys</span>
                </h3>
            </div>
            <div class="card-description-row">
                <p id="api-settings-card-description" class="card-description">Manage access from your client apps to Khoj</p>
            </div>
            <table id="api-settings-keys-table">
                <thead>
                <tr>
                    <th scope="col">Name</th>
                    <th scope="col">Key</th>
                    <th scope="col">Actions</th>
                </tr>
                </thead>
                <tbody id="api-key-list"></tbody>
            </table>
            <div class="card-action-row">
                <button class="card-button happy" id="generate-api-key" onclick="generateAPIKey()">
                    Generate API Key
                </button>
            </div>
        </div>
        {% endif %}
        {% if is_twilio_enabled %}
        <div id="phone-number-input-card" class="api-settings">
            <div class="card-title-row">
                <img class="card-icon" src="/static/assets/icons/whatsapp.svg" alt="WhatsApp icon">
                <h3 class="card-title">
                    <span>WhatsApp</span>
                </h3>
            </div>
            <div class="card-description-row">
                <p id="api-settings-card-description-verified" class="card-description" style="{{ 'display: none;' if not phone_number else '' }}">Your number is connected. You can now chat with Khoj on WhatsApp at <a href="https://wa.me/18488004242">+1-848-800-4242</a>. Learn more about the integration <a href="https://docs.khoj.dev/clients/whatsapp">here</a>.</p>
                <p id="api-settings-card-description-unverified" class="card-description" style="{{ 'display: none;' if phone_number else '' }}">Connect your number to chat with Khoj on WhatsApp. Learn more about the integration <a href="https://docs.khoj.dev/clients/whatsapp">here</a>.</p>
            </div>
            <div id="phone-number-input-element" class="card-action-row">
                {% if phone_number %}
                    <input type="text" id="mobile_code" class="form-control" placeholder="Phone Number" name="name" value="{{ phone_number }}">
                {% else %}
                    <input type="text" id="mobile_code" class="form-control" placeholder="Phone Number" name="name">
                {% endif %}
            </div>
            <div id="phone-number-update-callback" class="card-action-row" style="display: none;">
            </div>
            <div class="card-action-row">
                <button id="whatsapp-verify" class="card-button happy" style="display: none;">
                    Get OTP on WhatsApp and Verify
                </button>
                <button id="whatsapp-remove" class="card-button" style="display: none;">
                    Remove
                </button>
                <input type="number" maxlength="6" id="whatsapp_otp" class="whatsapp_otp" placeholder="OTP" name="otp_code" style="display: none;">
                <button id="whatsapp-verify-otp" class="card-button happy" style="display: none;">
                    Verify OTP
                </button>
            </div>
        </div>
        {% endif %}
    </div>
    {% endif %}
    {% if billing_enabled %}
    <div id="billing" class="section">
        <h2 class="section-title">Billing</h2>
        <div class="section-cards">
            <div class="card">
                <div class="card-title-row">
                    <img class="card-icon" src="/static/assets/icons/credit-card.png" alt="Credit Card">
                    <h3 class="card-title">
                        <span>Subscription</span>
                        <img id="configured-icon-subscription"
                            style="display: {% if subscription_state == 'trial' or subscription_state == 'expired' %}none{% endif %}"
                            class="configured-icon"
                            src="/static/assets/icons/confirm-icon.svg"
                            alt="Configured">
                    </h3>
                </div>
                <div class="card-description-row">
                    <p id="trial-description"
                       class="card-description"
                       style="display: {% if subscription_state != 'trial' %}none{% endif %}">
                        Subscribe to Khoj Cloud. See <a href="https://khoj.dev/pricing">pricing</a> for details.
                    </p>
                    <p id="unsubscribe-description"
                       class="card-description"
                       style="display: {% if subscription_state != 'subscribed' %}none{% endif %}">
                       You are <b>subscribed</b> to Khoj Cloud. Subscription will <b>renew</b> on <b>{{ subscription_renewal_date }}</b>
                    </p>
                    <p id="resubscribe-description"
                       class="card-description"
                       style="display: {% if subscription_state != 'unsubscribed' %}none{% endif %}">
                       You are <b>subscribed</b> to Khoj Cloud. Subscription will <b>expire</b> on <b>{{ subscription_renewal_date }}</b>
                    </p>
                    <p id="expire-description"
                       class="card-description"
                       style="display: {% if subscription_state != 'expired' %}none{% endif %}">
                       Subscribe to Khoj Cloud. Subscription <b>expired</b> on <b>{{ subscription_renewal_date }}</b>
                    </p>
                </div>
                <div class="card-action-row">
                    <button id="unsubscribe-button"
                            class="card-button"
                            onclick="unsubscribe()"
                            style="display: {% if subscription_state != 'subscribed' %}none{% endif %};">
                        Unsubscribe
                    </button>
                    <button id="resubscribe-button"
                            class="card-button happy"
                            onclick="resubscribe()"
                            style="display: {% if subscription_state != 'unsubscribed' %}none{% endif %};">
                        Resubscribe
                    </button>
                    <a id="subscribe-button"
                       class="card-button happy"
                       href="{{ khoj_cloud_subscription_url }}?prefilled_email={{ username }}"
                       style="display: {% if subscription_state == 'subscribed' or subscription_state == 'unsubscribed' %}none{% endif %};">
                        Subscribe
                        <svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14M12 5l7 7-7 7"></path></svg>
                    </a>
                </div>
            </div>
        </div>
    </div>
    {% endif %}
    <div class="section"></div>
    <div class="section" id="notification-banner-parent">
        <div id="notification-banner" style="display: none;"></div>
    </div>
</div>
<script>

    function saveProfileGivenName() {
        const givenName = document.getElementById("profile_given_name").value;
        fetch('/api/config/user/name?name=' + givenName, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.status == "ok") {
                let notificationBanner = document.getElementById("notification-banner");
                notificationBanner.innerHTML = "Profile name has been updated!";
                notificationBanner.style.display = "block";
                setTimeout(function() {
                    notificationBanner.style.display = "none";
                }, 5000);
            }
        })
    }

    function updateChatModel() {
        const chatModel = document.getElementById("chat-models").value;
        const saveModelButton = document.getElementById("save-model");
        saveModelButton.disabled = true;
        saveModelButton.innerHTML = "Saving...";

        fetch('/api/config/data/conversation/model?id=' + chatModel, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.status == "ok") {
                saveModelButton.innerHTML = "Save";
                saveModelButton.disabled = false;

                let notificationBanner = document.getElementById("notification-banner");
                notificationBanner.innerHTML = "Conversation model has been updated!";
                notificationBanner.style.display = "block";
                setTimeout(function() {
                    notificationBanner.style.display = "none";
                }, 5000);

            } else {
                saveModelButton.innerHTML = "Error";
                saveModelButton.disabled = false;
            }
        })
    };

    function updateSearchModel() {
        let confirmation = window.confirm("All your existing data will be deleted, and you will have to regenerate it. Are you sure you want to continue?");
        if (!confirmation) {
            return;
        }

        const searchModel = document.getElementById("search-models").value;
        const saveSearchModelButton = document.getElementById("save-search-model");
        saveSearchModelButton.disabled = true;
        saveSearchModelButton.innerHTML = "Saving...";

        fetch('/api/config/data/search/model?id=' + searchModel, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.status == "ok") {
                saveSearchModelButton.innerHTML = "Save";
                saveSearchModelButton.disabled = false;
            } else {
                saveSearchModelButton.innerHTML = "Error";
                saveSearchModelButton.disabled = false;
            }

            let notificationBanner = document.getElementById("notification-banner");
            notificationBanner.innerHTML = "Khoj can now better understand the language of your content! Manually sync your data from one of the Khoj clients to update your knowledge base.";
            notificationBanner.style.display = "block";
            setTimeout(function() {
                notificationBanner.style.display = "none";
            }, 5000);
        })
    };

    function clearContentType(content_source) {
        fetch('/api/config/data/content-source/' + content_source, {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json',
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.status == "ok") {
                document.getElementById("configured-icon-" + content_source).style.display = "none";
                document.getElementById("clear-" + content_source).style.display = "none";
            } else {
                document.getElementById("configured-icon-" + content_source).style.display = "";
                document.getElementById("clear-" + content_source).style.display = "";
            }
        })
    };

    function unsubscribe() {
        fetch('/api/subscription?operation=cancel&email={{username}}', {
            method: 'PATCH',
            headers: {
                'Content-Type': 'application/json',
            },
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
               document.getElementById("unsubscribe-description").style.display = "none";
               document.getElementById("unsubscribe-button").style.display = "none";

               document.getElementById("resubscribe-description").style.display = "";
               document.getElementById("resubscribe-button").style.display = "";

             }
        })
    }

    function resubscribe() {
        fetch('/api/subscription?operation=resubscribe&email={{username}}', {
            method: 'PATCH',
            headers: {
                'Content-Type': 'application/json',
            },
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
               document.getElementById("resubscribe-description").style.display = "none";
               document.getElementById("resubscribe-button").style.display = "none";

               document.getElementById("unsubscribe-description").style.display = "";
               document.getElementById("unsubscribe-button").style.display = "";
            }
        })
    }

    var sync = document.getElementById("sync");
    sync.addEventListener("click", function(event) {
        event.preventDefault();
        updateIndex(
            force=true,
            successText="Synced!",
            errorText="Unable to sync. Raise issue on Khoj <a href='https://github.com/khoj-ai/khoj/issues'>Github</a> or <a href='https://discord.gg/BDgyabRM6e'>Discord</a>.",
            button=sync,
            loadingText="Syncing...",
            emoji="");
    });

    function updateIndex(force, successText, errorText, button, loadingText, emoji) {
        const csrfToken = document.cookie.split('; ').find(row => row.startsWith('csrftoken'))?.split('=')[1];
        const original_html = button.innerHTML;
        button.disabled = true;
        button.innerHTML = emoji + " " + loadingText;
        fetch('/api/update?&client=web&force=' + force, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': csrfToken
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.detail != null) {
                throw new Error(data.detail);
            }

            document.getElementById("status").style.display = "none";

            button.disabled = false;
            button.innerHTML = `✅ ${successText}`;
            setTimeout(function() {
                button.innerHTML = original_html;
            }, 2000);
        })
        .catch((error) => {
            console.error('Error:', error);
            document.getElementById("status").innerHTML = emoji + " " + errorText
            document.getElementById("status").style.display = "block";
            button.disabled = false;
            button.innerHTML = '⚠️ Unsuccessful';
            setTimeout(function() {
                button.innerHTML = original_html;
            }, 2000);
        });

        content_sources = ["computer", "github", "notion"];
        content_sources.forEach(content_source => {
            fetch(`/api/config/data/${content_source}`, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.length > 0) {
                    document.getElementById("configured-icon-" + content_source).style.display = "";
                    document.getElementById("clear-" + content_source).style.display = "";
                } else {
                    document.getElementById("configured-icon-" + content_source).style.display = "none";
                    document.getElementById("clear-" + content_source).style.display = "none";
                }
            });
        });
    }

    function generateAPIKey() {
        const apiKeyList = document.getElementById("api-key-list");
        fetch('/auth/token', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
        })
        .then(response => response.json())
        .then(tokenObj => {
            apiKeyList.innerHTML += generateTokenRow(tokenObj);
        });
    }

    function copyAPIKey(token) {
        // Copy API key to clipboard
        navigator.clipboard.writeText(token);
        // Flash the API key copied icon
        const apiKeyColumn = document.getElementById(`api-key-${token}`);
        const original_html = apiKeyColumn.innerHTML;
        const copyApiKeyButton = document.getElementById(`api-key-copy-${token}`);
        setTimeout(function() {
            copyApiKeyButton.src = "/static/assets/icons/copy-button-success.svg";
            setTimeout(() => {
                copyApiKeyButton.src = "/static/assets/icons/copy-button.svg";
            }, 1000);
            apiKeyColumn.innerHTML = "✅ Copied!";
            setTimeout(function() {
                apiKeyColumn.innerHTML = original_html;
            }, 1000);
        }, 100);
    }

    function deleteAPIKey(token) {
        const apiKeyList = document.getElementById("api-key-list");
        fetch(`/auth/token?token=${token}`, {
            method: 'DELETE',
        })
        .then(response => {
            if (response.ok) {
                const apiKeyItem = document.getElementById(`api-key-item-${token}`);
                apiKeyList.removeChild(apiKeyItem);
            }
        });
    }

    function generateTokenRow(tokenObj) {
        let token = tokenObj.token;
        let tokenName = tokenObj.name;
        let truncatedToken = token.slice(0, 4) + "..." + token.slice(-4);
        let tokenId = `${tokenName}-${truncatedToken}`;
        return `
            <tr id="api-key-item-${token}">
                <td><b>${tokenName}</b></td>
                <td id="api-key-${token}">${truncatedToken}</td>
                <td>
                    <img id="api-key-copy-${token}" onclick="copyAPIKey('${token}')" class="configured-icon api-key-action enabled" src="/static/assets/icons/copy-button.svg" alt="Copy API Key" title="Copy API Key">
                    <img id="api-key-delete-${token}" onclick="deleteAPIKey('${token}')" class="configured-icon api-key-action enabled" src="/static/assets/icons/delete.svg" alt="Delete API Key" title="Delete API Key">
                </td>
            </tr>
        `;
    }

    function listApiKeys() {
        const apiKeyList = document.getElementById("api-key-list");
        fetch('/auth/token')
            .then(response => response.json())
            .then(tokens => {
                if (!tokens?.length > 0) return;
                apiKeyList.innerHTML = tokens?.map(generateTokenRow).join("");
            });
    }

    // List user's API keys on page load
    listApiKeys();

    function getIndexedDataSize() {
        document.getElementById("indexed-data-size").innerHTML = "Calculating...";
        fetch('/api/config/index/size')
            .then(response => response.json())
            .then(data => {
                document.getElementById("indexed-data-size").innerHTML = data.indexed_data_size_in_mb + " MB used";
            });
    }

    function removeFile(path) {
        fetch('/api/config/data/file?filename=' + path, {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json',
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.status == "ok") {
                getAllFilenames();
            }
        })
    }

    var phoneInputField = document.querySelector("#mobile_code");
    const iti = window.intlTelInput(phoneInputField, {
        initialCountry: "auto",
        geoIpLookup: callback => {
            fetch("https://ipapi.co/json")
            .then(res => res.json())
            .then(data => callback(data.country_code))
            .catch(() => callback("us"))
        },
        separateDialCode: true,
        utilsScript: "https://cdn.jsdelivr.net/npm/intl-tel-input@18.2.1/build/js/utils.js",
    });

    const errorMap = ["Invalid number", "Invalid country code", "Too short", "Too long", "Invalid number"];
    const phoneNumberUpdateCallback = document.getElementById("phone-number-update-callback");

    const phonenumberVerifyButton = document.getElementById("whatsapp-verify");
    const phonenumberRemoveButton = document.getElementById("whatsapp-remove");
    const phonenumberVerifyOTPButton = document.getElementById("whatsapp-verify-otp");
    const phonenumberOTPInput = document.getElementById("whatsapp_otp");
    const phonenumberVerifiedText = document.getElementById("api-settings-card-description-verified");
    const phonenumberUnverifiedText = document.getElementById("api-settings-card-description-unverified");

    const preExistingPhoneNumber = "{{ phone_number }}";
    let isPhoneNumberVerified = "{{ is_phone_number_verified }}";
    let isTwilioEnabled = "{{ is_twilio_enabled }}";
    isPhoneNumberVerified = isPhoneNumberVerified.toLowerCase();
    isTwilioEnabled = isTwilioEnabled.toLowerCase();

    if (isTwilioEnabled !== "true" ) {
        const phoneNumberVerificationCard = document.getElementById("phone-number-input-card");
        phoneNumberVerificationCard.style.display = "none";
    }
    if (preExistingPhoneNumber != "None" && isPhoneNumberVerified === "true") {
        phonenumberVerifyButton.style.display = "none";
        phonenumberRemoveButton.style.display = "";
    } else if (preExistingPhoneNumber != "None" && isPhoneNumberVerified === "false") {
        if (isTwilioEnabled == "true") {
            phonenumberVerifyButton.style.display = "";
            phonenumberRemoveButton.style.display = "none";
        } else {
            phonenumberVerifyButton.style.display = "none";
            phonenumberRemoveButton.style.display = "none";
        }
    }
    else {
        phonenumberVerifyButton.style.display = "";
        phonenumberRemoveButton.style.display = "none";
    }

    phoneInputField.addEventListener("keyup", () => {
        if (iti.isValidNumber() == false) {
            phonenumberVerifyButton.style.display = "none";
            phonenumberRemoveButton.style.display = "none";
        } else {
            phonenumberVerifyButton.style.display = "";
            phonenumberRemoveButton.style.display = "none";
        }
    })

    phonenumberRemoveButton.addEventListener("click", () => {
        fetch('/api/config/phone', {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json',
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.status == "ok") {
                phonenumberVerifyButton.style.display = "";
                phonenumberRemoveButton.style.display = "none";
                phonenumberVerifiedText.style.display = "none";
                phonenumberUnverifiedText.style.display = "block";
            }
        })
    })

    phonenumberVerifyButton.addEventListener("click", () => {
        console.log(iti.getValidationError());
        if (iti.isValidNumber() == false) {
            phoneNumberUpdateCallback.innerHTML = "Invalid phone number: " + errorMap[iti.getValidationError()];
            phoneNumberUpdateCallback.style.display = "block";
            setTimeout(function() {
                phoneNumberUpdateCallback.style.display = "none";
            }, 5000);
        } else {
            const mobileNumber = iti.getNumber();
            fetch('/api/config/phone?phone_number=' + mobileNumber, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.status == "ok") {
                    if (isTwilioEnabled == "True" || isTwilioEnabled == "true") {
                        phoneNumberUpdateCallback.innerHTML = "OTP sent to your phone number";
                        phonenumberVerifyOTPButton.style.display = "block";
                        phonenumberOTPInput.style.display = "block";
                    } else {
                        phonenumberVerifiedText.style.display = "block";
                        phoneNumberUpdateCallback.innerHTML = "Phone number updated";
                        phonenumberUnverifiedText.style.display = "none";
                    }
                    phonenumberVerifyButton.style.display = "none";
                    phoneNumberUpdateCallback.style.display = "block";
                    setTimeout(function() {
                        phoneNumberUpdateCallback.style.display = "none";
                    }, 5000);
                } else {
                    phoneNumberUpdateCallback.innerHTML = "Error updating phone number";
                    phoneNumberUpdateCallback.style.display = "block";
                    setTimeout(function() {
                        phoneNumberUpdateCallback.style.display = "none";
                    }, 5000);
                }
            })
            .catch((error) => {
                console.error('Error:', error);
                phoneNumberUpdateCallback.innerHTML = "Error updating phone number";
                phoneNumberUpdateCallback.style.display = "block";
                setTimeout(function() {
                    phoneNumberUpdateCallback.style.display = "none";
                }, 5000);
            });
        }
    })

    phonenumberVerifyOTPButton.addEventListener("click", () => {
        const otp = phonenumberOTPInput.value;
        if (otp.length != 6) {
            phoneNumberUpdateCallback.innerHTML = "Your OTP should be exactly 6 digits";
            phoneNumberUpdateCallback.style.display = "block";
            setTimeout(function() {
                phoneNumberUpdateCallback.style.display = "none";
            }, 5000);
            return;
        }

        fetch('/api/config/phone/verify?code=' + otp, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.status == "ok") {
                phoneNumberUpdateCallback.innerHTML = "Phone number updated";
                phonenumberVerifiedText.style.display = "block";
                phonenumberUnverifiedText.style.display = "none";
                phoneNumberUpdateCallback.style.display = "block";
                phonenumberRemoveButton.style.display = "";
                phonenumberVerifyButton.style.display = "none";
                phonenumberVerifyOTPButton.style.display = "none";
                phonenumberOTPInput.style.display = "none";
                setTimeout(function() {
                    phoneNumberUpdateCallback.style.display = "none";
                }, 5000);
            } else {
                phoneNumberUpdateCallback.innerHTML = "Error updating phone number";
                phoneNumberUpdateCallback.style.display = "block";
                setTimeout(function() {
                    phoneNumberUpdateCallback.style.display = "none";
                }, 5000);
            }
        })
        .catch((error) => {
            console.error('Error:', error);
            phoneNumberUpdateCallback.innerHTML = "Error updating phone number";
            phoneNumberUpdateCallback.style.display = "block";
            setTimeout(function() {
                phoneNumberUpdateCallback.style.display = "none";
            }, 5000);
        });
    })
</script>
{% endblock %}
