<?php
/**
 * Plugin Name:     AlertaPrecio
 * * Description:     Monitorea y enriquece fichas de producto con scraping.
 * Version:         1.0.0
 * Author:          Jorge Aguilera
 * Author URI:      https://alertaprecio.online
 * Text Domain:     alertaprecio
 * License:         GPLv2 or later
 * License URI:     https://www.gnu.org/licenses/gpl-2.0.html
 * Requires at least: 6.0
 * Requires PHP: 7.4
 */

defined('ABSPATH') or die('No script kiddies please!');

define('ALERTAPRECIO_PLUGIN_PATH', plugin_dir_path(__FILE__));

if ( ! function_exists( 'alertaprecio_get_post_data' ) ) {
    /**
     * Recupera y sanitiza todo $_POST['data'].
     *
     * 1) Deshace slashes de todo el array (wp_unslash).
     * 2) Comprueba que sea array (evita índices indefinidos).
     * 3) Aplica sanitize_text_field() recursivamente.
     *
     * @return array  Array sanitizado (vacío si no viene nada válido).
     */
            function alertaprecio_get_post_data() {
                        check_ajax_referer( 'alertaprecio_nonce', '_ajax_nonce' );

                if ( ! isset( $_POST['data'] ) || ! is_array( $_POST['data'] ) ) {
                    return [];
                }
                $raw = alertaprecio_get_post_var('data', 'array', []);
                $clean = [];
                foreach ( $raw as $key => $value ) {
                    if ( $key === 'alertaprecioUrl' || $key === 'image' ) {
                        $clean[ $key ] = esc_url_raw( $value );
                    } elseif ( in_array( $key, [ 'price', 'scrapedPrice', 'priceScraped', 'markup', 'threshold' ], true ) ) {
                        $clean[ $key ] =$value;
                    } elseif ( $key === 'monitoreable' || $key === 'alertaprecioConfirmed' ) {
                        $clean[ $key ] = filter_var( $value, FILTER_VALIDATE_BOOLEAN );
                    } else {
                        $clean[ $key ] = sanitize_text_field( $value );
                    }
                }
                return $clean;
            }
}
/**
 * Obtiene y sanitiza una variable desde $_POST
 *
 * @param string $key
 * @param string $type 'text' | 'int' | 'float' | 'email' | 'url' | 'bool' | 'array'
 * @param mixed $default
 * @return mixed
 */
// phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- $_POST[$key]
function alertaprecio_get_post_var($key, $type = 'text', $default = '') {
    if (!isset($_POST[$key])) return $default;
    $val = wp_unslash($_POST[$key]);
    if ($type === 'array' && is_array($val)) {
        $clean = [];
        foreach ($val as $k => $v) {
            if (is_array($v)) {
                $clean[$k] = alertaprecio_get_post_var_from_value($v, 'array');
            } else {
                $clean[$k] = sanitize_text_field(wp_unslash($v));
            }
        }
        return $clean;
    }
    switch ($type) {
        case 'int':
            return absint($val);
        case 'float':
            return floatval($val);
        case 'email':
            return sanitize_email($val);
        case 'url':
            return esc_url_raw($val);
        case 'bool':
            return filter_var($val, FILTER_VALIDATE_BOOLEAN);
        default:
            return sanitize_text_field($val);
    }
}
// Para arrays anidados
function alertaprecio_get_post_var_from_value($value, $type = 'text', $default = '') {
    if ($type === 'array' && is_array($value)) {
        $clean = [];
        foreach ($value as $k => $v) {
            if (is_array($v)) {
                $clean[$k] = alertaprecio_get_post_var_from_value($v, 'array');
            } else {
                $clean[$k] = sanitize_text_field(wp_unslash($v));
            }
        }
        return $clean;
    }
    // Para otros tipos (int, float, etc)
    return sanitize_text_field($value);
}


  function alertaprecio_get_sanitize($raw) {
                        check_ajax_referer( 'alertaprecio_nonce', '_ajax_nonce' );

                if ( ! isset( $raw ) || ! is_array( $raw ) ) {
                    return [];
                }
                $cleanRaw   = wp_unslash($raw);
                $clean = [];
                foreach ( $cleanRaw as $key => $value ) {
                    if ( $key === 'alertaprecioUrl' || $key === 'image' ) {
                        $clean[ $key ] = esc_url_raw( $value );
                    } elseif ( in_array( $key, [ 'price', 'scrapedPrice', 'priceScraped', 'markup', 'threshold' ], true ) ) {
                        $clean[ $key ] = floatval( $value );
                    } elseif ( $key === 'monitoreable' || $key === 'alertaprecioConfirmed' ) {
                        $clean[ $key ] = filter_var( $value, FILTER_VALIDATE_BOOLEAN );
                    } else {
                        $clean[ $key ] = sanitize_text_field( $value );
                    }
                }
                return $clean;
            }
            
