<?php

// Tạo metabox
add_action('add_meta_boxes', function () {
  add_meta_box('video_meta_box', 'Thông Tin Video', 'render_video_meta_box', ['post'], 'normal', 'high');
});

function render_video_meta_box($post)
{
  $meta = get_post_meta($post->ID);

  $is_hot = !empty($meta['video_hot'][0]);
  $label = esc_attr($meta['video_label'][0] ?? '');
  $duration = esc_attr($meta['video_duration'][0] ?? '');
  $servers = isset($meta['video_servers'][0]) ? json_decode($meta['video_servers'][0], true) : [];

  wp_nonce_field('save_video_meta', 'video_meta_nonce');

  echo '<p><label><input type="checkbox" name="video_hot" ' . checked($is_hot, true, false) . '> Video HOT</label></p>';
  echo '<p><label>Label:</label><br><input type="text" name="video_label" value="' . $label . '" style="width:100%"></p>';
  echo '<p><label>Thời lượng (hh:mm:ss):</label><br><input type="text" name="video_duration" value="' . $duration . '" pattern="\d{2}:\d{2}:\d{2}" placeholder="01:30:00" style="width:100%"></p>';

  echo '<div id="server-repeater">';
  if (!empty($servers)) {
    foreach ($servers as $index => $server) {
      render_server_group($server, $index);
    }
    $last_index = array_key_last($servers);
  } else {
    render_server_group([], 0);
    $last_index = 0;
  }
  echo '</div>';
  echo '<button type="button" class="button" onclick="addServerGroup()">+ Thêm Server</button>';

  echo <<<HTML
<script>
let serverIndex = {$last_index};

function addServerGroup() {
  serverIndex++;
  const wrapper = document.getElementById('server-repeater');
  const html = `
    <div class="server-group" style="border:1px solid #ccc;padding:10px;margin-bottom:10px">
      <p><label>Tên Server:</label><br>
      <input type="text" name="servers[\${serverIndex}][name]" style="width:100%"></p>
      <p><label>Video URL:</label><br>
      <input type="url" name="servers[\${serverIndex}][url]" style="width:100%"></p>
      <p><label>Định dạng:</label><br>
      <select name="servers[\${serverIndex}][format]" style="width:100%">
        <option value="">Chọn định dạng</option>
        <option value="embed">Embed</option>
        <option value="mp4">MP4</option>
        <option value="m3u8">M3U8</option>
        <option value="mov">MOV</option>
        <option value="avi">AVI</option>
        <option value="webm">WEBM</option>
      </select></p>
      <p><button type="button" class="button" onclick="this.closest('.server-group').remove()">Xoá</button></p>
    </div>`;
  wrapper.insertAdjacentHTML('beforeend', html);
}
</script>
HTML;
}

// Hàm render 1 server block
function render_server_group($server, $index)
{
  $name = esc_attr($server['name'] ?? '');
  $url = esc_attr($server['url'] ?? '');
  $format = esc_attr($server['format'] ?? '');

  echo '<div class="server-group" style="border:1px solid #ccc;padding:10px;margin-bottom:10px">';
  echo '<p><label>Tên Server:</label><br>';
  echo "<input type='text' name='servers[{$index}][name]' value='{$name}' style='width:100%'></p>";
  echo '<p><label>Video URL:</label><br>';
  echo "<input type='url' name='servers[{$index}][url]' value='{$url}' style='width:100%'></p>";
  echo '<p><label>Định dạng:</label><br>';
  echo "<select name='servers[{$index}][format]' style='width:100%'>";
  echo "<option value=''>Chọn định dạng</option>";
  foreach (['embed', 'mp4', 'm3u8', 'mov', 'avi', 'webm'] as $f) {
    echo "<option value='{$f}' " . selected($format, $f, false) . ">" . strtoupper($f) . "</option>";
  }
  echo "</select></p>";
  echo '<p><button type="button" class="button" onclick="this.closest(\'.server-group\').remove()">Xoá</button></p>';
  echo '</div>';
}

