<?php
/**
 * Conditional Redirects Add/Edit Form
 * 2-column layout: Main form (big) + Sidebar (small)
 *
 * @package Switchboard
 * @since 1.0.0
 */

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

// Get rule data if editing
$is_edit = !empty($_GET['rule']);
$rule_id = $is_edit ? intval($_GET['rule']) : 0;
$rule_data = [];

if ($is_edit) {
    global $wpdb;
    $table_name = $wpdb->prefix . 'switchboard_conditional_redirects';

    $rule_data = $wpdb->get_row(
        $wpdb->prepare("SELECT * FROM {$table_name} WHERE id = %d", $rule_id),
        ARRAY_A
    );

    if (!$rule_data) {
        wp_die(esc_html__('Redirect rule not found.', 'wpswitchboard'));
    }

    // Decode conditions
    $rule_data['conditions'] = json_decode($rule_data['conditions'], true);
    if (!is_array($rule_data['conditions'])) {
        $rule_data['conditions'] = [];
    }
}

// Set defaults
$defaults = [
    'rule_name' => '',
    'priority' => 10,
    'source_url' => '',
    'redirect_action' => 'fixed',
    'redirect_url' => '',
    'redirect_type' => '301',
    'is_active' => true,
    'conditions' => [],
];

$rule_data = array_merge($defaults, $rule_data);
$conditions = $rule_data['conditions'];
?>