add_action('admin_enqueue_scripts', function($hook) {
    $screens = [
        'toplevel_page_alertaprecio',
        'alertaprecio_page_alertaprecio_scraper',
        'alertaprecio_page_alertaprecio_enrich',
        'alertaprecio_page_alertaprecio_howto',
        'alertaprecio_page_alertaprecio_scraper_howto'
    ];

    if (!in_array($hook, $screens, true)) {
        return;
    }

    wp_enqueue_style(
        'alertaprecio-admin-style',
        plugin_dir_url(__FILE__) . 'admin/styles.css',
        [],
        filemtime(plugin_dir_path(__FILE__) . 'admin/styles.css')
    );

    wp_enqueue_script(
        'alertaprecio-admin-js',
        plugin_dir_url(__FILE__) . 'admin/general.js',
        ['jquery'],
        filemtime(plugin_dir_path(__FILE__) . 'admin/general.js'),
        true
    );

    wp_enqueue_style(
        'wscraper-style',
        plugins_url('assets/style.css', __FILE__),
        [],
        filemtime(plugin_dir_path(__FILE__) . 'assets/style.css')
    );

    wp_enqueue_script(
        'wscraper-js',
        plugins_url('js/wscraper.js', __FILE__),
        ['jquery'],
        filemtime(plugin_dir_path(__FILE__) . 'js/wscraper.js'),
        true
    );

    wp_localize_script('alertaprecio-admin-js', 'ALERTAPRECIO', [
        'ajaxurl'  => admin_url('admin-ajax.php'),
        'nonce'    => wp_create_nonce('alertaprecio_nonce'),
        'currency' => get_woocommerce_currency(),
        'apiBase'  => 'https://api.alertaprecio.online',
    ]);
});

add_action('admin_menu', function () {
    add_menu_page(
        'AlertaPrecio',
        'AlertaPrecio',
        'manage_options',
        'alertaprecio',
        'alertaprecio_render_admin_page',
        'dashicons-search',
        30
    );
    if (!empty($_COOKIE['alertaprecio_token'])) {
        add_submenu_page(
            'alertaprecio',
            'Monitor',
            'Monitor',
            'manage_options',
            'alertaprecio_scraper',
            'alertaprecio_render_scraper_page'
        );
   
        add_submenu_page(
            'alertaprecio',
            'Enriquecer IA',
            'Enriquecer IA',
            'manage_options',
            'alertaprecio_enrich',
            'alertaprecio_render_enrich_page'
        );
             add_submenu_page(
                'alertaprecio',
                'Ayuda',
                'Ayuda',
                'manage_options',
                'alertaprecio_howto',
                'alertaprecio_render_howto_page'
                );

    }
});
function alertaprecio_render_howto_page() {
  include_once ALERTAPRECIO_PLUGIN_PATH . 'admin/scraper-admin-howto.php';
}
function alertaprecio_render_scraper_page() {
    include_once ALERTAPRECIO_PLUGIN_PATH . 'admin/wscraper-admin-scraper.php';
}
function alertaprecio_render_enrich_page() {
    $prods = get_posts([
      'post_type'      => 'product',
      'posts_per_page' => -1,
      'post_status'    => 'publish',
      'orderby'        => '_id',
      'order'          => 'DSC',
    ]);
    $data = array_map(function($p){
        $en = alertaprecio_calculate_enrich_score($p->ID);
        update_post_meta($p->ID, '_enrich_score', $en);
        $seo = alertaprecio_calculate_seo_score($p->ID);
        update_post_meta($p->ID, '_seo_score', $seo);
        return [
          'id'            => $p->ID,
          'title'         => get_the_title($p),
          'enrich_score'  => $en,
          'seo_score'     => $seo,
          'url'           => get_post_meta($p->ID, '_urlscraper', true),
          'description'   => get_post_field('post_content', $p->ID),
        ];
    }, $prods);
    $tokens = intval($_COOKIE['alertaprecio_alerts'] ?? 0);
    wp_enqueue_script(
      'wscraper-js',
      plugins_url('js/wscraper.js', __FILE__),
      ['jquery'],
      "1.0.0",
      true
    );
    wp_localize_script('wscraper-js', 'ALERTAPRECIO_ENRICH_SETTINGS', [
      'products' => $data,
      'tokens'   => $tokens,
      'apiBase'  => 'https://api.alertaprecio.online',
    ]);
    include plugin_dir_path(__FILE__) . 'admin/wscraper-admin-enrich.html';
}

function alertaprecio_render_admin_page() {
    include_once ALERTAPRECIO_PLUGIN_PATH . 'admin/scraper-admin-page.php';
}

require_once ALERTAPRECIO_PLUGIN_PATH . 'includes/scraper-functions.php';

