<?php
/**
 * Custom field rules management view.
 *
 * @var array $data Data for the view.
 *
 * @package WPR_Translate
 */

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

// Normalize input data for the view.
$custom_field_rules = isset( $data['custom_field_rules'] ) && is_array( $data['custom_field_rules'] ) ? $data['custom_field_rules'] : array();
$custom_field_state = isset( $data['custom_field_state'] ) && is_array( $data['custom_field_state'] ) ? $data['custom_field_state'] : array();
$available_actions   = array(
    'copy'      => esc_html__( 'Copy', 'wpr-translate' ),
    'translate' => esc_html__( 'Translate', 'wpr-translate' ),
    'copy-once' => esc_html__( 'Copy Once', 'wpr-translate' ),
    'ignore'    => esc_html__( 'Ignore', 'wpr-translate' ),
);
$action_sections = array(
    'translate' => isset( $available_actions['translate'] ) ? $available_actions['translate'] : esc_html__( 'Translate', 'wpr-translate' ),
    'copy'      => isset( $available_actions['copy'] ) ? $available_actions['copy'] : esc_html__( 'Copy', 'wpr-translate' ),
    'copy-once' => isset( $available_actions['copy-once'] ) ? $available_actions['copy-once'] : esc_html__( 'Copy Once', 'wpr-translate' ),
    'ignore'    => isset( $available_actions['ignore'] ) ? $available_actions['ignore'] : esc_html__( 'Ignore', 'wpr-translate' ),
);
// Prepare grouped rule structures for rendering.
$grouped_rules  = array();
$post_type_list = array();