// Lưu metabox
add_action('save_post', function ($post_id) {
  if (!isset($_POST['video_meta_nonce']) || !wp_verify_nonce($_POST['video_meta_nonce'], 'save_video_meta')) return;
  if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;

  update_post_meta($post_id, 'video_hot', isset($_POST['video_hot']));
  update_post_meta($post_id, 'video_label', sanitize_text_field($_POST['video_label'] ?? ''));
  update_post_meta($post_id, 'video_duration', sanitize_text_field($_POST['video_duration'] ?? ''));

  $servers = $_POST['servers'] ?? [];
  $clean_servers = [];

  foreach ($servers as $s) {
    $clean_servers[] = [
      'name' => sanitize_text_field($s['name'] ?? ''),
      'url' => esc_url_raw($s['url'] ?? ''),
      'format' => sanitize_text_field($s['format'] ?? ''),
    ];
  }

  update_post_meta($post_id, 'video_servers', wp_json_encode($clean_servers));
});


function easy3x_lazy_thumb($post_id = null, $size = 'thumb-16x9', $attrs = [])
{
  $post_id = $post_id ?: get_the_ID();
  $thumb_url = get_the_post_thumbnail_url($post_id, $size);

  if (!$thumb_url) {
    $thumb_url = 'https://raw.githubusercontent.com/julien-gargot/images-placeholder/refs/heads/master/placeholder-L1.png';
  }

  $defaults = [
    'class'  => 'lazy-img blur-up',
    'width'  => '320',
    'height' => '180',
    'alt'    => esc_attr(get_the_title($post_id)),
  ];

  $attrs = array_merge($defaults, $attrs);

  $html = '<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMBgG52TxsAAAAASUVORK5CYII="';
  $html .= ' data-src="' . esc_url($thumb_url) . '"';

  foreach ($attrs as $key => $value) {
    $html .= ' ' . esc_attr($key) . '="' . esc_attr($value) . '"';
  }

  $html .= ' />';

  return $html;
}


/*add_action('init', function () {
  add_rewrite_rule('^search/([^/]+)/?$', 'index.php?s=$matches[1]', 'top');
});

add_filter('search_link', function ($url, $query) {
  return home_url('/search/' . urlencode($query) . '/');
}, 10, 2);

// Tạo endpoint /search và gán template riêng
add_action('init', function () {
  add_rewrite_rule('^search/?$', 'index.php?custom_search_page=1', 'top');
});

add_filter('query_vars', function ($vars) {
  $vars[] = 'custom_search_page';
  return $vars;
});

add_action('template_redirect', function () {
  if (get_query_var('custom_search_page') == 1) {
    // Load template riêng tại /pages/search.php
    include get_template_directory() . '/pages/search.php';
    exit;
  }
});

*/
//

// Xoá /category/ khỏi URL chuyên mục
/*add_filter('category_rewrite_rules', function($rules) {
  $categories = get_categories(['hide_empty' => false]);
  $new_rules = [];

  foreach ($categories as $cat) {
    $slug = $cat->slug;
    if ($cat->parent == 0) {
      $new_rules[$slug . '/?$'] = 'index.php?category_name=' . $slug;
      $new_rules[$slug . '/page/([0-9]{1,})/?$'] = 'index.php?category_name=' . $slug . '&paged=$matches[1]';
    }
  }

  return $new_rules + $rules;
});

// Xoá category base trong permalink
add_filter('request', function($query) {
  if (!empty($query['category_name'])) {
    $slug = $query['category_name'];
    $cat = get_category_by_slug($slug);
    if ($cat && $cat->slug === $slug) {
      $query['category_name'] = $cat->slug;
    }
  }
  return $query;
});

// Redirect /category/slug → /slug
add_action('template_redirect', function() {
  if (is_category()) {
    $term = get_queried_object();
    if ($term && !is_wp_error($term)) {
      $canonical = home_url($term->slug . '/');
      if (trailingslashit($_SERVER['REQUEST_URI']) !== trailingslashit(parse_url($canonical, PHP_URL_PATH))) {
        wp_redirect($canonical, 301);
        exit;
      }
    }
  }
});


//*/

