jQuery(document).ready(function($) {

    /**
     * ============================
     *  FORMAT DATE FR (UTC+2)
     * ============================
     */
    function formatFR(dateString) {
        if (!dateString) return '';
        const date = new Date(dateString.replace(' ', 'T') + '+02:00');
        return date.toLocaleString('fr-FR', {
            day: '2-digit',
            month: '2-digit',
            year: 'numeric',
            hour: '2-digit',
            minute: '2-digit'
        }).replace(':', 'h');
    }

    /**
     * ============================
     *  VARIABLES GLOBALES
     * ============================
     */
    let currentSearch = '';
    let currentPageActive = 1;
    let currentPagePending = 1;
    let currentPageOff = 1;

    /**
     * ============================
     *  CHARGEMENT DES 3 SECTIONS
     * ============================
     */
    function loadAllSections() {
        loadSection('active', currentPageActive);
        loadSection('pending', currentPagePending);
        loadSection('off', currentPageOff);
    }

    /**
     * ============================
     *  CHARGER UNE SECTION
     * ============================
     */
    function loadSection(type, page) {

        $.post(WPVG_ADMIN.ajax_url, {
            action: 'wpvg_list_vcards',
            nonce: WPVG_ADMIN.nonce,
            search: currentSearch,
            page: page
        }, function(response) {

            if (!response.success) {
                console.error(response);
                return;
            }

            const data = response.data[type];
            const wrapper = $('#wpvg-' + type + '-wrapper');

            if (!data || data.length === 0) {
                wrapper.html('<p>Aucune vCard trouvée.</p>');
                return;
            }

            let html = '<table class="widefat striped"><thead><tr>';

            /**
             * TITRES DES COLONNES
             */
            if (type === 'active') {
                html += '<th>Nom</th><th>vcardId</th><th>Email</th><th>Mobile</th><th>Date de création</th><th>Dernière mise à jour</th><th>Actions</th>';
            }

            if (type === 'pending') {
                html += '<th>Token</th><th>Email</th><th>Date de création</th><th>Dernière mise à jour</th><th>Actions</th>';
            }

            if (type === 'off') {
                html += '<th>Nom</th><th>vcardId</th><th>Email</th><th>Mobile</th><th>Date de création</th><th>Dernière mise à jour</th><th>Date de désactivation</th><th>Actions</th>';
            }

            html += '</tr></thead><tbody>';

            /**
             * LIGNES DU TABLEAU
             */
            data.forEach(item => {

                /** ACTIVE **/
                if (type === 'active') {
                    html += `
                        <tr>
                            <td>${item.name}</td>
                            <td>${item.vcardId}</td>
                            <td>${item.email}</td>
                            <td>${item.mobile ?? item.phone}</td>
                            <td>${formatFR(item.created)}</td>
                            <td>${formatFR(item.updated)}</td>
							<td>
								<button class="button wpvg-open" data-url="${item.url}">Voir</button>
								<button class="button wpvg-copy" data-url="${item.url}">Copier URL</button>
								<a class="button"
								   href="${WPVG_ADMIN.download_url}?id=${item.vcardId}&file=zip&token=${item.token}">
								   Télécharger ZIP
								</a>
								<button class="button wpvg-show-qr" data-url="${item.url}">QR</button>
								<button class="button wpvg-disable" data-id="${item.vcardId}">Désactiver</button>
							</td>
                        </tr>
                    `;
                }

                /** PENDING **/
                if (type === 'pending') {
                    html += `
                        <tr>
                            <td>${item.token}</td>
                            <td>${item.email}</td>
                            <td>${formatFR(item.created)}</td>
                            <td>${formatFR(item.updated)}</td>
                            <td>
                                <button class="button wpvg-activate-pending" data-token="${item.token}">Activer manuellement</button>
                            </td>
                        </tr>
                    `;
                }

                /** OFF **/
                if (type === 'off') {
                    html += `
                        <tr>
                            <td>${item.name}</td>
                            <td>${item.vcardId}</td>
                            <td>${item.email}</td>
                            <td>${item.mobile ?? item.phone}</td>
                            <td>${formatFR(item.created)}</td>
                            <td>${formatFR(item.updated)}</td>
                            <td>${formatFR(item.deactivated)}</td>
                            <td>
                                <button class="button wpvg-enable" data-id="${item.vcardId}">Réactiver</button>
                                <button class="button wpvg-delete" data-id="${item.vcardId}">Supprimer</button>
                            </td>
                        </tr>
                    `;
                }

            });

            html += '</tbody></table>';

            wrapper.html(html);

        });
    }

    /**
     * ============================
     *  RECHERCHE GLOBALE
     * ============================
     */
    $('#wpvg-search').on('input', function() {
        currentSearch = $(this).val();
        loadAllSections();
    });

    /**
     * ============================
     *  MODALE DE CONFIRMATION
     * ============================
     */
    function openModal(title, message, onConfirm) {
        $('#wpvg-modal-title').text(title);
        $('#wpvg-modal-message').text(message);

        $('#wpvg-modal-overlay').fadeIn(150);

        $('#wpvg-modal-confirm').off('click').on('click', function() {
            $('#wpvg-modal-overlay').fadeOut(150);
            onConfirm();
        });

        $('#wpvg-modal-cancel').off('click').on('click', function() {
            $('#wpvg-modal-overlay').fadeOut(150);
        });
    }

    /**
     * ============================
     *  ACTION : Désactiver
     * ============================
     */
    $(document).on('click', '.wpvg-disable', function() {
        const vcardId = $(this).data('id');

        openModal(
            'Désactiver la vCard',
            'Voulez-vous vraiment désactiver cette vCard ?',
            function() {

                $.post(WPVG_ADMIN.ajax_url, {
                    action: 'wpvg_action_disable',
                    nonce: WPVG_ADMIN.nonce,
                    vcardId: vcardId
                }, function(response) {
                    loadAllSections();
                });

            }
        );
    });

    /**
     * ============================
     *  ACTION : Réactiver
     * ============================
     */
    $(document).on('click', '.wpvg-enable', function() {
        const vcardId = $(this).data('id');

        openModal(
            'Réactiver la vCard',
            'Voulez-vous réactiver cette vCard ?',
            function() {

                $.post(WPVG_ADMIN.ajax_url, {
                    action: 'wpvg_action_enable',
                    nonce: WPVG_ADMIN.nonce,
                    vcardId: vcardId
                }, function(response) {
                    loadAllSections();
                });

            }
        );
    });

    /**
     * ============================
     *  ACTION : Supprimer (OFF)
     * ============================
     */
    $(document).on('click', '.wpvg-delete', function() {
        const vcardId = $(this).data('id');

        openModal(
            'Supprimer la vCard',
            'Cette action est définitive. Supprimer cette vCard ?',
            function() {

                $.post(WPVG_ADMIN.ajax_url, {
                    action: 'wpvg_action_delete',
                    nonce: WPVG_ADMIN.nonce,
                    vcardId: vcardId
                }, function(response) {
                    loadAllSections();
                });

            }
        );
    });

    /**
     * ============================
     *  ACTION : Activer un pending
     * ============================
     */
    $(document).on('click', '.wpvg-activate-pending', function() {
        const token = $(this).data('token');

        openModal(
            'Activer la vCard',
            'Activer cette vCard maintenant ?',
            function() {

                $.post(WPVG_ADMIN.ajax_url, {
                    action: 'wpvg_action_activate_pending',
                    nonce: WPVG_ADMIN.nonce,
                    token: token,
                    vcardId: token
                }, function(response) {
                    loadAllSections();
                });

            }
        );
    });

    /**
     * ============================
     *  ACTION : Copier URL
     * ============================
     */
    $(document).on('click', '.wpvg-copy', function() {
        navigator.clipboard.writeText($(this).data('url'));
        $(this).text('Copié !');
        setTimeout(() => $(this).text('Copier URL'), 1200);
    });
	
	/**
	 * ============================
	 *  ACTION : Voir la vCard
	 * ============================
	 */
	$(document).on('click', '.wpvg-open', function() {
		const url = $(this).data('url');
		if (url) {
			window.open(url, '_blank');
		}
	});


    /**
     * ============================
     *  QR CODE (modale)
     * ============================
     */
    $(document).on('click', '.wpvg-show-qr', function () {

        const url = $(this).data('url');
        if (!url) return;

        $('#wpvg-qr-overlay').css('display', 'flex');

        const container = document.getElementById('wpvg-qr-container');
        if (!container) return;

        const encoded = encodeURIComponent(url);
        const qrSrc = 'https://api.qrserver.com/v1/create-qr-code/?size=256x256&data=' + encoded;

        container.innerHTML = '<img src="' + qrSrc + '" width="256" height="256" alt="QR Code">';
    });

    $(document).on('click', '#wpvg-qr-close', function () {
        $('#wpvg-qr-overlay').hide();
    });

    /**
     * ============================
     *  CHARGEMENT INITIAL
     * ============================
     */
    loadAllSections();

});

jQuery(document).ready(function($){

    $('#wpvg-clean-gdpr').on('click', function(){

        if (!confirm("Confirmer la suppression des miniatures GDPR ?")) {
            return;
        }

        $('#wpvg-clean-result').html("Nettoyage en cours...");

        $.post(WPVG_ADMIN.ajax_url, {
            action: 'wpvg_clean_gdpr_thumbnails',
            nonce: WPVG_ADMIN.nonce
        }, function(response){

            if (response.success) {
                $('#wpvg-clean-result').html(
                    '<span style="color:green;font-weight:bold;">' + response.data.message + '</span>'
                );
            } else {
                $('#wpvg-clean-result').html(
                    '<span style="color:red;font-weight:bold;">Erreur lors du nettoyage.</span>'
                );
            }

        });
    });

});
