<?php
/**
 * Conditional Redirects List View Template
 * Clean list of all redirect rules
 *
 * @package Switchboard
 * @since 1.0.0
 */

if (!defined('ABSPATH')) {
    exit;
}

// Get instance to access table
global $wpdb;
$table_name = $wpdb->prefix . 'switchboard_conditional_redirects';

// Get all rules
$rules = $wpdb->get_results(
    "SELECT * FROM {$table_name} ORDER BY priority ASC, id ASC",
    ARRAY_A
);

// Calculate stats
$total_rules = count($rules);
$active_rules = 0;
$total_hits = 0;

foreach ($rules as $rule) {
    if ($rule['is_active'] == '1') {
        $active_rules++;
    }
    $total_hits += intval($rule['hit_count']);
}

// Determine current action
$action = isset($_GET['action']) ? sanitize_text_field($_GET['action']) : '';
?>

<div class="wrap sb-module-wrap">
    <!-- Header -->
    <div class="sb-module-header">
        <div class="sb-module-header-left">
            <svg class="sb-module-title-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4"></path>
            </svg>
            <div>
                <h1 class="sb-module-title">
                    <?php if ($action === 'add'): ?>
                        <?php esc_html_e('Creating a Redirect Rule', 'wpswitchboard'); ?>
                    <?php elseif ($action === 'edit'): ?>
                        <?php esc_html_e('Editing Redirect Rule', 'wpswitchboard'); ?>
                    <?php else: ?>
                        <?php esc_html_e('Conditional Redirects', 'wpswitchboard'); ?>
                    <?php endif; ?>
                    <span class="switchboard-badge">SWITCHBOARD</span>
                </h1>
                <p class="sb-module-subtitle">
                    <?php if ($action === 'add'): ?>
                        <?php esc_html_e('Create a new redirect rule with powerful conditional logic', 'wpswitchboard'); ?>
                    <?php elseif ($action === 'edit'): ?>
                        <?php esc_html_e('Edit your redirect rule settings and conditions', 'wpswitchboard'); ?>
                    <?php else: ?>
                        <?php esc_html_e('Redirect users based on conditions like language, URL parameters, referrer, and login status', 'wpswitchboard'); ?>
                    <?php endif; ?>
                </p>
            </div>
        </div>
        <div class="sb-module-header-right">
            <a href="https://docs.wpswitchboard.com/modules/utilities/conditional-redirects" target="_blank" class="sb-module-help-link">
                <span class="sb-module-help-link-icon dashicons dashicons-editor-help"></span>
                Help
            </a>
            <?php if ($action === 'add' || $action === 'edit'): ?>
                <a href="<?php echo esc_url(admin_url('admin.php?page=conditional-redirects')); ?>" class="sb-module-button sb-module-button-secondary">
                    <?php esc_html_e('Go Back', 'wpswitchboard'); ?>
                </a>
            <?php else: ?>
                <a href="<?php echo esc_url(admin_url('admin.php?page=conditional-redirects&action=add')); ?>" class="sb-module-button sb-module-button-primary">
                    <?php esc_html_e('Add New Rule', 'wpswitchboard'); ?>
                </a>
            <?php endif; ?>
        </div>
    </div>

    <!-- Main Content -->
    <div class="sb-module-container">
    <!-- Stats Cards -->
    <div class="sb-module-stats">
        <div class="sb-module-stat-card">
            <div class="sb-module-stat-label"><?php esc_html_e('Total Rules', 'wpswitchboard'); ?></div>
            <div class="sb-module-stat-content">
                <div class="sb-module-stat-value"><?php echo esc_html($total_rules); ?></div>
            </div>
        </div>

        <div class="sb-module-stat-card">
            <div class="sb-module-stat-label"><?php esc_html_e('Active Rules', 'wpswitchboard'); ?></div>
            <div class="sb-module-stat-content">
                <div class="sb-module-stat-value"><?php echo esc_html($active_rules); ?></div>
            </div>
        </div>

        <div class="sb-module-stat-card">
            <div class="sb-module-stat-label"><?php esc_html_e('Total Redirects', 'wpswitchboard'); ?></div>
            <div class="sb-module-stat-content">
                <div class="sb-module-stat-value"><?php echo number_format($total_hits); ?></div>
            </div>
        </div>

        <div class="sb-module-stat-card">
            <div class="sb-module-stat-label"><?php esc_html_e('Avg Hits per Rule', 'wpswitchboard'); ?></div>
            <div class="sb-module-stat-content">
                <div class="sb-module-stat-value"><?php echo $total_rules > 0 ? number_format($total_hits / $total_rules, 1) : '0'; ?></div>
            </div>
        </div>
    </div>

    <?php
    // Check if we're adding or editing
    if ($action === 'add' || $action === 'edit') {
        // Include edit form
        $edit_file = plugin_dir_path(__FILE__) . 'edit.php';
        if (file_exists($edit_file)) {
            include $edit_file;
        }
    } elseif (empty($rules)) {
    ?>
        <!-- Empty State -->
        <div class="sb-module-card">
            <div class="sb-module-card-body">
                <div class="sb-module-empty">
                    <svg class="sb-module-empty-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4"></path>
                    </svg>
                    <h2 class="sb-module-empty-title"><?php esc_html_e('No Redirect Rules Yet', 'wpswitchboard'); ?></h2>
                    <p class="sb-module-empty-desc"><?php esc_html_e('Create conditional redirects based on language, URL parameters, referrer, and login status to personalize user experiences.', 'wpswitchboard'); ?></p>
                    <a href="<?php echo esc_url(admin_url('admin.php?page=conditional-redirects&action=add')); ?>" class="sb-module-button sb-module-button-primary" style="margin-top: 16px;">
                        <?php esc_html_e('Create Your First Rule', 'wpswitchboard'); ?>
                    </a>

                    <div class="sb-module-usecases-section" style="margin-top: 32px;">
                        <h4 style="text-align: center; font-size: 14px; color: #6b7280; margin-bottom: 16px; font-weight: 500;"><?php esc_html_e('Popular Examples', 'wpswitchboard'); ?></h4>
                        <div class="sb-module-usecases-grid">
                            <div class="sb-module-usecase">
                                <svg class="sb-module-usecase-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 5h12M9 3v2m1.048 9.5A18.022 18.022 0 016.412 9m6.088 9h7M11 21l5-10 5 10M12.751 5C11.783 10.77 8.07 15.61 3 18.129"></path>
                                </svg>
                                <strong class="sb-module-usecase-title"><?php esc_html_e('Language Redirect', 'wpswitchboard'); ?></strong>
                                <span class="sb-module-usecase-desc"><?php esc_html_e('Send users to localized content', 'wpswitchboard'); ?></span>
                            </div>
                            <div class="sb-module-usecase">
                                <svg class="sb-module-usecase-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1"></path>
                                </svg>
                                <strong class="sb-module-usecase-title"><?php esc_html_e('Campaign Tracking', 'wpswitchboard'); ?></strong>
                                <span class="sb-module-usecase-desc"><?php esc_html_e('Route by URL parameters', 'wpswitchboard'); ?></span>
                            </div>
                            <div class="sb-module-usecase">
                                <svg class="sb-module-usecase-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8.684 13.342C8.886 12.938 9 12.482 9 12c0-.482-.114-.938-.316-1.342m0 2.684a3 3 0 110-2.684m0 2.684l6.632 3.316m-6.632-6l6.632-3.316m0 0a3 3 0 105.367-2.684 3 3 0 00-5.367 2.684zm0 9.316a3 3 0 105.368 2.684 3 3 0 00-5.368-2.684z"></path>
                                </svg>
                                <strong class="sb-module-usecase-title"><?php esc_html_e('Referrer Routing', 'wpswitchboard'); ?></strong>
                                <span class="sb-module-usecase-desc"><?php esc_html_e('Custom landing pages', 'wpswitchboard'); ?></span>
                            </div>
                            <div class="sb-module-usecase">
                                <svg class="sb-module-usecase-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"></path>
                                </svg>
                                <strong class="sb-module-usecase-title"><?php esc_html_e('Login Based', 'wpswitchboard'); ?></strong>
                                <span class="sb-module-usecase-desc"><?php esc_html_e('Different content by auth', 'wpswitchboard'); ?></span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    <?php 
    } else {
    ?>
        <!-- Rules List -->
        <div class="sb-module-card">
            <div class="sb-module-card-header">
                <div class="sb-module-card-header-left">
                    <h2 class="sb-module-card-title">Your Redirect Rules</h2>
                </div>
                <div class="sb-module-card-header-right">
                    <input type="search" id="cr-search" class="sb-module-search-input" placeholder="Search redirect rules...">
                </div>
            </div>

            <div class="sb-module-card-body sb-module-table-wrapper">
                <table class="sb-module-table">
                    <thead>
                        <tr>
                            <th class="col-active">Active</th>
                            <th class="col-rule-name">Rule Name</th>
                            <th class="col-source">Source</th>
                            <th class="col-conditions">Conditions</th>
                            <th class="col-redirect">Redirect To</th>
                            <th class="col-type">Type</th>
                            <th class="col-hits">Hits</th>
                            <th class="col-actions">Actions</th>
                        </tr>
                    </thead>
                    <tbody id="cr-rules-table">
                        <?php foreach ($rules as $rule):
                            $conditions = json_decode($rule['conditions'], true);
                            if (!is_array($conditions)) {
                                $conditions = [];
                            }
                        ?>
                            <tr class="<?php echo $rule['is_active'] == '0' ? 'inactive' : ''; ?>" data-rule-id="<?php echo esc_attr($rule['id']); ?>">
                                <td class="col-active">
                                    <label class="sb-module-toggle">
                                        <input type="checkbox"
                                               <?php checked($rule['is_active'], '1'); ?>
                                               onchange="toggleRule(<?php echo esc_attr($rule['id']); ?>, this.checked)">
                                        <span class="sb-module-toggle-slider"></span>
                                    </label>
                                </td>
                                <td class="col-rule-name">
                                    <strong><?php echo esc_html($rule['rule_name']); ?></strong>
                                    <br><small class="priority-badge">Priority: <?php echo esc_html($rule['priority']); ?></small>
                                </td>
                                <td class="col-source">
                                    <?php if (!empty($rule['source_url'])): ?>
                                        <code><?php echo esc_html($rule['source_url']); ?></code>
                                    <?php else: ?>
                                        <em class="text-muted">All frontend pages<br><small>(wp-admin excluded)</small></em>
                                    <?php endif; ?>
                                </td>
                                <td class="col-conditions">
                                    <?php
                                    $badges = [];
                                    if (!empty($conditions['language']['enabled'])) {
                                        $badges[] = '<span class="condition-badge language">' . esc_html($conditions['language']['languages']) . '</span>';
                                    }
                                    if (!empty($conditions['url_param']['enabled'])) {
                                        $param_text = !empty($conditions['url_param']['param_value'])
                                            ? esc_html($conditions['url_param']['param_name']) . '=' . esc_html($conditions['url_param']['param_value'])
                                            : esc_html($conditions['url_param']['param_name']);
                                        $badges[] = '<span class="condition-badge param">' . $param_text . '</span>';
                                    }
                                    if (!empty($conditions['referrer']['enabled'])) {
                                        $badges[] = '<span class="condition-badge referrer">' . esc_html($conditions['referrer']['referrer_pattern']) . '</span>';
                                    }
                                    if (!empty($conditions['login_status']['enabled'])) {
                                        $login_text = $conditions['login_status']['status'] === 'logged_in' ? 'Logged In' : 'Logged Out';
                                        $badges[] = '<span class="condition-badge login">' . $login_text . '</span>';
                                    }

                                    if (!empty($badges)) {
                                        echo implode(' ', $badges);
                                    } else {
                                        echo '<em class="text-muted">No conditions</em>';
                                    }
                                    ?>
                                </td>
                                <td class="col-redirect">
                                    <?php
                                    $action_icon = $rule['redirect_action'] === 'append' ? '+' :
                                                  ($rule['redirect_action'] === 'parameter' ? '?' : '&rarr;');
                                    ?>
                                    <span class="action-type"><?php echo $action_icon; ?></span>
                                    <code class="redirect-url"><?php echo esc_html($rule['redirect_url']); ?></code>
                                </td>
                                <td class="col-type">
                                    <span class="type-badge type-<?php echo esc_attr($rule['redirect_type']); ?>">
                                        <?php echo esc_html($rule['redirect_type']); ?>
                                    </span>
                                </td>
                                <td class="col-hits">
                                    <span class="hit-count"><?php echo number_format(intval($rule['hit_count'])); ?></span>
                                </td>
                                <td class="col-actions">
                                    <div class="sb-module-column-actions">
                                        <a href="<?php echo esc_url(admin_url('admin.php?page=conditional-redirects&action=edit&rule=' . intval($rule['id']))); ?>"
                                           class="sb-module-button sb-module-button-secondary sb-module-button-sm">
                                            Edit
                                        </a>
                                        <a href="<?php echo esc_url(wp_nonce_url(admin_url('admin.php?page=conditional-redirects&action=delete&rule=' . intval($rule['id'])), 'delete_rule_' . $rule['id'])); ?>"
                                           class="sb-module-button sb-module-button-danger sb-module-button-sm"
                                           onclick="return confirm('<?php esc_attr_e('Are you sure you want to delete this redirect rule?', 'wpswitchboard'); ?>');">
                                            Delete
                                        </a>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    <?php } ?>

    </div>