add_action('wp_ajax_alertaprecio_add_product', 'alertaprecio_add_product');
function alertaprecio_add_product() {
    check_ajax_referer('alertaprecio_nonce', '_ajax_nonce');

    if (!current_user_can('manage_woocommerce')) {
        wp_send_json_error('No autorizado', 403);
    }

    /** phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized */
$data = alertaprecio_get_post_data();
    if (!$data || empty($data['alertaprecioUrl']) || !isset($data['price'])) {
        wp_send_json_error('Datos inválidos', 400);
    }

    $url_scraped = esc_url_raw($data['alertaprecioUrl']);

    $exists = get_posts([
        'post_type'   => 'product',
        'meta_key'    => '_urlscraper',
        'meta_value'  => $url_scraped,
        'posts_per_page' => 1,
        'fields'      => 'ids',
        'post_status' => ['publish', 'draft', 'pending', 'future'],
    ]);

    if ($exists) {
        wp_send_json_error('❌ Esta URL ya existe.', 400);
    }

    $post_id = wp_insert_post([
        'post_title'   => sanitize_text_field($data['title']),
        'post_content' => sanitize_textarea_field($data['description']),
        'post_status'  => 'publish',
        'post_type'    => 'product',
    ]);

    if (is_wp_error($post_id)) {
        wp_send_json_error('❌ Error al crear producto', 500);
    }

    wp_set_object_terms($post_id, 'simple', 'product_type');

    $price       = floatval($data['price']);
    $markup      = isset($data['markup']) ? floatval($data['markup']) : 0;
    $scraped     = floatval($data['scrapedPrice']);
    $threshold   = isset($data['threshold']) ? floatval($data['threshold']) : 80;
    $monitoreable = !empty($data['monitoreable']) ? '1' : '0';

    update_post_meta($post_id, '_regular_price', $price);
    update_post_meta($post_id, '_price', $price);
    update_post_meta($post_id, '_idalertaprecio', '1');
    update_post_meta($post_id, '_urlscraper', $url_scraped);
    update_post_meta($post_id, '_alertaprecio_confirmed', '1'); // Producto recién creado, confirmado automáticamente
    update_post_meta($post_id, '_alertaprecio_monitoreable', $monitoreable);
    update_post_meta($post_id, '_alertaprecio_markup', $markup);
    update_post_meta($post_id, '_alertaprecio_price_scraped', $scraped);
    update_post_meta($post_id, '_alertaprecio_threshold', $threshold);

    if (!empty($data['image'])) {
        $img_id = alertaprecio_attach_external_image(esc_url_raw($data['image']), $post_id);
        if ($img_id && !is_wp_error($img_id)) {
            set_post_thumbnail($post_id, $img_id);
        }
    }

    wp_send_json_success(['id' => $post_id, 'confirmed' => true]);
}

add_action('wp_ajax_alertaprecio_get_scraped_products','alertaprecio_get_scraped_products');
function alertaprecio_get_scraped_products() {
    if (!current_user_can('manage_woocommerce')) wp_send_json_error('No autorizado');
    $posts = get_posts([
        'post_type'=>'product',
        'posts_per_page'=>-1,
        'meta_key'=>'_idalertaprecio',
        'meta_value'=>'1',
        'fields'=>'ids',
    ]);
    $res=[];
    foreach($posts as $id){
        $res[]= [
            'id'=>$id,
            'title'=>get_the_title($id),
            'description'=>get_post_field('post_content',$id),
            'price'=>floatval(get_post_meta($id,'_price',true)),
            'scrapedPrice'=>floatval(get_post_meta($id,'_alertaprecio_price_scraped',true)),
            'currency'=>get_woocommerce_currency(),
            'image'=>get_the_post_thumbnail_url($id,'medium'),
            'markup'=>floatval(get_post_meta($id,'_alertaprecio_markup',true)),
            'monitoreable'=>get_post_meta($id,'_alertaprecio_monitoreable',true)==='1',
            'accepted'=>get_post_meta($id,'_alertaprecio_confirmed',true)==='1',
            'url'=>get_post_meta($id,'_urlscraper',true),
            'alertaprecioAutomaticaPrice'=>get_post_meta($id,'_alertaprecio_automatica_price',true)==='1',
            'threshold'=>floatval(get_post_meta($id,'_alertaprecio_threshold',true))?:80
        ];
    }
    wp_send_json_success($res);
}


/** ----- AJAX: MONITOREAR PRODUCTO ----- */
add_action( 'wp_ajax_alertaprecio_toggle_monitoring', 'alertaprecio_toggle_monitoring' );
function alertaprecio_toggle_monitoring() {
    check_ajax_referer( 'alertaprecio_nonce', '_ajax_nonce' );
    if ( ! current_user_can( 'manage_woocommerce' ) ) {
        wp_send_json_error( 'No autorizado' );
    }
    $pid     = alertaprecio_get_post_var('product_id', 'int');
    $monitor = alertaprecio_get_post_var('monitor', 'text');
    $monitor = in_array($monitor, [ '1', 'true', 1, true ], true ) ? '1' : '0';

    if ( ! $pid || get_post_type( $pid ) !== 'product' ) {
        wp_send_json_error( 'Producto inválido' );
    }

    update_post_meta( $pid, '_alertaprecio_monitoreable', $monitor );
    wp_send_json_success( [ 'monitor' => $monitor ] );
}
/** ----- AJAX: TOGGLE AUTO PRICE ----- */
add_action( 'wp_ajax_alertaprecio_toggle_auto_price', 'alertaprecio_toggle_auto_price' );
function alertaprecio_toggle_auto_price() {
    check_ajax_referer( 'alertaprecio_nonce', '_ajax_nonce' );
    $pid = alertaprecio_get_post_var('product_id', 'int');
    if ( ! $pid || get_post_type( $pid ) !== 'product' ) {
        wp_send_json_error( 'Producto inválido', 400 );
    }
    $mon = get_post_meta( $pid, '_alertaprecio_monitoreable', true );
    $conf = get_post_meta( $pid, '_alertaprecio_confirmed', true );
    if ( $mon !== '1' || $conf !== '1' ) {
        wp_send_json_error( 'Solo si está monitoreado y confirmado', 403 );
    }

    $current = get_post_meta( $pid, '_alertaprecio_automatica_price', true );
    $new     = ( $current === '1' ) ? '0' : '1';

    update_post_meta( $pid, '_alertaprecio_automatica_price', $new );
    wp_send_json_success( [ 'auto' => $new === '1' ] );
}

