{% extends "layouts/base.html" %}

{% block title %}WhatsApp Settings{% endblock %}

{% block extra_css %}
<style>
    .settings-container {
        /* max-width: 600px; */
        margin: 0 auto;
        background-color: #ffffff;
        padding: 20px;
        border-radius: 8px;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    }

    .settings-container h2 {
        text-align: center;
        margin-bottom: 20px;
        color: #042954;
    }

    .form-group {
        margin-bottom: 20px;
    }

    .form-group label {
        font-weight: bold;
        color: #333;
        margin-bottom: 8px;
        display: block;
    }

    .form-control {
        width: 100%;
        padding: 10px;
        border: 1px solid #ddd;
        border-radius: 4px;
        font-size: 16px;
    }

    .form-control:focus {
        border-color: #042954;
        box-shadow: 0 0 0 2px rgba(4, 41, 84, 0.1);
        outline: none;
    }

    .btn-primary {
        width: 100%;
        margin-top: 20px;
        background: #042954;
        color: white;
        font-size: 16px;
        border-radius: 4px;
        padding: 12px 0;
        border: none;
        cursor: pointer;
        transition: background-color 0.3s ease;
    }

    .btn-primary:hover {
        background: #031f42;
    }

    .help-text {
        font-size: 14px;
        color: #666;
        margin-top: 5px;
    }

    .input-group {
        position: relative;
        display: flex;
        align-items: center;
    }

    .input-group .prefix {
        position: absolute;
        left: 10px;
        color: #666;
    }

    .input-group input {
        padding-left: 30px;
    }

    .card {
        background: #f8f9fa;
        border-radius: 8px;
        padding: 15px;
        margin-bottom: 20px;
    }

    .card-title {
        color: #042954;
        font-size: 18px;
        margin-bottom: 10px;
    }

    .card-text {
        color: #666;
        font-size: 14px;
        line-height: 1.5;
    }


    .webhook-info button {
        background-color: #042954;
        color: white;
        border: none;
        padding: 5px 10px;
        border-radius: 4px;
    }

    .webhook-info button:hover {
        background: #031f42;
    }

    .webhook-info {
        display: flex;
        flex-direction: column;
        gap: 10px;
    }

    .webhook-info code {
        font-size: 15px;
    }

    .webhook-info strong {
        font-size: 15px;
    }

    .form-row {
        width: 100%;
        display: flex;
        align-items: center;
        gap: 20px;
    }

    .form-col {
        width: 50%;
    }
</style>
{% endblock %}

