<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

add_action('admin_menu', function () {
    add_menu_page(
        __('Trusted Clients', 'trusted-clients'),
        __('Trusted Clients', 'trusted-clients'),
        'manage_options',
        'trusted-clients',
        'trusted_clients_admin_tabs_page',
        'dashicons-groups',
        30
    );
});

add_action('admin_enqueue_scripts', function ($hook) {
    if (strpos($hook, 'trusted-clients') === false) return;

    wp_enqueue_media();

    wp_enqueue_style(
        'trusted-clients-admin-style',
        plugin_dir_url(__FILE__) . 'assets/css/admin-style.css',
        [],
        filemtime(plugin_dir_path(__FILE__) . 'assets/css/admin-style.css')
    );

    wp_enqueue_script(
        'trusted-clients-admin-script',
        plugin_dir_url(__FILE__) . 'assets/js/admin-script.js',
        ['jquery'],
        filemtime(plugin_dir_path(__FILE__) . 'assets/js/admin-script.js'),
        true
    );
});

function trusted_clients_admin_tabs_page() {
    if (!current_user_can('manage_options')) return;

    if (isset($_POST['trusted_clients_guardar_fotos']) && check_admin_referer('trusted_clients_guardar_fotos_action', 'trusted_clients_guardar_fotos_nonce')) {
        $total = intval($_POST['trusted_clients_total_fotos'] ?? 6); // Sin límite artificial
        update_option("trusted_clients_total_fotos", $total);

        for ($i = 1; $i <= $total; $i++) {
            $key = "trusted_clients_foto_$i";
            if (isset($_POST[$key])) {
                update_option($key, esc_url_raw(wp_unslash($_POST[$key])));
            } else {
                delete_option($key);
            }
        }

        echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__('Fotos guardadas correctamente.', 'trusted-clients') . '</p></div>';
    }

    if (isset($_POST['trusted_clients_guardar_visual']) && check_admin_referer('trusted_clients_guardar_visual_action', 'trusted_clients_guardar_visual_nonce')) {
        update_option("trusted_clients_mostrar_estrellas", isset($_POST["trusted_clients_mostrar_estrellas"]) ? 1 : 0);
        update_option("trusted_clients_aleatorio", isset($_POST["trusted_clients_aleatorio"]) ? 1 : 0);
        update_option("trusted_clients_texto", sanitize_text_field(wp_unslash($_POST["trusted_clients_texto"] ?? '')));
        update_option("trusted_clients_fotos_mostrar", intval($_POST["trusted_clients_fotos_mostrar"] ?? 6));
        echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__('Opciones de visualización guardadas.', 'trusted-clients') . '</p></div>';
    }

    if (isset($_POST['trusted_clients_enviar_feedback']) && check_admin_referer('trusted_clients_enviar_feedback_action', 'trusted_clients_enviar_feedback_nonce')) {
        $feedback = isset($_POST['trusted_clients_feedback']) ? sanitize_textarea_field(wp_unslash($_POST['trusted_clients_feedback'])) : '';
        update_option('trusted_clients_feedback', $feedback);
        wp_mail('nicolasarche@gmail.com', __('Nuevo feedback desde Trusted Clients', 'trusted-clients'), $feedback, ['Content-Type: text/plain']);
        echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__('¡Gracias por tu comentario!', 'trusted-clients') . '</p></div>';
    }

    $total_fotos = intval(get_option("trusted_clients_total_fotos", 6)); // Sin límite artificial
    $texto = esc_html(get_option("trusted_clients_texto", ''));
    $mostrar_estrellas = intval(get_option('trusted_clients_mostrar_estrellas', 1));
    $aleatorio = intval(get_option('trusted_clients_aleatorio', 0));
    $fotos_mostrar = intval(get_option('trusted_clients_fotos_mostrar', 6));
    $feedback_guardado = get_option('trusted_clients_feedback', '');
?>
<div class="wrap">
    <h1><?php esc_html_e('Trusted Clients', 'trusted-clients'); ?></h1>
    <h2 class="nav-tab-wrapper">
        <a href="#tab-fotos" class="nav-tab nav-tab-active"><?php esc_html_e('Cargar Fotos', 'trusted-clients'); ?></a>
        <a href="#tab-visual" class="nav-tab"><?php esc_html_e('Visualización', 'trusted-clients'); ?></a>
        <a href="#tab-sobre" class="nav-tab"><?php esc_html_e('Sobre Trusted Clients', 'trusted-clients'); ?></a>
    </h2>

    <div id="tab-fotos" class="trusted-clients-tab-content active">
        <form method="post">
            <div class="trusted-clients-grid-container" id="trusted-clients-fotos-container">
                <?php for ($i = 1; $i <= $total_fotos; $i++): 
                    $foto = esc_url(get_option("trusted_clients_foto_$i")); ?>
                    <div class="trusted-clients-grid-item" id="<?php echo esc_attr('trusted-clients-row-' . $i); ?>">
                        <?php $label = sprintf(__('Foto #%d', 'trusted-clients'), $i); ?>
                        <label><strong><h4><?php echo esc_html($label); ?></h4></strong></label>
                        <div class="trusted-clients-thumbnail"><?php if ($foto): ?><img src="<?php echo esc_url($foto); ?>" alt="<?php esc_attr_e('Vista previa de cliente', 'trusted-clients'); ?>" /><?php endif; ?></div>
                        <input type="text" name="<?php echo esc_attr("trusted_clients_foto_$i"); ?>" id="<?php echo esc_attr("trusted_clients_foto_$i"); ?>" value="<?php echo esc_url($foto); ?>" class="regular-text" />
                        <div class="trusted-clients-grid-buttons">
                            <button type="button" class="button trusted-clients-media-upload" data-target="<?php echo esc_attr("trusted_clients_foto_$i"); ?>"><?php esc_html_e('Seleccionar', 'trusted-clients'); ?></button>
                            <button type="button" class="button trusted-clients-remove-foto" data-row="<?php echo esc_attr("trusted-clients-row-$i"); ?>"><?php esc_html_e('Eliminar', 'trusted-clients'); ?></button>
                        </div>
                    </div>
                <?php endfor; ?>
            </div>

            <p><button type="button" class="button button-secondary" id="trusted-clients-agregar-foto"><?php esc_html_e('Agregar otra foto', 'trusted-clients'); ?></button></p>
            <p id="trusted-clients-max-fotos-msg" style="color:#888;"></p>

            <input type="hidden" name="trusted_clients_total_fotos" id="trusted_clients_total_fotos" value="<?php echo esc_attr($total_fotos); ?>" />
            <input type="hidden" name="trusted_clients_guardar_fotos" value="1" />
            <?php wp_nonce_field('trusted_clients_guardar_fotos_action', 'trusted_clients_guardar_fotos_nonce'); ?>
            <?php submit_button(__('Guardar Fotos', 'trusted-clients')); ?>
        </form>
    </div>

    <div id="tab-visual" class="trusted-clients-tab-content">
        <form method="post">
            <table class="form-table">
                <tr>
                    <th><?php esc_html_e('¿Mostrar estrellas?', 'trusted-clients'); ?></th>
                    <td><input type="checkbox" name="trusted_clients_mostrar_estrellas" value="1" <?php checked($mostrar_estrellas, 1); ?>></td>
                </tr>
                <tr>
                    <th><?php esc_html_e('Texto personalizado', 'trusted-clients'); ?></th>
                    <td>
                        <textarea name="trusted_clients_texto" class="large-text"><?php echo esc_textarea($texto); ?></textarea>
                        <?php
                        $frases = [
                            __('+ de 20 dueños de agencia confían en mi trabajo.', 'trusted-clients'),
                            __('Clientes reales, resultados comprobados.', 'trusted-clients'),
                            __('Personas increíbles con las que tuve el placer de trabajar.', 'trusted-clients'),
                            __('Empresas que apostaron por mis ideas.', 'trusted-clients'),
                            __('No son solo clientes, son relaciones que crecen.', 'trusted-clients'),
                        ];
                        foreach ($frases as $frase) {
                            echo '<p><a href="#" class="trusted-clients-frase" data-frase="' . esc_attr($frase) . '">' . esc_html($frase) . '</a></p>';
                        }
                        ?>
                    </td>
                </tr>
                <tr>
                    <th><?php esc_html_e('Cantidad de fotos a mostrar', 'trusted-clients'); ?></th>
                    <td>
                        <select name="trusted_clients_fotos_mostrar">
                            <?php for ($i = 1; $i <= 6; $i++): ?>
                                <option value="<?php echo esc_attr($i); ?>" <?php selected($fotos_mostrar, $i); ?>><?php echo esc_html($i); ?></option>
                            <?php endfor; ?>
                        </select>
                    </td>
                </tr>
                <tr>
                    <th><?php esc_html_e('¿Mostrar aleatoriamente?', 'trusted-clients'); ?></th>
                    <td><input type="checkbox" name="trusted_clients_aleatorio" value="1" <?php checked($aleatorio, 1); ?>></td>
                </tr>
            </table>
            <input type="hidden" name="trusted_clients_guardar_visual" value="1" />
            <p>
                <strong><?php esc_html_e('Shortcode:', 'trusted-clients'); ?></strong>
                <code>[trusted_clients]</code>
                <br>
                <em><?php esc_html_e('Usá este shortcode en cualquier página, entrada o widget para mostrar el contenido.', 'trusted-clients'); ?></em>
            </p>

            <?php wp_nonce_field('trusted_clients_guardar_visual_action', 'trusted_clients_guardar_visual_nonce'); ?>
            <?php submit_button(__('Guardar Opciones', 'trusted-clients')); ?>
        </form>
    </div>

    <div id="tab-sobre" class="trusted-clients-tab-content">
        <form method="post">
            <p><?php esc_html_e('Este plugin te permite mostrar visualmente la confianza que tus clientes tienen en vos.', 'trusted-clients'); ?></p>
            <textarea name="trusted_clients_feedback" class="large-text" rows="5"><?php echo esc_textarea($feedback_guardado); ?></textarea>
            <p><input type="submit" name="trusted_clients_enviar_feedback" class="button button-primary" value="<?php esc_attr_e('Enviar Feedback', 'trusted-clients'); ?>"></p>
            <?php wp_nonce_field('trusted_clients_enviar_feedback_action', 'trusted_clients_enviar_feedback_nonce'); ?>
        </form>
    </div>
</div>
<?php
}