function easy3x_count_video_view()
{
  if (!is_singular('post')) return;

  $post_id = get_the_ID();
  $ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
  $key = 'viewed_' . md5($ip . '_' . $post_id);
  $timeout = 24 * HOUR_IN_SECONDS;

  if (!isset($_COOKIE[$key])) {
    // Tăng số view
    $views = (int) get_post_meta($post_id, 'video_view', true);
    update_post_meta($post_id, 'video_view', $views + 1);

    // Set cookie để giới hạn 24h
    setcookie($key, '1', time() + $timeout, COOKIEPATH, COOKIE_DOMAIN, is_ssl(), true);
    $_COOKIE[$key] = '1'; // Phòng cache set chậm
  }
}
add_action('wp', 'easy3x_count_video_view');

//

// Chèn code vào <head> không lọc <script>
add_action('wp_head', function () {
  $custom_head = get_theme_mod('custom_head_code');
  if (!empty($custom_head)) {
    echo force_balance_tags($custom_head);
  }
}, 99);

// Chèn code trước </body> không lọc <script>
add_action('wp_footer', function () {
  $custom_footer = get_theme_mod('custom_footer_code');
  if (!empty($custom_footer)) {
    echo force_balance_tags($custom_footer);
  }
}, 99);


add_action('wp_head', function () {
  $variables = [
    '--color-primary'     => get_theme_mod('color_primary'),
    '--color-accent'      => get_theme_mod('color_accent'),
    '--color-highlight'   => get_theme_mod('color_highlight'),
    '--color-dark'        => get_theme_mod('color_dark'),
    '--color-text'        => get_theme_mod('color_text'),
    '--color-muted'       => get_theme_mod('color_muted'),
    '--font-size-base'    => get_theme_mod('font_size_base') . 'rem',
    '--font-weight-base'  => get_theme_mod('font_weight_base'),
  ];

  echo '<style>:root{';
  foreach ($variables as $var => $val) {
    if (!empty($val)) {
      echo $var . ':' . esc_attr($val) . ';';
    }
  }
  echo '}</style>';
}, 20);


// Đăng ký taxonomy tùy chỉnh "Search"
add_action('init', function () {
  $labels = [
    'name'              => 'Search',
    'singular_name'     => 'Search Term',
    'search_items'      => 'Tìm kiếm Search Terms',
    'all_items'         => 'Tất cả Search Terms',
    'edit_item'         => 'Chỉnh sửa Search Term',
    'update_item'       => 'Cập nhật Search Term',
    'add_new_item'      => 'Thêm Search Term mới',
    'new_item_name'     => 'Tên Search Term mới',
    'menu_name'         => 'Search'
  ];

  register_taxonomy('search', ['post'], [
    'labels'            => $labels,
    'hierarchical'      => false,
    'public'            => true,
    'show_ui'           => true,
    'show_admin_column' => true,
    'query_var'         => true,
    'rewrite'           => ['slug' => 'search'],
    'show_in_rest'      => true, // Hỗ trợ Gutenberg và API
  ]);
});

// Thêm trường tùy chỉnh "Keywords" cho taxonomy "Search"
add_action('search_add_form_fields', function () {
?>
  <div class="form-field">
    <label for="search_keywords">Keywords (cách nhau bởi dấu phẩy)</label>
    <input type="text" name="search_keywords" id="search_keywords" value="" placeholder="keyword1, keyword2, keyword3" />
    <p class="description">Nhập các keywords, cách nhau bằng dấu phẩy. Mỗi keyword sẽ được lưu thành slug SEO-friendly.</p>
  </div>
<?php
});

