<?php
/**
 * Admin forms list template
 *
 * @package SPAI_Contact_Form
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

// Get forms
$db_handler = new SPAI_DB_Handler();
$forms = $db_handler->get_forms();
?>

<div class="wrap spai-admin-wrapper">
    <div class="spai-admin-header">
        <h1>
            <?php _e('SPAI Contact Forms', 'spai-contact-form'); ?>
            <a href="<?php echo admin_url('admin.php?page=spai-contact-form-new'); ?>" class="page-title-action">
                <?php _e('Add New', 'spai-contact-form'); ?>
            </a>
            <button type="button" id="import-form-btn" class="page-title-action">
                <?php _e('Import Form', 'spai-contact-form'); ?>
            </button>
        </h1>
    </div>
    
    <div class="spai-admin-content">
        <!-- Import form file input (hidden by default) -->
        <div id="import-form-container" style="display: none; margin: 20px 0; padding: 15px; background: #f1f1f1; border: 1px solid #ccc;">
            <h3><?php _e('Import Form', 'spai-contact-form'); ?></h3>
            <input type="file" id="import-form-file" accept=".json" />
            <button type="button" id="do-import-btn" class="button button-primary"><?php _e('Upload', 'spai-contact-form'); ?></button>
            <button type="button" id="cancel-import-btn" class="button"><?php _e('Cancel', 'spai-contact-form'); ?></button>
            <div id="import-status" style="margin-top: 10px;"></div>
        </div>
        
        <?php if (empty($forms)): ?>
            <p><?php _e('No forms found. Create your first form!', 'spai-contact-form'); ?></p>
        <?php else: ?>
            <table class="wp-list-table widefat fixed striped">
                <thead>
                    <tr>
                        <th><?php _e('Form Name', 'spai-contact-form'); ?></th>
                        <th><?php _e('Shortcode', 'spai-contact-form'); ?></th>
                        <th><?php _e('Status', 'spai-contact-form'); ?></th>
                        <th><?php _e('Created', 'spai-contact-form'); ?></th>
                        <th><?php _e('Actions', 'spai-contact-form'); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($forms as $form): ?>
                        <tr>
                            <td>
                                <strong>
                                    <a href="<?php echo admin_url('admin.php?page=spai-contact-form-new&form_id=' . $form->id); ?>">
                                        <?php echo esc_html($form->form_name); ?>
                                    </a>
                                </strong>
                            </td>
                            <td>
                                <code>[spai_form id="<?php echo $form->id; ?>"]</code>
                            </td>
                            <td>
                                <?php if ($form->active): ?>
                                    <span style="color: #46b450;"><?php _e('Active', 'spai-contact-form'); ?></span>
                                <?php else: ?>
                                    <span style="color: #dc3232;"><?php _e('Inactive', 'spai-contact-form'); ?></span>
                                <?php endif; ?>
                            </td>
                            <td><?php echo date_i18n(get_option('date_format'), strtotime($form->created_at)); ?></td>
                            <td>
                                <a href="<?php echo admin_url('admin.php?page=spai-contact-form-new&form_id=' . $form->id); ?>">
                                    <?php _e('Edit', 'spai-contact-form'); ?>
                                </a>
                                |
                                <a href="#" class="export-form" data-form-id="<?php echo $form->id; ?>">
                                    <?php _e('Export', 'spai-contact-form'); ?>
                                </a>
                                |
                                <a href="#" class="delete-form" data-form-id="<?php echo $form->id; ?>" style="color: #dc3232;">
                                    <?php _e('Delete', 'spai-contact-form'); ?>
                                </a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
    </div>
</div>

<script>
jQuery(document).ready(function($) {
    // Delete form handler
    $('.delete-form').on('click', function(e) {
        e.preventDefault();
        
        if (!confirm('<?php _e('Are you sure you want to delete this form?', 'spai-contact-form'); ?>')) {
            return;
        }
        
        var formId = $(this).data('form-id');
        var $row = $(this).closest('tr');
        
        $.post(ajaxurl, {
            action: 'spai_delete_form',
            nonce: '<?php echo wp_create_nonce('spai_admin_nonce'); ?>',
            form_id: formId
        }, function(response) {
            if (response.success) {
                $row.fadeOut();
            } else {
                alert(response.data || 'Failed to delete form');
            }
        });
    });
    
    // Export form handler
    $('.export-form').on('click', function(e) {
        e.preventDefault();
        
        var formId = $(this).data('form-id');
        
        $.post(ajaxurl, {
            action: 'spai_export_form',
            nonce: '<?php echo wp_create_nonce('spai_admin_nonce'); ?>',
            form_id: formId
        }, function(response) {
            if (response.success) {
                // Create blob and download
                var data = JSON.stringify(response.data, null, 2);
                var blob = new Blob([data], {type: 'application/json'});
                var url = window.URL.createObjectURL(blob);
                var a = document.createElement('a');
                a.href = url;
                a.download = 'spai-form-' + response.data.form_name.replace(/[^a-z0-9]/gi, '-').toLowerCase() + '-' + new Date().toISOString().split('T')[0] + '.json';
                document.body.appendChild(a);
                a.click();
                window.URL.revokeObjectURL(url);
                document.body.removeChild(a);
            } else {
                alert(response.data || 'Export failed');
            }
        });
    });
    
    // Import form handlers
    $('#import-form-btn').on('click', function(e) {
        e.preventDefault();
        $('#import-form-container').slideDown();
    });
    
    $('#cancel-import-btn').on('click', function(e) {
        e.preventDefault();
        $('#import-form-container').slideUp();
        $('#import-form-file').val('');
        $('#import-status').empty();
    });
    
    $('#do-import-btn').on('click', function(e) {
        e.preventDefault();
        
        var fileInput = document.getElementById('import-form-file');
        var file = fileInput.files[0];
        
        if (!file) {
            alert('Please select a file to import');
            return;
        }
        
        var reader = new FileReader();
        reader.onload = function(e) {
            try {
                var formData = JSON.parse(e.target.result);
                
                $.post(ajaxurl, {
                    action: 'spai_import_form',
                    nonce: '<?php echo wp_create_nonce('spai_admin_nonce'); ?>',
                    form_data: formData
                }, function(response) {
                    if (response.success) {
                        $('#import-status').html('<div class="notice notice-success"><p>Form imported successfully!</p></div>');
                        setTimeout(function() {
                            window.location.reload();
                        }, 1500);
                    } else {
                        $('#import-status').html('<div class="notice notice-error"><p>' + (response.data || 'Import failed') + '</p></div>');
                    }
                });
            } catch (error) {
                $('#import-status').html('<div class="notice notice-error"><p>Invalid JSON file</p></div>');
            }
        };
        reader.readAsText(file);
    });
});
</script>