/** ----- AJAX: ASSIGN MARKUP ----- */
add_action( 'wp_ajax_alertaprecio_assign_markup', 'alertaprecio_assign_markup' );
function alertaprecio_assign_markup() {
    check_ajax_referer( 'alertaprecio_nonce', '_ajax_nonce' );
    $pid  = alertaprecio_get_post_var('product_id', 'int');
    $mark = alertaprecio_get_post_var('markup', 'float');

    if ( ! $pid || $mark < 0 ) {
        wp_send_json_error( 'Datos inválidos' );
    }
    if ( get_post_type( $pid ) !== 'product' ) {
        wp_send_json_error( 'Producto inválido' );
    }

    update_post_meta( $pid, '_alertaprecio_markup_percent', $mark );

    $base_raw = get_post_meta( $pid, '_alertaprecio_price_scraped', true );
    $base     = floatval( $base_raw );
    if ( ! $base ) {
        wp_send_json_error( 'Precio base no disponible' );
    }

    $new_price = round( $base * ( 1 + $mark / 100 ) );
    update_post_meta( $pid, '_regular_price', $new_price );
    update_post_meta( $pid, '_price', $new_price );

    wp_send_json_success( [
        'new_price'  => $new_price,
        'markup'     => $mark,
        'base_price' => $base,
    ] );
}

/** ----- AJAX: UPDATE MARKUP ----- */
add_action( 'wp_ajax_alertaprecio_update_markup', 'alertaprecio_update_markup' );
function alertaprecio_update_markup() {
    check_ajax_referer( 'alertaprecio_nonce', '_ajax_nonce' );
    $pid  = alertaprecio_get_post_var('product_id', 'int');
    $mark = alertaprecio_get_post_var('markup', 'float');

    if ( ! $pid || $mark < 0 ) {
        wp_send_json_error( 'Datos inválidos' );
    }
    update_post_meta( $pid, '_alertaprecio_markup', $mark );
    wp_send_json_success( 'Porcentaje actualizado' );
}

/** ----- AJAX: SET GLOBAL PRICE THRESHOLD ----- */
add_action( 'wp_ajax_alertaprecio_set_price_threshold', 'alertaprecio_set_price_threshold' );
function alertaprecio_set_price_threshold() {
    check_ajax_referer( 'alertaprecio_nonce', '_ajax_nonce' );
    $val = alertaprecio_get_post_var('threshold', 'float', 80);
    update_option( 'alertaprecio_price_threshold', $val );
    wp_send_json_success( true );
}

/** ----- AJAX: UPDATE PRODUCT THRESHOLD ----- */
add_action( 'wp_ajax_alertaprecio_update_threshold', 'alertaprecio_update_threshold' );
function alertaprecio_update_threshold() {
    check_ajax_referer( 'alertaprecio_nonce', '_ajax_nonce' );
    $pid = alertaprecio_get_post_var('product_id', 'int');
    $th  = alertaprecio_get_post_var('threshold', 'float');
    if ( ! $pid || $th < 0 || $th > 100 ) {
        wp_send_json_error( 'Datos inválidos' );
    }
    update_post_meta( $pid, '_alertaprecio_threshold', $th );
    wp_send_json_success( true );
}



add_action('init', function () {
    $next = wp_next_scheduled('alertaprecio_cron_check_prices');
    if ($next) {
        
    } else {
       
    }
});
add_action('admin_notices', function () {
    if (defined('DISABLE_WP_CRON') && DISABLE_WP_CRON) {
        echo '<div class="notice notice-error"><p>⚠️ El cron de WordPress está desactivado. Para que el monitoreo automático funcione, elimina <code>define(\'DISABLE_WP_CRON\', true);</code> de tu archivo <code>wp-config.php</code>.</p></div>';
    }
});

register_activation_hook(__FILE__,function(){
    if(!wp_next_scheduled('alertaprecio_cron_check_prices'))
        wp_schedule_event(time(), 'daily', 'alertaprecio_cron_check_prices');
});
register_deactivation_hook(__FILE__,function(){
    wp_clear_scheduled_hook('alertaprecio_cron_check_prices');
});