add_action('search_edit_form_fields', function ($term) {
  $keywords = get_term_meta($term->term_id, 'search_keywords', true);
?>
  <tr class="form-field">
    <th scope="row"><label for="search_keywords">Keywords (cách nhau bởi dấu phẩy)</label></th>
    <td>
      <input type="text" name="search_keywords" id="search_keywords" value="<?php echo esc_attr($keywords); ?>" placeholder="keyword1, keyword2, keyword3" />
      <p class="description">Nhập các keywords, cách nhau bằng dấu phẩy. Mỗi keyword sẽ được lưu thành slug SEO-friendly.</p>
    </td>
  </tr>
<?php
});

// Lưu trường "Keywords"
add_action('created_search', 'save_search_keywords');
add_action('edited_search', 'save_search_keywords');
function save_search_keywords($term_id)
{
  if (isset($_POST['search_keywords'])) {
    $keywords = sanitize_text_field($_POST['search_keywords']);
    update_term_meta($term_id, 'search_keywords', $keywords);

    // Tự động tạo slug chuẩn cho từng keyword (nếu cần)
    $keyword_array = array_filter(array_map('trim', explode(',', $keywords)));
    $slugs = array_map('sanitize_title', $keyword_array);
    update_term_meta($term_id, 'search_keywords_slugs', $slugs);
  }
}





// Đăng ký endpoint /search/
function vippro_register_search_endpoint()
{
  add_rewrite_rule('^search/?$', 'index.php?vippro_search=1', 'top');
}
add_action('init', 'vippro_register_search_endpoint');

// Đăng ký query var
function vippro_add_query_vars($vars)
{
  $vars[] = 'vippro_search';
  return $vars;
}
add_filter('query_vars', 'vippro_add_query_vars');

// Load template pages/search.php khi truy cập /search/
function vippro_template_redirect()
{
  if (get_query_var('vippro_search') == 1) {
    $template = get_stylesheet_directory() . '/pages/search.php';
    if (file_exists($template)) {
      include $template;
      exit;
    } else {
      // fallback: load search.php mặc định
      include get_query_template('search');
      exit;
    }
  }
}
add_action('template_redirect', 'vippro_template_redirect');



// Đổi tên post mặc định thành "Videos"
add_action('init', 'rename_post_type_to_videos');
function rename_post_type_to_videos()
{
  global $wp_post_types;

  if (isset($wp_post_types['post'])) {
    $labels = &$wp_post_types['post']->labels;

    $labels->name               = 'Videos';
    $labels->singular_name      = 'Video';
    $labels->add_new            = 'Thêm Video Mới';
    $labels->add_new_item       = 'Thêm Video Mới';
    $labels->edit_item          = 'Sửa Video';
    $labels->new_item           = 'Video Mới';
    $labels->view_item          = 'Video Mới';
    $labels->search_items       = 'Tìm Kiếm Video';
    $labels->not_found          = 'Không Thấy Video';
    $labels->not_found_in_trash = 'Ko Thấy Video Trong Thùng Rác';
    $labels->all_items          = 'Tất Cả Videos';
    $labels->menu_name          = 'Videos';
    $labels->name_admin_bar     = 'Video';

    // Optional: đổi icon và vị trí trong menu
    $wp_post_types['post']->menu_icon = 'dashicons-video-alt3';
    $wp_post_types['post']->menu_position = 5;
  }
}


function easy3x_show_ad($size = '728x90')
{
  // Kiểm tra nếu chưa bật quảng cáo này thì không hiển thị
  if (! get_theme_mod("easy3x_ad_enable_{$size}", false)) {
    return;
  }

  // Lấy code từ customizer
  $code = get_theme_mod("easy3x_ad_{$size}");

  if (! empty($code)) {
    echo '<div class="ad-container" aria-label="advertisement" role="complementary">';
    echo $code; // cho phép HTML/JS user nhập
    echo '</div>';
  }
}