</div>

<script>
jQuery(document).ready(function($) {
    // Search functionality
    $('#cr-search').on('input', function() {
        var query = $(this).val().toLowerCase();
        $('#cr-rules-table tr').each(function() {
            var name = $(this).find('.col-rule-name').text().toLowerCase();
            var source = $(this).find('.col-source').text().toLowerCase();
            var conditions = $(this).find('.col-conditions').text().toLowerCase();
            var redirect = $(this).find('.col-redirect').text().toLowerCase();

            if (name.includes(query) || source.includes(query) || conditions.includes(query) || redirect.includes(query)) {
                $(this).show();
            } else {
                $(this).hide();
            }
        });
    });

    // Toggle rule active status
    window.toggleRule = function(id, isActive) {
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'switchboard_conditional_redirects_toggle',
                nonce: '<?php echo wp_create_nonce('switchboard_nonce'); ?>',
                id: id,
                is_active: isActive ? 1 : 0
            },
            success: function(response) {
                if (response.success) {
                    // Update row visual state
                    var $row = $('tr[data-rule-id="' + id + '"]');
                    if (isActive) {
                        $row.removeClass('inactive');
                    } else {
                        $row.addClass('inactive');
                    }

                    // Refresh page to update stats
                    location.reload();
                } else {
                    alert('Error toggling rule: ' + (response.data || 'Unknown error'));
                    // Revert checkbox
                    $('tr[data-rule-id="' + id + '"] input[type="checkbox"]').prop('checked', !isActive);
                }
            },
            error: function() {
                alert('Error toggling rule. Please try again.');
                // Revert checkbox
                $('tr[data-rule-id="' + id + '"] input[type="checkbox"]').prop('checked', !isActive);
            }
        });
    };
});
</script>
