{% extends 'layout.html' %}

{% block content %}
<nav class="glass-nav">
    <div class="nav-brand">
        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"></path><polyline points="3.27 6.96 12 12.01 20.73 6.96"></polyline><line x1="12" y1="22.08" x2="12" y2="12"></line></svg>
        Tada to Odoo Migration
    </div>
    <div class="nav-user">
        <span class="user-badge">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path><circle cx="12" cy="7" r="4"></circle></svg>
            {{ employee_name }}
        </span>
        <a href="{{ url_for('logout') }}" class="btn-logout">
            Log out
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"></path><polyline points="16 17 21 12 16 7"></polyline><line x1="21" y1="12" x2="9" y2="12"></line></svg>
        </a>
    </div>
</nav>

<div class="content-wrapper">
    <div class="glass-panel table-panel">
        <div class="panel-header">
            <h2 class="panel-title">Customer Database</h2>
            <p class="panel-subtitle">Review and migrate customer profiles to Odoo 19.</p>
        </div>
        <div class="table-responsive">
            <table id="customersTable" class="display" style="width:100%">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Name</th>
                        <th>Phone</th>
                        <th>Email</th>
                        <th>Level</th>
                        <th>Points</th>
                        <th>Migrated By</th>
                        <th class="action-col">Action</th>
                    </tr>
                </thead>
                <tbody>
                    <!-- Populated by DataTables via AJAX -->
                </tbody>
            </table>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_scripts %}
<script>
$(document).ready(function() {
    var table = $('#customersTable').DataTable({
        "processing": true,
        "serverSide": true,
        "ajax": {
            "url": "{{ url_for('get_customers') }}",
            "type": "GET"
        },
        "columns": [
            { "data": "id" },
            { "data": "name" },
            { "data": "phone_number", "defaultContent": "-" },
            { "data": "email", "defaultContent": "-" },
            { "data": "level", "defaultContent": "-" },
            { "data": "point_amount", "defaultContent": "0" },
            { 
                "data": "responsible", 
                "render": function(data, type, row) {
                    if(data) {
                        return `<span class="badge badge-success">Done by ${data}</span>`;
                    }
                    return `<span class="badge badge-warning">Pending</span>`;
                }
            },
            {
                "data": null,
                "orderable": false,
                "render": function(data, type, row) {
                    if(row.responsible) {
                        return `<button class="btn-migrasi disabled" disabled>Migrated</button>`;
                    }
                    let safeName = row.name ? row.name.replace(/'/g, "\\'") : 'Unknown Customer';
                    return `<button class="btn-migrasi" onclick="migrateCustomer(${row.id}, '${safeName}')">Migrasi Data</button>`;
                }
            }
        ],
        "pageLength": 10,
        "language": {
            "search": "Search records:",
            "searchPlaceholder": "Name, Email, Phone (min 3 chars)"
        }
    });

    // Custom search logic: debounce 400ms and min 3 characters
    var searchTimeout = null;
    $('.dataTables_filter input').unbind().bind('input', function() {
        var searchTerm = this.value;
        clearTimeout(searchTimeout);
        searchTimeout = setTimeout(function() {
            if (searchTerm.length >= 3 || searchTerm.length === 0) {
                table.search(searchTerm).draw();
            }
        }, 400);
    });

    window.migrateCustomer = function(id, name) {
        Swal.fire({
            title: 'Confirm Migration',
            text: `Are you sure you want to migrate "${name}" to Odoo 19?`,
            icon: 'question',
            showCancelButton: true,
            confirmButtonColor: '#6366f1',
            cancelButtonColor: '#334155',
            confirmButtonText: 'Yes, migrate now!',
            background: '#1e293b',
            color: '#f8fafc',
            customClass: {
                popup: 'glass-popup'
            }
        }).then((result) => {
            if (result.isConfirmed) {
                // Show loading
                Swal.fire({
                    title: 'Migrating...',
                    text: 'Please wait while data is being transferred.',
                    allowOutsideClick: false,
                    background: '#1e293b',
                    color: '#f8fafc',
                    didOpen: () => {
                        Swal.showLoading();
                    }
                });

                // AJAX Request
                $.ajax({
                    url: `/api/migrate/${id}`,
                    type: 'POST',
                    success: function(response) {
                        if(response.success) {
                            Swal.fire({
                                title: 'Success!',
                                text: response.message,
                                icon: 'success',
                                background: '#1e293b',
                                color: '#f8fafc',
                                confirmButtonColor: '#10b981'
                            });
                            table.draw(false); // Reload table data without resetting pagination
                        } else {
                            Swal.fire({
                                title: 'Failed!',
                                text: response.message,
                                icon: 'error',
                                background: '#1e293b',
                                color: '#f8fafc',
                                confirmButtonColor: '#ef4444'
                            });
                        }
                    },
                    error: function(xhr) {
                        let msg = "An unexpected error occurred.";
                        if(xhr.responseJSON && xhr.responseJSON.message) {
                            msg = xhr.responseJSON.message;
                        }
                        Swal.fire({
                            title: 'Error!',
                            text: msg,
                            icon: 'error',
                            background: '#1e293b',
                            color: '#f8fafc',
                            confirmButtonColor: '#ef4444'
                        });
                    }
                });
            }
        });
    }
});
</script>
{% endblock %}