// Group rules by their post type so each section renders its own table.
foreach ( $custom_field_rules as $rule_id => $rule ) {
    $post_type = isset( $rule['post'] ) ? sanitize_key( $rule['post'] ) : '';

    if ( ! isset( $grouped_rules[ $post_type ] ) ) {
        $grouped_rules[ $post_type ] = array();
        $post_type_list[]            = $post_type;
    }

    $grouped_rules[ $post_type ][ $rule_id ] = $rule;
}
?>
<div class="wrap wpr-translate-admin">
    <h1><?php esc_html_e( 'Custom Field Rules', 'wpr-translate' ); ?></h1>

    <?php settings_errors( 'wpr_cf_preferences' ); ?>

    <div class="wpr-card wpr-settings-card wpr-cf-rules-card">
        <div class="wpr-cf-header">
            <h2><?php esc_html_e( 'Custom Field Rules', 'wpr-translate' ); ?></h2>
            <p class="description"><?php esc_html_e( 'Define how each custom field is handled when creating or updating translations. Copy keeps values synced from the original, Copy Once duplicates the value only on creation, Translate expects a language-specific value, and Ignore leaves the field unchanged. These rules are applied whenever translation drafts are created or refreshed.', 'wpr-translate' ); ?></p>
        </div>

        <div class="wpr-cf-status">
            <div class="wpr-cf-status-item">
                <div class="wpr-cf-status-label"><?php esc_html_e( 'Rules File', 'wpr-translate' ); ?></div>
                <div class="wpr-cf-status-value"><?php echo esc_html( isset( $custom_field_state['path'] ) ? $custom_field_state['path'] : '' ); ?></div>
            </div>
            <div class="wpr-cf-status-item">
                <div class="wpr-cf-status-label"><?php esc_html_e( 'Current Hash', 'wpr-translate' ); ?></div>
                <div class="wpr-cf-status-value"><?php echo esc_html( isset( $custom_field_state['current_hash'] ) ? $custom_field_state['current_hash'] : '' ); ?></div>
            </div>
            <div class="wpr-cf-status-item">
                <div class="wpr-cf-status-label"><?php esc_html_e( 'Last Loaded Hash', 'wpr-translate' ); ?></div>
                <div class="wpr-cf-status-value"><?php echo esc_html( isset( $custom_field_state['hash'] ) ? $custom_field_state['hash'] : '' ); ?></div>
            </div>
            <div class="wpr-cf-status-item">
                <div class="wpr-cf-status-label"><?php esc_html_e( 'Status', 'wpr-translate' ); ?></div>
                <div class="wpr-cf-status-value"><?php echo esc_html( isset( $custom_field_state['status'] ) ? $custom_field_state['status'] : '' ); ?></div>
            </div>
            <?php if ( ! empty( $custom_field_state['last_loaded'] ) ) :
                $timestamp = (int) $custom_field_state['last_loaded'];
                $format    = trim( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ) );
                $formatted = function_exists( 'wp_date' ) ? wp_date( $format, $timestamp ) : date_i18n( $format, $timestamp );
                ?>
                <div class="wpr-cf-status-item">
                    <div class="wpr-cf-status-label"><?php esc_html_e( 'Last Reloaded', 'wpr-translate' ); ?></div>
                    <div class="wpr-cf-status-value"><?php echo esc_html( $formatted ); ?></div>
                </div>
            <?php endif; ?>
            <?php if ( ! empty( $custom_field_state['error_message'] ) ) : ?>
                <div class="wpr-cf-status-item wpr-cf-status-error">
                    <div class="wpr-cf-status-label"><?php esc_html_e( 'Last Error', 'wpr-translate' ); ?></div>
                    <div class="wpr-cf-status-value"><?php echo esc_html( $custom_field_state['error_message'] ); ?></div>
                </div>
            <?php endif; ?>
        </div>

        <div class="wpr-cf-rules" id="wpr-cf-rules">
            <?php if ( empty( $custom_field_rules ) ) : ?>
                <div class="wpr-cf-rule-empty"><?php esc_html_e( 'No custom field rules are currently loaded.', 'wpr-translate' ); ?></div>
            <?php else : ?>
                <?php foreach ( $post_type_list as $post_type ) :
                    $post_rules = isset( $grouped_rules[ $post_type ] ) ? $grouped_rules[ $post_type ] : array();
                    $label      = $post_type;
                    $rules_by_action = array(
                        'translate' => array(),
                        'copy'      => array(),
                        'copy-once' => array(),
                        'ignore'    => array(),
                    );

                    // Split rows by their currently selected action.
                    foreach ( $post_rules as $rule_key => $rule_value ) {
                        $current_action = '';

                        if ( is_array( $rule_value ) ) {
                            $current_action = isset( $rule_value['action'] ) ? (string) $rule_value['action'] : '';

                            if ( '' === $current_action && isset( $rule_value['file_action'] ) ) {
                                $current_action = (string) $rule_value['file_action'];
                            }
                        }

                        if ( ! isset( $rules_by_action[ $current_action ] ) ) {
                            $current_action = 'ignore';
                        }

                        $rules_by_action[ $current_action ][ $rule_key ] = $rule_value;
                    }

                    if ( '' === $label ) {
                        $label = esc_html__( 'General', 'wpr-translate' );
                    } else {
                        $post_object = get_post_type_object( $post_type );

                        if ( $post_object && isset( $post_object->labels->singular_name ) && $post_object->labels->singular_name ) {
                            $label = $post_object->labels->singular_name;
                        }
                    }
                    ?>
                    <div class="wpr-cf-rules-group" data-post-type="<?php echo esc_attr( $post_type ); ?>">
                        <h3 class="wpr-cf-group-title"><?php printf( esc_html__( '%s Fields', 'wpr-translate' ), esc_html( $label ) ); ?></h3>
                        <?php
                        // Show a quick reload button for property fields.
                        if ( 'estate_property' === $post_type ) :
                        ?>
                            <form method="post" class="wpr-cf-reload-form wpr-cf-reload-form-inline">
                                <?php wp_nonce_field( 'wpr_cf_reload', 'wpr_cf_reload_nonce' ); ?>
                                <input type="hidden" name="wpr_cf_action" value="reload" />
                                <div class="wpr-settings-actions">
                                    <button type="submit" class="button"><?php esc_html_e( 'Reload from JSON File', 'wpr-translate' ); ?></button>
                                </div>
                            </form>
                        <?php endif; ?>
                        <div class="wpr-cf-action-accordion">
                            <?php foreach ( $action_sections as $action_key => $action_label ) :
                                $action_rules = isset( $rules_by_action[ $action_key ] ) && is_array( $rules_by_action[ $action_key ] ) ? $rules_by_action[ $action_key ] : array();
                                $panel_id     = 'wpr-cf-panel-' . sanitize_html_class( '' !== $post_type ? $post_type : 'general' ) . '-' . sanitize_html_class( $action_key );
                                $is_open      = ( 'translate' === $action_key );
                                ?>
                                <div class="wpr-cf-accordion-item" data-action="<?php echo esc_attr( $action_key ); ?>">
                                    <div class="wpr-cf-accordion-toggle" role="button" tabindex="0" aria-expanded="<?php echo $is_open ? 'true' : 'false'; ?>" data-panel-id="<?php echo esc_attr( $panel_id ); ?>">
                                        <div class="wpr-cf-accordion-title"><?php echo esc_html( $action_label ); ?></div>
                                        <div class="wpr-cf-accordion-count"><?php echo esc_html( (string) count( $action_rules ) ); ?></div>
                                    </div>
                                    <div id="<?php echo esc_attr( $panel_id ); ?>" class="wpr-cf-accordion-panel<?php echo $is_open ? ' is-open' : ''; ?>">
                                        <?php if ( empty( $action_rules ) ) : ?>
                                            <div class="wpr-cf-accordion-empty"><?php esc_html_e( 'No custom fields in this action group.', 'wpr-translate' ); ?></div>
                                        <?php else : ?>
                                            <div class="wpr-cf-rules-table">
                                                <?php foreach ( $action_rules as $rule_id => $rule ) :
                                                    $rule_id     = isset( $rule['id'] ) ? $rule['id'] : $rule_id;
                                                    $rule_uid    = isset( $rule['uid'] ) ? $rule['uid'] : $rule_id;
                                                    $rule_label  = isset( $rule['label'] ) ? $rule['label'] : $rule_id;
                                                    $rule_action = isset( $rule['action'] ) ? $rule['action'] : '';
                                                    $file_action = isset( $rule['file_action'] ) ? $rule['file_action'] : '';
                                                    $rule_source = isset( $rule['source'] ) ? $rule['source'] : 'file';
                                                    $description = isset( $rule['description'] ) ? $rule['description'] : '';

                                                    if ( '' === $rule_action && '' !== $file_action ) {
                                                        $rule_action = $file_action;
                                                    }
                                                    ?>
                                                    <div class="wpr-cf-rule-row<?php echo 'override' === $rule_source ? ' has-override' : ''; ?>" data-rule-id="<?php echo esc_attr( $rule_uid ); ?>" data-rule-source="<?php echo esc_attr( $rule_source ); ?>">
                                                        <div class="wpr-cf-rule-col wpr-cf-rule-col-title">
                                                            <div class="wpr-cf-rule-title"><?php echo esc_html( $rule_label ); ?></div>
                                                            <div class="wpr-cf-rule-key"><?php echo esc_html( $rule_id ); ?></div>
                                                            <?php if ( '' !== $description ) : ?>
                                                                <div class="wpr-cf-rule-description"><?php echo esc_html( $description ); ?></div>
                                                            <?php endif; ?>
                                                            <?php if ( '' !== $file_action ) : ?>
                                                                <div class="wpr-cf-rule-default"><?php printf( esc_html__( 'Default: %s', 'wpr-translate' ), esc_html( $file_action ) ); ?></div>
                                                            <?php endif; ?>
                                                        </div>
                                                        <div class="wpr-cf-rule-col wpr-cf-rule-col-action">
                                                            <select class="wpr-cf-rule-select" data-rule-id="<?php echo esc_attr( $rule_uid ); ?>" data-default-action="<?php echo esc_attr( $file_action ); ?>">
                                                                <?php foreach ( $available_actions as $value => $label_text ) : ?>
                                                                    <option value="<?php echo esc_attr( $value ); ?>" <?php selected( $rule_action, $value ); ?>><?php echo esc_html( $label_text ); ?></option>
                                                                <?php endforeach; ?>
                                                            </select>
                                                            <div class="wpr-cf-rule-status" role="status" aria-live="polite"></div>
                                                        </div>
                                                    </div>
                                                <?php endforeach; ?>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>

        <form method="post" class="wpr-cf-reload-form">
            <?php wp_nonce_field( 'wpr_cf_reload', 'wpr_cf_reload_nonce' ); ?>
            <input type="hidden" name="wpr_cf_action" value="reload" />
            <div class="wpr-settings-actions">
                <button type="submit" class="button"><?php esc_html_e( 'Reload from JSON File', 'wpr-translate' ); ?></button>
            </div>
        </form>
    </div>
</div>
