{% if session.get('company_id') %}
    {% extends 'layouts/base.html' %}
{% else %}
    {% extends 'admin/base.html' %}
{% endif %}

{% block title %}Packages{% endblock %}

{% block content %}
<div class="page-header">
    <div>
        <h1 class="page-title">Packages</h1>
        <p class="page-subtitle">
            Review available plans and make quick adjustments without touching the underlying dataset.
        </p>
    </div>
</div>

{% if error %}
    <div class="alert alert-danger" role="alert">
        {{ error }}
    </div>
{% endif %}

<div id="packagesFeedback" class="toast hidden"></div>

<div class="packages-grid">
    {% for package in packages %}
        <article class="package-card" data-package-id="{{ package.id }}">
            <div class="package-card-header">
                <h3 class="package-title">{{ package.title }}</h3>
                <button
                    class="btn btn-ghost edit-package"
                    data-id="{{ package.id }}"
                    data-title="{{ package.title }}"
                    data-description="{{ package.description or '' }}"
                    data-contacts="{{ package.no_of_contacts }}"
                    data-mins="{{ package.no_of_mins }}"
                    data-price="{{ package.price }}"
                    data-files="{{ package.no_of_files }}"
                    title="Edit package"
                >
                    <i class="fa-light fa-pen-to-square"></i>
                </button>
            </div>
            <p class="package-description">{{ package.description or 'No description provided.' }}</p>
            <div class="package-meta">
                <div class="meta-item">
                    <span class="meta-label">Contacts</span>
                    <span class="meta-value" data-field="no_of_contacts">{{ package.no_of_contacts }}</span>
                </div>
                <div class="meta-item">
                    <span class="meta-label">Call Minutes</span>
                    <span class="meta-value" data-field="no_of_mins">{{ package.no_of_mins }}</span>
                </div>
                <div class="meta-item">
                    <span class="meta-label">Validity</span>
                    <span class="meta-value">30 days</span>
                </div>
                
                <div class="meta-item">
                    <span class="meta-label">Price</span>
                    <span class="meta-value" data-field="price">{{ currency }} {{ '%.2f' | format(package.price|float) }}</span>
                </div>
                <div class="meta-item">
                    <span class="meta-label">No. of Files</span>
                    <span class="meta-value" data-field="no_of_files">
                        {% if package.no_of_files %}
                            {{ package.no_of_files }} files
                        {% else %}
                            Unlimited
                        {% endif %}
                    </span>
                </div>
            </div>
        </article>
    {% else %}
        <div class="empty-state">
            <i class="fa-light fa-box-open"></i>
            <p>No packages found.</p>
        </div>
    {% endfor %}
</div>


    <div id="packageModal" class="modal hidden">
        <div class="modal-backdrop">
    
            <div class="modal-dialog">
                <div class="modal-header">
                    <h2 class="modal-title">Update Package</h2>
                    <button class="modal-close" type="button" title="Close">
                        <i class="fa-light fa-xmark"></i>
                    </button>
                </div>
                <form id="packageForm">
                    <input type="hidden" name="package_id" id="packageIdField">
                    <div class="modal-body">
                        <div class="form-group">
                            <label for="packageTitle">Title</label>
                            <input type="text" id="packageTitle" name="title" required>
                        </div>
                        <div class="form-group">
                            <label for="packageDescription">Description</label>
                            <textarea id="packageDescription" name="description" rows="3"></textarea>
                        </div>
                        <div class="form-group inline">
                            <div>
                                <label for="packageContacts">No. of Contacts</label>
                                <input type="number" id="packageContacts" name="no_of_contacts" min="0" step="1">
                            </div>
                            <div>
                                <label for="packageMinutes">No. of Minutes</label>
                                <input type="number" id="packageMinutes" name="no_of_mins" min="0" step="1">
                            </div>
                        </div>
                        <div class="form-group">
                        <label for="packageFiles">No. of Files can be uploaded</label>
                            <input type="number" id="packageFiles" name="no_of_files" min="0" step="1">
                        </div>
                        <div class="form-group">
                            <label for="packagePrice">Price</label>
                            <input type="number" id="packagePrice" name="price" min="0" step="0.01">
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-ghost" id="packageCancel">Cancel</button>
                        <button type="submit" class="btn btn-primary">
                            <i class="fa-light fa-floppy-disk"></i>
                            <span>Save changes</span>
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