add_action('alertaprecio_cron_check_prices','alertaprecio_cron_check_prices');
function alertaprecio_cron_check_prices(){

  $apiToken    = get_option('alertaprecio_api_token',    '');
    $apiWebToken = get_option('alertaprecio_api_webtoken', '');

  $q = new WP_Query([
    'post_type'=>'product',
    'posts_per_page'=>-1,
    'post_status'=>'publish',
    'meta_query'=>[
      ['key'=>'_alertaprecio_monitoreable','value'=>'1'],
      ['key'=>'_alertaprecio_confirmed','value'=>'1'],
    ],
  ]);

  while($q->have_posts()){
    $q->the_post();
    $pid = get_the_ID();
    $url = get_post_meta($pid,'_urlscraper',true);
    if(!$url) continue;
    $headers = [
            'Content-Type'  => 'application/json',
            'x-api-key'   => $apiWebToken,
            'Authorization' => 'Bearer ' . $apiToken,
        ];

        $resp = wp_remote_post(
      'https://api.alertaprecio.online/products/woosearch',
      [
                'headers' => $headers,
        'body'    => wp_json_encode([
          'input'    => $url,
          'currency' => get_woocommerce_currency(),
        ]),
        'timeout' => 20,
      ]
    );

    if ( is_wp_error( $resp ) ) {
     
      continue;
    }

    $code = wp_remote_retrieve_response_code( $resp );
    $body = wp_remote_retrieve_body( $resp );

    $data = json_decode( $body, true );
    if ( empty($data['price']) || floatval($data['price']) <= 0 ) {
      continue;
    }

    $newp = floatval( $data['price'] );
    update_post_meta( $pid, '_alertaprecio_price_scraped', $newp );

    if ( get_post_meta($pid,'_alertaprecio_automatica_price',true) === '1' ) {
      $mark = floatval( get_post_meta($pid,'_alertaprecio_markup',true) );
      $fp = round( $newp * (1 + $mark/100) );
      update_post_meta( $pid, '_regular_price', $fp );
      update_post_meta( $pid, '_price', $fp );
    }
  }

  wp_reset_postdata();
  return true;
}

add_action('wp_ajax_alertaprecio_run_cron_now','alertaprecio_run_cron_now');
function alertaprecio_run_cron_now(){
    check_ajax_referer('alertaprecio_nonce','_ajax_nonce');
    if(!current_user_can('manage_woocommerce')) wp_send_json_error('No autorizado');
    alertaprecio_cron_check_prices();
    wp_send_json_success();
}

add_action('rest_api_init', function() {
    register_rest_route('alertaprecio/v1','/google-callback', [
        'methods'             => 'GET',
        'callback'            => 'alertaprecio_handle_google_callback',
        'permission_callback' => '__return_true',
    ]);
});
add_filter( 'rest_pre_serve_request', function( $served, $result, $request, $server ) {
    if ( $request->get_route() === '/alertaprecio/v1/google-callback' ) {
        header( 'Content-Type: text/html; charset=utf-8' );

        if ( is_wp_error( $result ) ) {
            echo '<p>' . esc_html( $result->get_error_message() ) . '</p>';
            exit;
        }

        if ( $result instanceof WP_REST_Response ) {
            $data = $result->get_data();

            if ( is_string( $data ) ) {
                   $allowed = wp_kses_allowed_html( 'post' );
                $allowed['script'] = [
                    'type'    => true,
                    'charset' => true,
                ];
                echo wp_kses( $data, $allowed );
                exit;
            }

            echo wp_json_encode( $data );
            exit;
        }

        if ( is_string( $result ) ) {
               $allowed = wp_kses_allowed_html( 'post' );
            $allowed['script'] = [
                'type'    => true,
                'charset' => true,
            ];
            echo wp_kses( $result, $allowed );
            exit;
        }

        echo esc_html( wp_json_encode( $result ) );
        exit;
    }

    return $served;
}, 10, 4 );

/**
 * wscraper_get_price_threshold
 */
add_action( 'wp_ajax_alertaprecio_get_price_threshold', 'alertaprecio_get_price_threshold' );
function alertaprecio_get_price_threshold() {
    check_ajax_referer( 'alertaprecio_nonce', '_ajax_nonce' );
    $val = get_option( 'alertaprecio_price_threshold', 80 );
    wp_send_json_success( $val );
}

function alertaprecio_handle_google_callback(WP_REST_Request $req) {
    $token    = sanitize_text_field($req->get_param('token'));
    $email    = sanitize_email($req->get_param('email'));
    $alerts   = intval($req->get_param('alerts'));
    $webtoken = sanitize_text_field($req->get_param('webtoken'));
    if (empty($token) || empty($email)) {
        return new WP_REST_Response('❌ Parámetros inválidos',400);
    }
    $expire = time() + DAY_IN_SECONDS;
    setcookie('alertaprecio_token',$token,$expire,'/wp-admin/',COOKIE_DOMAIN,is_ssl(),true);
    setcookie('alertaprecio_email',$email,$expire,'/wp-admin/',COOKIE_DOMAIN,is_ssl(),true);
    setcookie('alertaprecio_alerts',$alerts,$expire,'/wp-admin/',COOKIE_DOMAIN,is_ssl(),true);
    setcookie('alertaprecio_webtoken',$webtoken,$expire,'/wp-admin/',COOKIE_DOMAIN,is_ssl(),true);
      update_option('alertaprecio_api_token',    $token);
    update_option('alertaprecio_api_webtoken', $webtoken);
    $html = '<!DOCTYPE html><html lang="es"><head><meta charset="UTF-8"><title>Iniciando sesión...</title>
    <script>
      localStorage.setItem("alertaprecio_token",'.json_encode($token).');
      localStorage.setItem("alertaprecio_email",'.json_encode($email).');
      localStorage.setItem("alertaprecio_alerts",'.json_encode($alerts).');
      localStorage.setItem("alertaprecio_webtoken",'.json_encode($webtoken).');
      window.location.href='.json_encode(admin_url('admin.php?page=alertaprecio')).';
    </script></head><body><p>✅ Iniciando sesión... Redirigiendo.</p></body></html>';
    return new WP_REST_Response($html,200,['Content-Type'=>'text/html; charset=utf-8']);
}

