<?php
/**
 * Admin submissions page template
 */

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

$db_handler = new SPAI_DB_Handler();

// Get submissions
global $wpdb;
$table = $wpdb->prefix . 'spai_submissions';
$submissions = $wpdb->get_results("SELECT s.*, f.form_name 
    FROM $table s 
    LEFT JOIN {$wpdb->prefix}spai_forms f ON s.form_id = f.id 
    ORDER BY s.created_at DESC 
    LIMIT 50");
?>

<div class="wrap">
    <h1 class="wp-heading-inline"><?php echo esc_html(get_admin_page_title()); ?></h1>
    <button class="page-title-action" id="export-submissions-json">
        <span class="dashicons dashicons-download" style="margin-top: 3px;"></span> Export as JSON
    </button>
    <button class="page-title-action" id="export-submissions-csv">
        <span class="dashicons dashicons-download" style="margin-top: 3px;"></span> Export as CSV
    </button>
    <hr class="wp-header-end">
    
    <?php if (empty($submissions)): ?>
        <p><?php _e('No submissions yet.', 'spai-contact-form'); ?></p>
    <?php else: ?>
        <table class="wp-list-table widefat fixed striped">
            <thead>
                <tr>
                    <th style="width: 50px;"><?php _e('ID', 'spai-contact-form'); ?></th>
                    <th style="width: 150px;"><?php _e('Form', 'spai-contact-form'); ?></th>
                    <th style="width: 150px;"><?php _e('Date', 'spai-contact-form'); ?></th>
                    <th><?php _e('Summary', 'spai-contact-form'); ?></th>
                    <th style="width: 200px;"><?php _e('Integration Status', 'spai-contact-form'); ?></th>
                    <th style="width: 80px;"><?php _e('Actions', 'spai-contact-form'); ?></th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($submissions as $submission): ?>
                    <?php
                    $data = json_decode($submission->submission_data, true);
                    $status = json_decode($submission->integration_status, true);
                    ?>
                    <tr>
                        <td><?php echo esc_html($submission->id); ?></td>
                        <td><?php echo esc_html($submission->form_name); ?></td>
                        <td><?php echo esc_html($submission->created_at); ?></td>
                        <td>
                            <?php 
                            // Show summary of submission
                            $summary = array();
                            if (!empty($data['first_name']) || !empty($data['last_name'])) {
                                $summary[] = trim(($data['first_name'] ?? '') . ' ' . ($data['last_name'] ?? ''));
                            }
                            if (!empty($data['email'])) {
                                $summary[] = $data['email'];
                            }
                            if (!empty($data['phone'])) {
                                $summary[] = $data['phone'];
                            }
                            echo esc_html(implode(' | ', $summary));
                            ?>
                        </td>
                        <td>
                            <?php if (!empty($status)): ?>
                                <?php foreach ($status as $integration => $info): ?>
                                    <div class="integration-status">
                                        <span class="status-<?php echo esc_attr($info['status']); ?>">
                                            <?php echo esc_html($integration . ': ' . $info['status']); ?>
                                        </span>
                                        <?php if ($info['status'] === 'failed' && !empty($info['error'])): ?>
                                            <div class="error-details" style="margin-top: 5px;">
                                                <a href="#" class="show-error-details" style="color: #d63638; text-decoration: none; font-size: 12px;">
                                                    ⚠️ Show error details
                                                </a>
                                                <div class="error-message" style="display: none; margin-top: 5px; padding: 10px; background: #f8f8f8; border-left: 3px solid #d63638; font-size: 12px;">
                                                    <?php 
                                                    if (is_array($info['error']) && isset($info['error'][0]['message'])) {
                                                        echo '<strong>Error:</strong> ' . esc_html($info['error'][0]['message']);
                                                        if (isset($info['error'][0]['extensions']['error_data'])) {
                                                            echo '<br><strong>Details:</strong> ';
                                                            $error_data = $info['error'][0]['extensions']['error_data'];
                                                            if (is_array($error_data)) {
                                                                foreach ($error_data as $key => $value) {
                                                                    echo '<br>&nbsp;&nbsp;' . esc_html($key) . ': ' . esc_html(is_array($value) ? json_encode($value) : $value);
                                                                }
                                                            } else {
                                                                echo esc_html($error_data);
                                                            }
                                                        }
                                                    } else {
                                                        echo '<strong>Error:</strong> ' . esc_html(is_array($info['error']) ? json_encode($info['error']) : $info['error']);
                                                    }
                                                    ?>
                                                </div>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </td>
                        <td>
                            <button class="button button-small toggle-details" data-submission-id="<?php echo esc_attr($submission->id); ?>">
                                <span class="dashicons dashicons-arrow-down"></span>
                                Details
                            </button>
                        </td>
                    </tr>
                    <tr class="submission-details" id="details-<?php echo esc_attr($submission->id); ?>" style="display: none;">
                        <td colspan="6" style="background: #f6f7f7; padding: 20px;">
                            <div style="display: flex; gap: 20px;">
                                <div style="flex: 1;">
                                    <h4>Submission Data</h4>
                                    <table class="form-table" style="margin: 0;">
                                        <?php foreach ($data as $key => $value): ?>
                                        <tr>
                                            <th style="padding: 5px 10px 5px 0; font-weight: 600;">
                                                <?php echo esc_html(ucwords(str_replace('_', ' ', $key))); ?>:
                                            </th>
                                            <td style="padding: 5px 0;">
                                                <?php echo esc_html(is_array($value) ? implode(', ', $value) : $value); ?>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </table>
                                </div>
                                <?php if (!empty($status)): ?>
                                <div style="flex: 1;">
                                    <h4>Integration Details</h4>
                                    <?php foreach ($status as $integration => $info): ?>
                                        <div style="margin-bottom: 15px; padding: 10px; background: white; border: 1px solid #ccd0d4;">
                                            <h5 style="margin: 0 0 10px 0;"><?php echo esc_html(ucfirst($integration)); ?></h5>
                                            <p><strong>Status:</strong> 
                                                <span class="status-<?php echo esc_attr($info['status']); ?>">
                                                    <?php echo esc_html($info['status']); ?>
                                                </span>
                                            </p>
                                            <?php if (!empty($info['external_id'])): ?>
                                                <?php if ($integration === 'monday'): ?>
                                                    <p><strong>Item ID:</strong> <?php echo esc_html($info['external_id']); ?></p>
                                                    <?php if (!empty($info['board_id'])): ?>
                                                        <p><strong>Board ID:</strong> <?php echo esc_html($info['board_id']); ?></p>
                                                    <?php endif; ?>
                                                <?php else: ?>
                                                    <p><strong>External ID:</strong> <?php echo esc_html($info['external_id']); ?></p>
                                                <?php endif; ?>
                                            <?php endif; ?>
                                            <?php if (!empty($info['updated_at'])): ?>
                                                <p><strong>Processed:</strong> <?php echo esc_html($info['updated_at']); ?></p>
                                            <?php endif; ?>
                                            <?php if ($info['status'] === 'failed' && !empty($info['error'])): ?>
                                                <div style="margin-top: 10px; padding: 10px; background: #fef1f1; border-left: 3px solid #d63638;">
                                                    <?php 
                                                    if (is_array($info['error']) && isset($info['error'][0]['message'])) {
                                                        echo '<strong>Error:</strong> ' . esc_html($info['error'][0]['message']);
                                                    } else {
                                                        echo '<strong>Error:</strong> ' . esc_html(is_array($info['error']) ? json_encode($info['error']) : $info['error']);
                                                    }
                                                    ?>
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                                <?php endif; ?>
                            </div>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    <?php endif; ?>
</div>

<style>
.status-completed { color: #00a32a; font-weight: bold; }
.status-failed { color: #d63638; font-weight: bold; }
.status-pending { color: #dba617; font-weight: bold; }
.integration-status { margin-bottom: 10px; }
.error-message {
    word-wrap: break-word;
    max-width: 400px;
}
</style>

<script>
jQuery(document).ready(function($) {
    // Toggle error details
    $('.show-error-details').on('click', function(e) {
        e.preventDefault();
        var $errorMessage = $(this).siblings('.error-message');
        if ($errorMessage.is(':visible')) {
            $errorMessage.slideUp();
            $(this).text('⚠️ Show error details');
        } else {
            $errorMessage.slideDown();
            $(this).text('⚠️ Hide error details');
        }
    });
    
    // Toggle submission details
    $('.toggle-details').on('click', function() {
        var submissionId = $(this).data('submission-id');
        var $detailsRow = $('#details-' + submissionId);
        var $icon = $(this).find('.dashicons');
        
        if ($detailsRow.is(':visible')) {
            $detailsRow.hide();
            $icon.removeClass('dashicons-arrow-up').addClass('dashicons-arrow-down');
        } else {
            $detailsRow.show();
            $icon.removeClass('dashicons-arrow-down').addClass('dashicons-arrow-up');
        }
    });
});
</script>