{% endblock %}

{% block extra_js %}
<script>
    (function () {
        const currencyLabel = "{{ currency }}";
        const modal = document.getElementById('packageModal');
        const modalBackdrop = modal.querySelector('.modal-backdrop');
        const closeButton = modal.querySelector('.modal-close');
        const cancelButton = document.getElementById('packageCancel');
        const form = document.getElementById('packageForm');
        const feedback = document.getElementById('packagesFeedback');
        let activeCard = null;

        function showModal() {
            modal.classList.remove('hidden');
            document.body.classList.add('modal-open');
        }

        function hideModal() {
            modal.classList.add('hidden');
            document.body.classList.remove('modal-open');
            form.reset();
            activeCard = null;
        }

        function showFeedback(message, tone = 'success') {
            if (!feedback) return;
            feedback.textContent = message;
            feedback.classList.remove('hidden', 'error');
            if (tone === 'error') {
                feedback.classList.add('error');
            } else {
                feedback.classList.remove('error');
            }
            clearTimeout(feedback._timeout);
            feedback._timeout = setTimeout(() => feedback.classList.add('hidden'), 3500);
        }

        document.querySelectorAll('.edit-package').forEach(button => {
            button.addEventListener('click', () => {
                activeCard = button.closest('.package-card');
                document.getElementById('packageIdField').value = button.dataset.id;
                document.getElementById('packageTitle').value = button.dataset.title || '';
                document.getElementById('packageDescription').value = button.dataset.description || '';
                document.getElementById('packageContacts').value = button.dataset.contacts || 0;
                document.getElementById('packageMinutes').value = button.dataset.mins || 0;
                document.getElementById('packagePrice').value = button.dataset.price || 0;
                document.getElementById('packageFiles').value = button.dataset.files || 0;
                showModal();
            });
        });

        [cancelButton, closeButton].forEach(el => {
            el.addEventListener('click', hideModal);
        });

        form.addEventListener('submit', async (event) => {
            event.preventDefault();
            const packageId = document.getElementById('packageIdField').value;
            const formData = {
                title: document.getElementById('packageTitle').value,
                description: document.getElementById('packageDescription').value,
                no_of_contacts: document.getElementById('packageContacts').value,
                no_of_mins: document.getElementById('packageMinutes').value,
                price: document.getElementById('packagePrice').value,
                no_of_files: document.getElementById('packageFiles').value,
            };

            const submitBtn = form.querySelector('button[type="submit"]');
            submitBtn.disabled = true;
            submitBtn.classList.add('loading');

            try {
                const response = await fetch(`{{ url_for('admin.update_package', package_id=0) }}`.replace('0', packageId), {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(formData),
                });
                const result = await response.json();
                if (!response.ok || !result.success) {
                    throw new Error(result.error || 'Failed to update package.');
                }

                if (activeCard) {
                    activeCard.querySelector('.package-title').textContent = result.package.title;
                    activeCard.querySelector('.package-description').textContent = result.package.description || 'No description provided.';
                    activeCard.querySelector('[data-field="no_of_contacts"]').textContent = result.package.no_of_contacts;
                    activeCard.querySelector('[data-field="no_of_mins"]').textContent = result.package.no_of_mins;
                    activeCard.querySelector('[data-field="price"]').textContent = `${currencyLabel} ${Number(result.package.price).toFixed(2)}`;
                    activeCard.querySelector('[data-field="no_of_files"]').textContent =
                        result.package.no_of_files ? `${result.package.no_of_files} files` : 'Unlimited';
                    const editBtn = activeCard.querySelector('.edit-package');
                    editBtn.dataset.title = result.package.title;
                    editBtn.dataset.description = result.package.description || '';
                    editBtn.dataset.contacts = result.package.no_of_contacts;
                    editBtn.dataset.mins = result.package.no_of_mins;
                    editBtn.dataset.price = result.package.price;
                    editBtn.dataset.files = result.package.no_of_files;
                }

                showFeedback('Package updated successfully.');
                hideModal();
            } catch (error) {
                console.error(error);
                showFeedback(error.message || 'Unable to update package.', 'error');
            } finally {
                submitBtn.disabled = false;
                submitBtn.classList.remove('loading');
            }
        });
    })();
</script>
{% endblock %}