register_activation_hook(__FILE__,function(){flush_rewrite_rules();});

function alertaprecio_calculate_enrich_score($post_id) {
    $score = 0;
    $post = get_post($post_id);
    if (!$post || $post->post_type !== 'product') {
        return 0;
    }
    $words = str_word_count(wp_strip_all_tags($post->post_title));
    if ($words >= 3) {
        $score += 2;
    }
    $desc_words = str_word_count(wp_strip_all_tags($post->post_content));
    if ($desc_words >= 100) {
        $score += 2;
    }
    if (has_excerpt($post_id)) {
        $score += 1;
    }
    if (get_post_thumbnail_id($post_id)) {
        $score += 2;
    }
    $gallery = get_post_meta($post_id,'_product_image_gallery',true);
    if ($gallery && count(explode(',',$gallery)) >= 3) {
        $score += 1;
    }
    $cats = wp_get_post_terms($post_id,'product_cat');
    if (count($cats) >= 1) {
        $score += 1;
    }
    $tags = wp_get_post_terms($post_id,'product_tag');
    if (count($tags) >= 1) {
        $score += 1;
    }
    $attributes = wc_get_product($post_id)->get_attributes();
    if (!empty($attributes)) {
        $score += 1;
    }
    return min(10, max(0, $score));
}
function alertaprecio_calculate_seo_score($post_id) {
    $score = 0;
    $post = get_post($post_id);
    if (!$post || $post->post_type !== 'product') return 0;

    $title   = $post->post_title ?? '';
    $slug    = $post->post_name ?? '';
    $content = wp_strip_all_tags($post->post_content ?? '');

    // 1. Meta descripción
    $meta_desc = get_post_meta($post_id, '_yoast_wpseo_metadesc', true) ?: get_post_meta($post_id, '_aioseo_description', true);
    $desc_len = mb_strlen($meta_desc);
    if ($desc_len >= 50 && $desc_len <= 160)        $score += 2;
    elseif ($desc_len >= 30 && $desc_len <= 200)    $score += 1;

    // 2. Slug amigable (más permisivo)
    $slug_words = count(explode('-', $slug));
    if ($slug_words <= 7) $score += 1;

    // 3. Slug aparece en título
    $slug_plain = str_replace('-', ' ', strtolower($slug));
    if (stripos(strtolower($title), $slug_plain) !== false) $score += 1;

    // 4. Título largo o con palabras clave típicas
    $title_words = preg_split('/[\s\-]+/', $title);
    if (count($title_words) >= 4) $score += 1;

    // 5. Enlaces en la descripción
    if (preg_match('/<a\s[^>]*href="https?:\/\/[^"]+"/i', $post->post_content)) {
        $score += 1;
    }

    // 6. Imágenes con texto ALT (solo 1 basta para sumar)
    $gallery = get_post_meta($post_id, '_product_image_gallery', true);
    $imgs = array_filter(explode(',', $gallery));
    $thumb_id = get_post_thumbnail_id($post_id);
    if ($thumb_id) array_unshift($imgs, $thumb_id);

    $alt_ok = 0;
    foreach ($imgs as $img_id) {
        $alt = get_post_meta($img_id, '_wp_attachment_image_alt', true);
        if (!empty($alt) && strlen($alt) >= 3) $alt_ok++;
    }
    if ($alt_ok >= 1) $score += 1;
    if ($alt_ok >= 3) $score += 1;

    // 7. Uso de keywords (1 uso suma, 3+ suma más)
    $keywords = get_post_meta($post_id, '_enrich_keywords', true);
    if ($keywords && is_string($keywords)) {
        $kw_array = explode(',', strtolower($keywords));
        $hits = 0;
        foreach ($kw_array as $kw) {
            if (stripos($content, trim($kw)) !== false) $hits++;
        }
        if ($hits >= 1) $score += 1;
        if ($hits >= 3) $score += 1;
    }

    // 8. Descripción larga (enriquecida ≥ 300 palabras)
    $word_count = str_word_count(wp_strip_all_tags($post->post_content));
    if ($word_count >= 300) $score += 1;

    // 9. Extracto personalizado (no generado automáticamente)
    $excerpt = $post->post_excerpt ?? '';
    if (!empty($excerpt) && strlen($excerpt) >= 50) $score += 1;

    return min(10, max(0, $score));
}



add_action('save_post_product', function($post_id) {
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
    if (!current_user_can('edit_post', $post_id)) return;
    $enr_score = alertaprecio_calculate_enrich_score($post_id);
    $seo_score = alertaprecio_calculate_seo_score($post_id);
    update_post_meta($post_id,'_enrich_score',$enr_score);
    update_post_meta($post_id,'_seo_score',$seo_score);
});