<!-- Add/Edit Form -->
<form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" id="cr-form">
    <?php wp_nonce_field('cr_save', 'cr_nonce'); ?>
    <input type="hidden" name="action" value="cr_save">
    <input type="hidden" name="is_edit" value="<?php echo $is_edit ? '1' : '0'; ?>">
    <?php if ($is_edit): ?>
        <input type="hidden" name="rule_id" value="<?php echo esc_attr($rule_id); ?>">
    <?php endif; ?>

    <!-- 2-Column Layout -->
    <div class="sb-module-form-layout">
        <!-- Main Column (Big) -->
        <div class="sb-module-form-main">
            <!-- Basic Settings -->
            <div class="sb-module-card sb-module-form-section">
                <div class="sb-module-card-header">
                    <div class="sb-module-card-header-left">
                        <h2 class="sb-module-card-title"><?php esc_html_e('Basic Settings', 'wpswitchboard'); ?></h2>
                        <p class="sb-module-card-desc"><?php esc_html_e('Core information for your redirect rule', 'wpswitchboard'); ?></p>
                    </div>
                </div>
                <div class="sb-module-card-body">
                    <div class="sb-module-form-group">
                        <label for="rule_name" class="sb-module-form-label">
                            <?php esc_html_e('Rule Name', 'wpswitchboard'); ?>
                            <span class="sb-module-required">*</span>
                        </label>
                        <input type="text" name="rule_name" id="rule_name" value="<?php echo esc_attr($rule_data['rule_name']); ?>" class="sb-module-input" placeholder="<?php esc_attr_e('e.g., Spanish users to ES site', 'wpswitchboard'); ?>" required>
                        <p class="sb-module-form-help"><?php esc_html_e('A descriptive name for this redirect rule', 'wpswitchboard'); ?></p>
                    </div>

                    <div class="sb-module-form-group">
                        <label for="source_url" class="sb-module-form-label"><?php esc_html_e('Source Page (Optional)', 'wpswitchboard'); ?></label>
                        <input type="text" name="source_url" id="source_url" value="<?php echo esc_attr($rule_data['source_url']); ?>" class="sb-module-input" placeholder="<?php esc_attr_e('Leave empty for all frontend pages, or enter: / or /pricing/ or /blog/*', 'wpswitchboard'); ?>">
                        <p class="sb-module-form-help">
                            <strong><?php esc_html_e('Examples:', 'wpswitchboard'); ?></strong>
                            <?php esc_html_e('Empty = all frontend pages (wp-admin always excluded),', 'wpswitchboard'); ?>
                            <code>/</code> <?php esc_html_e('= homepage only,', 'wpswitchboard'); ?>
                            <code>/pricing/</code> <?php esc_html_e('= specific page,', 'wpswitchboard'); ?>
                            <code>/blog/*</code> <?php esc_html_e('= all blog pages', 'wpswitchboard'); ?>
                            <br>
                            <strong><?php esc_html_e('Note:', 'wpswitchboard'); ?></strong> <?php esc_html_e('Redirects never run on wp-admin, AJAX, or REST API requests.', 'wpswitchboard'); ?>
                        </p>
                    </div>
                </div>
            </div>

            <!-- Conditions -->
            <div class="sb-module-card sb-module-form-section">
                <div class="sb-module-card-header">
                    <div class="sb-module-card-header-left">
                        <h2 class="sb-module-card-title"><?php esc_html_e('Conditions', 'wpswitchboard'); ?></h2>
                        <p class="sb-module-card-desc"><?php esc_html_e('All enabled conditions must match for the redirect to trigger', 'wpswitchboard'); ?></p>
                    </div>
                </div>
                <div class="sb-module-card-body">
                    <!-- Language Condition -->
                    <div class="sb-module-option-item" style="margin-bottom: 16px;">
                        <label class="sb-module-checkbox-label" style="margin-bottom: 0;">
                            <input type="checkbox" name="cond_language_enabled" id="cond_language_enabled" value="1" <?php checked(!empty($conditions['language']['enabled'])); ?>>
                            <span class="sb-module-text-semibold"><?php esc_html_e('Browser Language', 'wpswitchboard'); ?></span>
                        </label>
                        <div class="sb-module-form-group" id="cond_language_body" style="display: <?php echo !empty($conditions['language']['enabled']) ? 'block' : 'none'; ?>; margin-top: 12px; margin-left: 24px;">
                            <label for="cond_language_codes" class="sb-module-form-label"><?php esc_html_e('Languages (comma-separated)', 'wpswitchboard'); ?></label>
                            <input type="text" name="cond_language_codes" id="cond_language_codes" value="<?php echo esc_attr($conditions['language']['languages'] ?? ''); ?>" class="sb-module-input" placeholder="<?php esc_attr_e('en, es, fr, de', 'wpswitchboard'); ?>">
                            <p class="sb-module-form-help"><?php esc_html_e('Redirect if user\'s browser language matches any of these codes', 'wpswitchboard'); ?></p>
                        </div>
                    </div>

                    <!-- URL Parameter Condition -->
                    <div class="sb-module-option-item" style="margin-bottom: 16px;">
                        <label class="sb-module-checkbox-label" style="margin-bottom: 0;">
                            <input type="checkbox" name="cond_param_enabled" id="cond_param_enabled" value="1" <?php checked(!empty($conditions['url_param']['enabled'])); ?>>
                            <span class="sb-module-text-semibold"><?php esc_html_e('URL Parameter', 'wpswitchboard'); ?></span>
                        </label>
                        <div id="cond_param_body" style="display: <?php echo !empty($conditions['url_param']['enabled']) ? 'block' : 'none'; ?>; margin-top: 12px; margin-left: 24px;">
                            <div class="sb-module-form-grid">
                                <div class="sb-module-form-group">
                                    <label for="cond_param_name" class="sb-module-form-label"><?php esc_html_e('Parameter Name', 'wpswitchboard'); ?></label>
                                    <input type="text" name="cond_param_name" id="cond_param_name" value="<?php echo esc_attr($conditions['url_param']['param_name'] ?? ''); ?>" class="sb-module-input" placeholder="<?php esc_attr_e('utm_source', 'wpswitchboard'); ?>">
                                </div>
                                <div class="sb-module-form-group">
                                    <label for="cond_param_value" class="sb-module-form-label"><?php esc_html_e('Parameter Value (optional)', 'wpswitchboard'); ?></label>
                                    <input type="text" name="cond_param_value" id="cond_param_value" value="<?php echo esc_attr($conditions['url_param']['param_value'] ?? ''); ?>" class="sb-module-input" placeholder="<?php esc_attr_e('facebook', 'wpswitchboard'); ?>">
                                </div>
                            </div>
                            <p class="sb-module-form-help"><?php esc_html_e('Redirect if URL contains this parameter. Leave value empty to match any value.', 'wpswitchboard'); ?></p>
                        </div>
                    </div>

                    <!-- Referrer Condition -->
                    <div class="sb-module-option-item" style="margin-bottom: 16px;">
                        <label class="sb-module-checkbox-label" style="margin-bottom: 0;">
                            <input type="checkbox" name="cond_referrer_enabled" id="cond_referrer_enabled" value="1" <?php checked(!empty($conditions['referrer']['enabled'])); ?>>
                            <span class="sb-module-text-semibold"><?php esc_html_e('Referrer', 'wpswitchboard'); ?></span>
                        </label>
                        <div class="sb-module-form-group" id="cond_referrer_body" style="display: <?php echo !empty($conditions['referrer']['enabled']) ? 'block' : 'none'; ?>; margin-top: 12px; margin-left: 24px;">
                            <label for="cond_referrer_pattern" class="sb-module-form-label"><?php esc_html_e('Referrer Pattern', 'wpswitchboard'); ?></label>
                            <input type="text" name="cond_referrer_pattern" id="cond_referrer_pattern" value="<?php echo esc_attr($conditions['referrer']['referrer_pattern'] ?? ''); ?>" class="sb-module-input" placeholder="<?php esc_attr_e('facebook.com', 'wpswitchboard'); ?>">
                            <p class="sb-module-form-help"><?php esc_html_e('Redirect if the referrer URL contains this text (partial match)', 'wpswitchboard'); ?></p>
                        </div>
                    </div>

                    <!-- Login Status Condition -->
                    <div class="sb-module-option-item" style="margin-bottom: 0;">
                        <label class="sb-module-checkbox-label" style="margin-bottom: 0;">
                            <input type="checkbox" name="cond_login_enabled" id="cond_login_enabled" value="1" <?php checked(!empty($conditions['login_status']['enabled'])); ?>>
                            <span class="sb-module-text-semibold"><?php esc_html_e('Login Status', 'wpswitchboard'); ?></span>
                        </label>
                        <div class="sb-module-form-group" id="cond_login_body" style="display: <?php echo !empty($conditions['login_status']['enabled']) ? 'block' : 'none'; ?>; margin-top: 12px; margin-left: 24px;">
                            <label for="cond_login_status" class="sb-module-form-label"><?php esc_html_e('User Must Be', 'wpswitchboard'); ?></label>
                            <select name="cond_login_status" id="cond_login_status" class="sb-module-select">
                                <option value="logged_in" <?php selected($conditions['login_status']['status'] ?? '', 'logged_in'); ?>><?php esc_html_e('Logged In', 'wpswitchboard'); ?></option>
                                <option value="logged_out" <?php selected($conditions['login_status']['status'] ?? '', 'logged_out'); ?>><?php esc_html_e('Logged Out', 'wpswitchboard'); ?></option>
                            </select>
                            <p class="sb-module-form-help"><?php esc_html_e('Redirect based on user authentication status', 'wpswitchboard'); ?></p>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Redirect Target -->
            <div class="sb-module-card sb-module-form-section">
                <div class="sb-module-card-header">
                    <div class="sb-module-card-header-left">
                        <h2 class="sb-module-card-title"><?php esc_html_e('Redirect Target', 'wpswitchboard'); ?></h2>
                        <p class="sb-module-card-desc"><?php esc_html_e('Where to redirect users when conditions match', 'wpswitchboard'); ?></p>
                    </div>
                </div>
                <div class="sb-module-card-body">
                    <div class="sb-module-form-group">
                        <label for="redirect_action" class="sb-module-form-label"><?php esc_html_e('Redirect Action', 'wpswitchboard'); ?></label>
                        <select name="redirect_action" id="redirect_action" class="sb-module-select" required>
                            <option value="fixed" <?php selected($rule_data['redirect_action'], 'fixed'); ?>><?php esc_html_e('Fixed URL - Redirect to specific URL', 'wpswitchboard'); ?></option>
                            <option value="append" <?php selected($rule_data['redirect_action'], 'append'); ?>><?php esc_html_e('Append to Path - Add to current URL path (e.g., /es/)', 'wpswitchboard'); ?></option>
                            <option value="parameter" <?php selected($rule_data['redirect_action'], 'parameter'); ?>><?php esc_html_e('Add Parameter - Add query parameter (e.g., lang=es)', 'wpswitchboard'); ?></option>
                        </select>
                        <p class="sb-module-form-help" id="action-description">
                            <?php
                            switch ($rule_data['redirect_action']) {
                                case 'append':
                                    echo esc_html__('Add this path segment to the current URL (e.g., /es/ for language subfolders)', 'wpswitchboard');
                                    break;
                                case 'parameter':
                                    echo esc_html__('Add a query parameter to the current URL (preserves existing parameters)', 'wpswitchboard');
                                    break;
                                default:
                                    echo esc_html__('Redirect to a fixed URL (internal or external)', 'wpswitchboard');
                            }
                            ?>
                        </p>
                    </div>

                    <div class="sb-module-form-group">
                        <label for="redirect_url" class="sb-module-form-label" id="redirect-url-label">
                            <?php
                            switch ($rule_data['redirect_action']) {
                                case 'append':
                                    echo esc_html__('Path to Append', 'wpswitchboard');
                                    break;
                                case 'parameter':
                                    echo esc_html__('Parameter to Add', 'wpswitchboard');
                                    break;
                                default:
                                    echo esc_html__('Redirect URL / Value', 'wpswitchboard');
                            }
                            ?>
                            <span class="sb-module-required">*</span>
                        </label>
                        <input type="text" name="redirect_url" id="redirect_url" value="<?php echo esc_attr($rule_data['redirect_url']); ?>" class="sb-module-input"
                               placeholder="<?php
                               switch ($rule_data['redirect_action']) {
                                   case 'append':
                                       echo esc_attr__('/es/ or /fr/ or /language/', 'wpswitchboard');
                                       break;
                                   case 'parameter':
                                       echo esc_attr__('lang=es or source=facebook', 'wpswitchboard');
                                       break;
                                   default:
                                       echo esc_attr__('https://example.com/page or /internal-page', 'wpswitchboard');
                               }
                               ?>" required>
                        <p class="sb-module-form-help" id="redirect-url-hint">
                            <?php
                            switch ($rule_data['redirect_action']) {
                                case 'append':
                                    echo '<strong>' . esc_html__('Example:', 'wpswitchboard') . '</strong> ' . esc_html__('Enter', 'wpswitchboard') . ' <code>/es/</code> ' . esc_html__('to change', 'wpswitchboard') . ' <code>/about/</code> → <code>/es/about/</code>';
                                    break;
                                case 'parameter':
                                    echo '<strong>' . esc_html__('Example:', 'wpswitchboard') . '</strong> ' . esc_html__('Enter', 'wpswitchboard') . ' <code>lang=es</code> ' . esc_html__('to add', 'wpswitchboard') . ' <code>?lang=es</code> ' . esc_html__('to current URL', 'wpswitchboard');
                                    break;
                                default:
                                    echo esc_html__('Enter a full URL (https://...) or internal path (/page)', 'wpswitchboard');
                            }
                            ?>
                        </p>
                    </div>
                </div>
            </div>

            <!-- Form Actions -->
            <div class="sb-module-form-actions">
                <div class="sb-module-form-actions-left">
                    <?php if ($is_edit): ?>
                        <a href="<?php echo esc_url(wp_nonce_url(add_query_arg(['action' => 'delete', 'rule' => $rule_id], admin_url('admin.php?page=conditional-redirects')), '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'); ?>');">
                            <?php esc_html_e('Delete', 'wpswitchboard'); ?>
                        </a>
                    <?php endif; ?>
                </div>
                <div class="sb-module-form-actions-right">
                    <a href="<?php echo esc_url(admin_url('admin.php?page=conditional-redirects')); ?>" class="sb-module-button sb-module-button-secondary sb-module-button-sm">
                        <?php esc_html_e('Cancel', 'wpswitchboard'); ?>
                    </a>
                    <button type="submit" name="save" class="sb-module-button sb-module-button-primary sb-module-button-sm">
                        <?php echo $is_edit ? esc_html__('Update Rule', 'wpswitchboard') : esc_html__('Create Rule', 'wpswitchboard'); ?>
                    </button>
                </div>
            </div>
        </div>

        <!-- Sidebar Column (Small) -->
        <div class="sb-module-form-sidebar">
            <div class="sb-module-card" style="position: sticky; top: 24px;">
                <div class="sb-module-card-header">
                    <h2 class="sb-module-card-title"><?php esc_html_e('Quick Settings', 'wpswitchboard'); ?></h2>
                </div>
                <div class="sb-module-card-body">
                    <div class="sb-module-form-group">
                        <label class="sb-module-form-label"><?php esc_html_e('Status', 'wpswitchboard'); ?></label>
                        <label class="sb-module-toggle">
                            <input type="checkbox" name="is_active" value="1" <?php checked($rule_data['is_active'], true); ?>>
                            <span class="sb-module-toggle-slider"></span>
                        </label>
                        <p class="sb-module-form-help"><?php esc_html_e('Enable or disable this redirect rule', 'wpswitchboard'); ?></p>
                    </div>

                    <div class="sb-module-form-group">
                        <label for="priority" class="sb-module-form-label"><?php esc_html_e('Priority', 'wpswitchboard'); ?></label>
                        <input type="number" name="priority" id="priority" value="<?php echo esc_attr($rule_data['priority']); ?>" class="sb-module-input" min="0" max="999" required>
                        <p class="sb-module-form-help"><?php esc_html_e('Lower number = higher priority (checked first)', 'wpswitchboard'); ?></p>
                    </div>

                    <div class="sb-module-form-group">
                        <label for="redirect_type" class="sb-module-form-label"><?php esc_html_e('Redirect Type', 'wpswitchboard'); ?></label>
                        <select name="redirect_type" id="redirect_type" class="sb-module-select" required>
                            <option value="301" <?php selected($rule_data['redirect_type'], '301'); ?>><?php esc_html_e('301 Permanent', 'wpswitchboard'); ?></option>
                            <option value="302" <?php selected($rule_data['redirect_type'], '302'); ?>><?php esc_html_e('302 Temporary', 'wpswitchboard'); ?></option>
                        </select>
                        <p class="sb-module-form-help"><?php esc_html_e('Use 302 for testing, 301 for permanent redirects', 'wpswitchboard'); ?></p>
                    </div>

                    <?php if ($is_edit): ?>
                        <div style="margin-top: 24px; padding-top: 24px; border-top: 1px solid var(--primary-50);">
                            <h3 style="font-size: 14px; font-weight: 600; color: var(--primary-900); margin: 0 0 12px 0;"><?php esc_html_e('Rule Info', 'wpswitchboard'); ?></h3>
                            <div style="font-size: 13px; color: #64748b; line-height: 1.6;">
                                <p style="margin: 0 0 8px 0;"><strong><?php esc_html_e('Rule ID:', 'wpswitchboard'); ?></strong> #<?php echo esc_html($rule_id); ?></p>
                                <?php
                                global $wpdb;
                                $table_name = $wpdb->prefix . 'switchboard_conditional_redirects';
                                $hit_count = $wpdb->get_var($wpdb->prepare("SELECT hit_count FROM {$table_name} WHERE id = %d", $rule_id));
                                ?>
                                <p style="margin: 0 0 8px 0;"><strong><?php esc_html_e('Total Hits:', 'wpswitchboard'); ?></strong> <?php echo number_format(intval($hit_count)); ?></p>
                                <p style="margin: 0;"><strong><?php esc_html_e('Status:', 'wpswitchboard'); ?></strong> 
                                    <?php if ($rule_data['is_active']): ?>
                                        <span style="color: #166534;"><?php esc_html_e('Active', 'wpswitchboard'); ?></span>
                                    <?php else: ?>
                                        <span style="color: #991b1b;"><?php esc_html_e('Inactive', 'wpswitchboard'); ?></span>
                                    <?php endif; ?>
                                </p>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</form>

<script>
jQuery(document).ready(function($) {
    // Toggle condition bodies
    $('#cond_language_enabled').on('change', function() {
        $('#cond_language_body').toggle(this.checked);
    });

    $('#cond_param_enabled').on('change', function() {
        $('#cond_param_body').toggle(this.checked);
    });

    $('#cond_referrer_enabled').on('change', function() {
        $('#cond_referrer_body').toggle(this.checked);
    });

    $('#cond_login_enabled').on('change', function() {
        $('#cond_login_body').toggle(this.checked);
    });

    // Handle redirect action change - update placeholders and labels
    $('#redirect_action').on('change', function() {
        const action = $(this).val();
        const label = $('#redirect-url-label');
        const input = $('#redirect_url');
        const hint = $('#redirect-url-hint');
        const description = $('#action-description');

        if (action === 'fixed') {
            label.html('<?php esc_html_e('Redirect URL / Value', 'wpswitchboard'); ?> <span class="sb-module-required">*</span>');
            input.attr('placeholder', '<?php esc_attr_e('https://example.com/page or /internal-page', 'wpswitchboard'); ?>');
            hint.text('<?php esc_attr_e('Enter a full URL (https://...) or internal path (/page)', 'wpswitchboard'); ?>');
            description.text('<?php esc_attr_e('Redirect to a fixed URL (internal or external)', 'wpswitchboard'); ?>');
        } else if (action === 'append') {
            label.html('<?php esc_html_e('Path to Append', 'wpswitchboard'); ?> <span class="sb-module-required">*</span>');
            input.attr('placeholder', '<?php esc_attr_e('/es/ or /fr/ or /language/', 'wpswitchboard'); ?>');
            hint.html('<strong><?php esc_attr_e('Example:', 'wpswitchboard'); ?></strong> <?php esc_attr_e('Enter', 'wpswitchboard'); ?> <code>/es/</code> <?php esc_attr_e('to change', 'wpswitchboard'); ?> <code>/about/</code> → <code>/es/about/</code>');
            description.text('<?php esc_attr_e('Add this path segment to the current URL (e.g., /es/ for language subfolders)', 'wpswitchboard'); ?>');
        } else if (action === 'parameter') {
            label.html('<?php esc_html_e('Parameter to Add', 'wpswitchboard'); ?> <span class="sb-module-required">*</span>');
            input.attr('placeholder', '<?php esc_attr_e('lang=es or source=facebook', 'wpswitchboard'); ?>');
            hint.html('<strong><?php esc_attr_e('Example:', 'wpswitchboard'); ?></strong> <?php esc_attr_e('Enter', 'wpswitchboard'); ?> <code>lang=es</code> <?php esc_attr_e('to add', 'wpswitchboard'); ?> <code>?lang=es</code> <?php esc_attr_e('to current URL', 'wpswitchboard'); ?>');
            description.text('<?php esc_attr_e('Add a query parameter to the current URL (preserves existing parameters)', 'wpswitchboard'); ?>');
        }
    });
});
</script>
