<?php defined('BASEPATH') or exit('No direct script access allowed');
/**
 * Boot Top 10 — posiciona o widget LOGO APÓS a saudação (ex.: "Bom Dia ...")
 * independentemente do tema. Renderiza no footer e reposiciona via JS.
 */

// Esconde apenas ícone de menu do cliente e pequenas margens
hooks()->add_action('app_customers_head', function () {
    echo '<style>
      .customers.navigation .icon-qrassociados,
      .customers .navbar .icon-qrassociados {display:none!important}
      #qrassoc-top10-card{margin:24px 0}
    </style>';
});

if (!function_exists('qrassoc_view_include')) {
    function qrassoc_view_include($rel, $vars = [])
    {
        $abs = __DIR__ . '/views/' . $rel . '.php';
        if (!file_exists($abs) && function_exists('module_dir_path')) {
            $alt = module_dir_path('qrassociados', 'views/' . $rel . '.php');
            if ($alt && file_exists($alt)) $abs = $alt;
        }
        if (file_exists($abs)) {
            if (is_array($vars)) extract($vars, EXTR_SKIP);
            ob_start(); include $abs; echo ob_get_clean();
        }
    }
}

if (!function_exists('qrassoc_render_top10_once')) {
    function qrassoc_render_top10_once()
    {
        static $done = false;
        if ($done) return;
        $done = true;

        if (!defined('QRASSOC_TOP10_RENDERED')) {
            define('QRASSOC_TOP10_RENDERED', true);
        }

        if (!is_client_logged_in()) return;

        $CI =& get_instance();

        // --- Guard: render ONLY on client dashboard (home) ---
$class  = isset($CI->router->class)  ? strtolower($CI->router->class)  : '';
$method = isset($CI->router->method) ? strtolower($CI->router->method) : '';
$seg1   = strtolower($CI->uri->segment(1) ?? '');
$seg2   = strtolower($CI->uri->segment(2) ?? '');
$uri    = trim($CI->uri->uri_string(), '/');
$is_dashboard = false;
if ($class === 'clients' && in_array($method, ['','index','home','dashboard'], true)) { $is_dashboard = true; }
if (in_array($seg1, ['clients','customers'], true) && in_array($seg2, ['', 'index', 'home', 'dashboard'], true)) { $is_dashboard = true; }
if (in_array($uri, ['clients','customers'], true)) { $is_dashboard = true; }
if (!$is_dashboard) { return; }
// --- end guard ---

        $prefix       = db_prefix();
        $hitsTable    = $prefix.'qrassociados_hits';
        $clientsTable = $prefix.'clients';

        $fk = null;
        if ($CI->db->field_exists('client_id', $hitsTable))    $fk = 'client_id';
        elseif ($CI->db->field_exists('customer_id', $hitsTable)) $fk = 'customer_id';

        $dtcol = null;
        if ($CI->db->field_exists('created_at', $hitsTable)) $dtcol = 'created_at';
        elseif ($CI->db->field_exists('date', $hitsTable))   $dtcol = 'date';

        // coleta
        $top = []; $me = null;
        if ($fk) {
            $CI->db->select('c.userid as client_id, c.company as client_name, COUNT(h.id) as hits', false);
            $CI->db->from($hitsTable.' h');
            $CI->db->join($clientsTable.' c', 'c.userid = h.'.$fk, 'left');
            if ($dtcol) $CI->db->where('DATE(h.'.$dtcol.') >=', date('Y-m-d', strtotime('-30 days')));
            $CI->db->group_by('c.userid');
            $CI->db->order_by('hits', 'DESC');
            $CI->db->limit(10);
            $top = $CI->db->get()->result_array();

            if (function_exists('get_client_user_id')) {
                $myId = get_client_user_id();
                $pos = 1;
                foreach ($top as $row) {
                    if ((int)$row['client_id'] === (int)$myId) {
                        $me = ['position'=>$pos, 'hits'=>(int)$row['hits']];
                        break;
                    }
                    $pos++;
                }
            }
        }

        // wrapper + view
        echo '<div id="qrassoc-top10-card" class="panel_s">';
        qrassoc_view_include('client/widget_top10', ['top'=>$top, 'me'=>$me]);
        echo '</div>';

        // Script: posiciona LOGO APÓS a saudação (h1..h4 / page-title / page-heading).
        echo '<script>
        (function(){
          function findGreeting(container){
            if(!container) return null;
            var sels = "h1,h2,h3,h4,.page-title,.page-heading,.greeting,.customer-greeting";
            var nodes = container.querySelectorAll(sels);
            if(!nodes || !nodes.length) return null;
            var guess = nodes[0];
            for (var i=0;i<nodes.length;i++){
              var el = nodes[i];
              var txt = (el.textContent || "").trim().toLowerCase();
              if (!txt) continue;
              if (txt.includes("bom dia") || txt.includes("boa tarde") || txt.includes("boa noite")
                  || txt.includes("bem-vindo") || txt.includes("bem vindo") || txt.indexOf("olá")===0 || txt.indexOf("ola")===0){
                return el;
              }
            }
            return guess;
          }
          function insertAfter(newNode, referenceNode){
            if (!referenceNode || !referenceNode.parentNode) return false;
            if (referenceNode.nextSibling){
              referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
            } else {
              referenceNode.parentNode.appendChild(newNode);
            }
            return true;
          }
          function moveCard(){
            var card = document.getElementById("qrassoc-top10-card");
            if(!card) return;
            var content = document.querySelector(".customers .content, .content-wrapper, .content, main, #content");
            var footer  = document.querySelector("footer, .footer, #footer");
            var placed = false;
            if (content){
              var greet = findGreeting(content);
              if (greet){
                 placed = insertAfter(card, greet);
              }
              if (!placed){
                 // não encontrou saudação – põe no topo do conteúdo
                 content.insertBefore(card, content.firstChild);
                 placed = true;
              }
            }
            if (!placed && footer && footer.parentNode){
              footer.parentNode.insertBefore(card, footer); // último recurso: antes do footer
            }
          }
          if (document.readyState !== "loading") moveCard();
          else document.addEventListener("DOMContentLoaded", moveCard);
          window.addEventListener("load", moveCard);
        })();
        </script>';
    }
}

// Apenas um hook: renderiza no footer e move para o lugar correto.
hooks()->add_action("app_customers_footer", function () {
    qrassoc_render_top10_once();
}, 1);