add_action('manage_product_posts_custom_column', function($col,$post_id) {
    switch ($col) {
        case 'enrich_score':
            $en = get_post_meta($post_id,'_enrich_score',true);
            if ($en===''||!is_numeric($en)) {
                $en = alertaprecio_calculate_enrich_score($post_id);
                update_post_meta($post_id,'_enrich_score',$en);
            }
            echo esc_html($en?:'-');
            break;
        case 'seo_score':
            $seo = get_post_meta($post_id,'_seo_score',true);
            if ($seo===''||!is_numeric($seo)) {
                $seo = alertaprecio_calculate_seo_score($post_id);
                update_post_meta($post_id,'_seo_score',$seo);
            }
            echo esc_html($seo?:'-');
            break;
        case '_urlscraper':
            $url = get_post_meta($post_id,'_urlscraper',true);
            if ($url) {
                echo '<a href="'.esc_url($url).'" target="_blank" style="color:#0073aa;">'.esc_html(wp_trim_words($url,6,'…')).'</a>';
            } else {
                echo '—';
            }
            break;
    }
},10,2);

add_action('wp_ajax_alertaprecio_update_enriched', 'alertaprecio_update_enriched');
function alertaprecio_update_enriched() {
    check_ajax_referer('alertaprecio_nonce','_ajax_nonce');
    if (!current_user_can('manage_woocommerce')) {
        wp_send_json_error('No autorizado');
    }

$data = alertaprecio_get_post_var('data', 'array', []);
if (!$data || empty($data['productId'])) {
    wp_send_json_error('Datos inválidos');
}

if (!$data || empty($data['productId'])) {
        wp_send_json_error('Datos inválidos');
    }
    $productId = (int) isset($_POST['data']['productId']) ? wp_unslash($_POST['data']['productId']) : null;
    if(!$productId) return null;
    $post_id = intval($productId);

    $product = wc_get_product($post_id);
    if (!$product) {
        wp_send_json_error('Producto no encontrado');
    }

    $update = ['ID' => $post_id];

    if (!empty($data['seo']['metaTitle'])) {
        $optimized_title = sanitize_text_field($data['seo']['metaTitle']);
        $update['post_title'] = $optimized_title;
        update_post_meta($post_id, '_yoast_wpseo_title', $optimized_title);
    } elseif (!empty($data['title'])) {
        $update['post_title'] = sanitize_text_field($data['title']);
    }

    // Descripción enriquecida con enlace interno si no existe
    if (!empty($data['enrichedDescription'])) {
        $content = sanitize_textarea_field($data['enrichedDescription']);
        $update['post_content'] = $content;

        if (!preg_match('/href="https?:\/\//i', $content)) {
            $cat = wp_get_post_terms($post_id, 'product_cat')[0]->slug ?? '';
            $internal_link = $cat ? home_url('/categoria-producto/' . $cat) : home_url();
            $update['post_content'] .= '<p><a href="' . esc_url($internal_link) . '">Descubre más productos relacionados</a></p>';
        }
    }

    // Meta descripción SEO (yoast o aioseo)
    if (!empty($data['seo']['metaDescription'])) {
        $meta_desc = sanitize_textarea_field($data['seo']['metaDescription']);
        update_post_meta($post_id, '_yoast_wpseo_metadesc', $meta_desc);
    }

    $current_meta = get_post_meta($post_id, '_yoast_wpseo_metadesc', true);
    if (empty($current_meta) || mb_strlen($current_meta) < 50) {
        $auto_desc = wp_trim_words(wp_strip_all_tags($update['post_content'] ?? ''), 30, '...');
        update_post_meta($post_id, '_yoast_wpseo_metadesc', $auto_desc);
    }

    // Short description
    if (!empty($data['shortDescription'])) {
        $update['post_excerpt'] = sanitize_textarea_field($data['shortDescription']);
    } else {
        $update['post_excerpt'] = wp_trim_words($update['post_content'] ?? '', 25, '...');
    }

    wp_update_post($update);

    // Palabras clave SEO y etiquetas
    $keywords = !empty($data['seo']['keywords'])
        ? array_map('sanitize_text_field', $data['seo']['keywords'])
        : array_filter(array_slice(preg_split('/[\s\-]+/', strtolower($update['post_title'] ?? '')), 0, 5), fn($k) => strlen($k) > 3);

    if (!empty($keywords)) {
        update_post_meta($post_id, '_enrich_keywords', implode(',', $keywords));
        wp_set_post_terms($post_id, $keywords, 'product_tag', true);
    }

    // Marca y color como atributos
    if (!empty($data['brand'])) {
        $brand = sanitize_text_field($data['brand']);
        wp_set_object_terms($post_id, $brand, 'pa_brand', true);
        update_post_meta($post_id, '_product_brand', $brand);
    }

    if (!empty($data['color'])) {
        $color = sanitize_text_field($data['color']);
        wp_set_object_terms($post_id, $color, 'pa_color', true);
        update_post_meta($post_id, '_product_color', $color);
    }

    // Peso y dimensiones
    if (isset($data['weightKg'])) {
        $product->set_weight(floatval($data['weightKg']));
    }

    if (!empty($data['dimensions']) && is_array($data['dimensions'])) {
        $product->set_length(floatval($data['dimensions']['length'] ?? 0));
        $product->set_width(floatval($data['dimensions']['width'] ?? 0));
        $product->set_height(floatval($data['dimensions']['height'] ?? 0));
    }

    // Imágenes y ALT optimizado
    $gallery_ids = [];
    if (!empty($data['images']) && is_array($data['images'])) {
        foreach ($data['images'] as $index => $img_url) {
            if ($index >= 5) break;
            $att_id = alertaprecio_attach_external_image($img_url, $post_id);
            if (!is_wp_error($att_id) && $att_id) {
                update_post_meta($att_id, '_wp_attachment_image_alt', $update['post_title'] ?? 'Imagen del producto');
                if ($index === 0) {
                    set_post_thumbnail($post_id, $att_id);
                } else {
                    $gallery_ids[] = $att_id;
                }
            }
        }
    }

    // Si no hay imagen destacada, usar placeholder
    if (!has_post_thumbnail($post_id)) {
        $placeholder_url = plugins_url('assets/notfound.png', __FILE__);
        $att_id = alertaprecio_attach_external_image($placeholder_url, $post_id);
        if (!is_wp_error($att_id)) {
            set_post_thumbnail($post_id, $att_id);
            update_post_meta($att_id, '_wp_attachment_image_alt', $update['post_title'] ?? 'Imagen por defecto');
        }
    }

    if (!empty($gallery_ids)) {
        update_post_meta($post_id, '_product_image_gallery', implode(',', $gallery_ids));
    }

    $product->save();

    // Puntuaciones enriquecidas
    $seo_score = alertaprecio_calculate_seo_score($post_id);
    $enrich_score = alertaprecio_calculate_enrich_score($post_id);
    update_post_meta($post_id, '_seo_score', $seo_score);
    update_post_meta($post_id, '_enrich_score', $enrich_score);

    wp_send_json_success([
        'seo_score' => $seo_score,
        'enrich_score' => $enrich_score
    ]);
}