{% block content %}
<div class="settings-container mt-5">
    <h2>WhatsApp Settings</h2>

    <!-- API Credentials Card -->
    <div class="card mb-4" style="padding: 35px;">
        <div class="card-title">WhatsApp API Credentials Setup</div>
        <div class="card-text">
            <ol>
                <li>Go to <a href="https://developers.facebook.com/" target="_blank">Meta Developers</a></li>
                <li>Click "My Apps" and create a new app or select existing</li>
                <li>Select "Business" as the app type</li>
                <li>In App Dashboard:
                    <ul>
                        <li>Go to "Settings" > "Basic"</li>
                        <li>Copy the "App ID" and "App Secret"</li>
                        <li>Add "WhatsApp" product to your app</li>
                        <li>Go to "WhatsApp" > "API Setup"</li>
                        <li>Copy the "Phone Number ID" for your registered number</li>
                        <li>Generate "Permanent Access Token" (System User Access Token recommended)</li>
                    </ul>
                </li>
            </ol>
        </div>
    </div>

    <form method="POST" action="{{ url_for('company.update_whatsapp_settings') }}" id="whatsapp-setting-form">
        <!-- API Credentials Section -->
        <div class="form-row">
            <div class="form-col">
                <div class="form-group">
                    <label for="whatsapp_app_id">App ID</label>
                    <input type="text" id="whatsapp_app_id" name="whatsapp_app_id" class="form-control"
                        value="{{ company.app_id if company.app_id else '' }}" placeholder="Enter your App ID">
                    <div class="help-text">Found in Meta Developers Console > Settings > Basic</div>
                </div>
            </div>
            <div class="form-col">
                <div class="form-group">
                    <label for="whatsapp_app_secret">App Secret</label>
                    <input type="password" id="whatsapp_app_secret" name="whatsapp_app_secret" class="form-control"
                        value="{{ company.app_secret if company.app_secret else '' }}"
                        placeholder="Enter your App Secret">
                    <div class="help-text">Found in Meta Developers Console > Settings > Basic</div>
                </div>
            </div>

        </div>

        <!-- Existing WhatsApp Fields -->

        <div class="form-row">
            <div class="form-col">
                <div class="form-group">
                    <label for="whatsapp_phone_number">WhatsApp Phone Number</label>
                    <div class="input-group">
                        <span class="prefix">+</span>
                        <input type="text" id="whatsapp_phone_number" name="whatsapp_phone_number" class="form-control"
                            value="{{ company.whatsapp_phone_number if company.whatsapp_phone_number else '' }}"
                            placeholder="1234567890">
                    </div>
                    <div class="help-text">Your registered WhatsApp Business number without the '+' sign</div>
                </div>
            </div>
            <div class="form-col">

                <div class="form-group">
                    <label for="whatsapp_phone_number_id">Phone Number ID</label>
                    <input type="text" id="whatsapp_phone_number_id" name="whatsapp_phone_number_id"
                        class="form-control"
                        value="{{ company.whatsapp_phone_number_id if company.whatsapp_phone_number_id else '' }}"
                        placeholder="123456789012345">
                    <div class="help-text">Found in WhatsApp > API Setup > Phone Number ID</div>
                </div>
            </div>
        </div>

        <div class="form-group">
            <label for="whatsapp_access_token">Permanent Access Token</label>
            <input type="password" id="whatsapp_access_token" name="whatsapp_access_token" class="form-control"
                value="{{ company.whatsapp_access_token if company.whatsapp_access_token else '' }}"
                placeholder="Enter your permanent access token">
            <div class="help-text">Use a System User Access Token for permanent access</div>
        </div>

        <!-- Webhook Section -->
        <div class="card mb-4" style="display: flex; flex-direction: column; gap: 10px;">
            <div class="card-title">Webhook Configuration</div>
            <div class="webhook-info mt-2 p-3 bg-light">
                <div class="mb-2">
                    <strong>Callback URL:</strong>
                    <code>{{ base_url }}/webhook</code>
                    <button class="btn btn-sm btn-secondary" onclick="copyToClipboard('callback-url')">Copy</button>
                </div>
                <div>
                    <strong>Verify Token:</strong>
                    <code>{{ company.whatsapp_verify_token }}</code>
                    <button class="btn btn-sm btn-secondary" onclick="copyToClipboard('verify-token')">Copy</button>
                </div>
            </div>
            <div class="help-text mt-2">Configure these in WhatsApp > Webhook settings</div>
        </div>

        <button type="submit" class="btn btn-primary">Save WhatsApp Settings</button>
    </form>

    <!-- Token Status Card -->
    {% if company.whatsapp_token_updated_at %}
    <div class="card mt-4">
        <div class="card-title">Token Status</div>
        <div class="card-text">
            Last Updated: {{ company.whatsapp_token_updated_at.strftime('%Y-%m-%d %H:%M:%S') }}
        </div>
    </div>
    {% endif %}
</div>
{% endblock %}

{% block extra_js %}
<script>
    function copyToClipboard(type) {
        let text;
        if (type === 'callback-url') {
            text = '{{ base_url }}/webhook';
        } else if (type === 'verify-token') {
            text = '{{ company.whatsapp_verify_token }}';
        }

        navigator.clipboard.writeText(text).then(() => {
            showNotification('Copied to clipboard!', 'success');
        }).catch(() => {
            showNotification('Failed to copy to clipboard', 'error');
        });
    }

    document.addEventListener('DOMContentLoaded', function () {
        const settingsForm = document.querySelector('#whatsapp-setting-form');

        settingsForm.addEventListener('submit', async function (e) {
            e.preventDefault();
            const formData = new FormData(this);

            try {
                const response = await fetch(this.action, {
                    method: 'POST',
                    body: formData
                });

                if (response.ok) {
                    showNotification('WhatsApp settings updated successfully!', 'success');
                    setTimeout(() => {
                        window.location.reload();
                    }, 1500);
                } else {
                    const data = await response.json();
                    showNotification('Error updating WhatsApp settings: ' + data.error, 'error');
                }
            } catch (error) {
                console.error('Error:', error);
                showNotification('Error updating WhatsApp settings. Please try again.', 'error');
            }
        });

        // Format phone number input
        const phoneInput = document.getElementById('whatsapp_phone_number');
        phoneInput.addEventListener('input', function (e) {
            let value = e.target.value.replace(/\D/g, '');
            e.target.value = value;
        });
    });
</script>
{% endblock %}