/** ----- AJAX: UPDATE PRODUCT PRICE ----- */
add_action('wp_ajax_alertaprecio_update_product_price', 'alertaprecio_update_product_price');
function alertaprecio_update_product_price() {
    check_ajax_referer('alertaprecio_nonce', '_ajax_nonce');

    if (!current_user_can('manage_woocommerce')) {
        wp_send_json_error('No autorizado', 403);
    }

    $data = alertaprecio_get_post_var('data', 'array', []);
    if (!$data || empty($data['wooProductId']) || !isset($data['price'])) {
        wp_send_json_error('Datos inválidos', 400);
    }

    $post_id = intval($data['wooProductId']);
    if (get_post_type($post_id) !== 'product') {
        wp_send_json_error('Producto no encontrado', 404);
    }

    $new_price   = floatval($data['price']);
    $markup      = isset($data['markup']) ? floatval($data['markup']) : get_post_meta($post_id, '_alertaprecio_markup', true);
    $scraped     = isset($data['priceScraped']) ? floatval($data['priceScraped']) : get_post_meta($post_id, '_alertaprecio_price_scraped', true);
    $threshold   = isset($data['threshold']) ? floatval($data['threshold']) : get_post_meta($post_id, '_alertaprecio_threshold', true);

    update_post_meta($post_id, '_regular_price', $new_price);
    update_post_meta($post_id, '_price', $new_price);

    // Marca como confirmado
    update_post_meta($post_id, '_alertaprecio_confirmed', '1');

    // Actualiza metadatos adicionales si son enviados
    update_post_meta($post_id, '_alertaprecio_markup', $markup);
    update_post_meta($post_id, '_alertaprecio_price_scraped', $scraped);
    update_post_meta($post_id, '_alertaprecio_threshold', $threshold);

    wp_send_json_success([
        'id' => $post_id,
        'new_price' => $new_price,
        'confirmed' => true
    ]);
}

add_action('wp_ajax_alertaprecio_logout','alertaprecio_logout');
function alertaprecio_logout(){
    check_ajax_referer('alertaprecio_nonce','_ajax_nonce');

    $expire     = time() - 3600;  // hace que caduquen inmediatamente
    $secure     = is_ssl();
    $httpOnly   = true;
    $cookiePath = '/wp-admin/';
    $cookieDomain = COOKIE_DOMAIN;

    // Caducamos las mismas cookies que creaste al inicio
    setcookie('alertaprecio_token',    '', $expire, $cookiePath, $cookieDomain, $secure, $httpOnly);
    setcookie('alertaprecio_email',    '', $expire, $cookiePath, $cookieDomain, $secure, $httpOnly);
    setcookie('alertaprecio_alerts',   '', $expire, $cookiePath, $cookieDomain, $secure, $httpOnly);
    setcookie('alertaprecio_webtoken', '', $expire, $cookiePath, $cookieDomain, $secure, $httpOnly);

    wp_send_json_success();
}

// 1) Define tu tarea diaria (si ya la tienes, salta este paso)
add_action( 'alertaprecio_daily_scrape', 'alertaprecio_daily_scrape_callback' );
function alertaprecio_daily_scrape_callback() {
   alertaprecio_cron_check_prices();
}

// 2) En cada visita front-end, comprueba si ya la corriste hoy y si es ≥ 11 h
function alertaprecio_maybe_run_daily_scrape() {
    $current_hour = intval( gmdate( 'G' ) );
    $today = gmdate( 'Y-m-d' );
    $last_run = get_option( 'alertaprecio_dayscraped_date', '' );

    if ( $current_hour >= 11 && $last_run !== $today ) {
        do_action( 'alertaprecio_daily_scrape' );
        update_option( 'alertaprecio_dayscraped_date', $today );
    }
}
add_action( 'wp', 'alertaprecio_maybe_run_daily_scrape' );
