<?php
defined('BASEPATH') or exit('No direct script access allowed');

/*
Module Name: QR Associados
Description: Rastreamento de acessos via QR Code para clientes (admin e portal) com ranking e estatísticas. QR local com phpqrcode.
Version: 1.1.7
Requires at least: 3.3.1
Author: NDMidia
Author URI: https://ndmidia.com.br
*/

define('QRASSOCIADOS_MODULE_NAME', 'qrassociados');

register_activation_hook(QRASSOCIADOS_MODULE_NAME, 'qrassociados_activation_hook');
function qrassociados_activation_hook()
{
    $CI =& get_instance();
    // Ensure folders
    $path = FCPATH . 'modules/qrassociados/uploads/clients';
    if (!is_dir($path)) {
        @mkdir($path, 0755, true);
    }
    // Tables
    $CI->db->query("CREATE TABLE IF NOT EXISTS `qrassociados_settings` (
        `id` INT AUTO_INCREMENT PRIMARY KEY,
        `client_id` INT NOT NULL UNIQUE,
        `destination_url` VARCHAR(512) NULL,
        `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
        `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        INDEX (`client_id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");

    $CI->db->query("CREATE TABLE IF NOT EXISTS `qrassociados_hits` (
        `id` BIGINT AUTO_INCREMENT PRIMARY KEY,
        `client_id` INT NOT NULL,
        `ip` VARCHAR(64) NULL,
        `user_agent` TEXT NULL,
        `referrer` VARCHAR(1024) NULL,
        `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
        INDEX (`client_id`),
        INDEX (`created_at`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
}

// Admin sidebar menu: QR Associados
hooks()->add_action('admin_init', 'qrassociados_admin_menu');
function qrassociados_admin_menu()
{
    $CI = &get_instance();
    if (isset($CI->app_menu)) {
        $CI->app_menu->add_sidebar_menu_item('qrassociados', [
            'name'     => 'QR Associados',
            'href'     => admin_url('qrassociados'),
            'icon'     => 'fa fa-qrcode',
            'position' => 30,
        ]);
    }
}

// Customer profile tab: provide a 'view' so core loads directly
hooks()->add_filter('customer_profile_tabs', 'qrassociados_add_customer_tab', 10, 1);
function qrassociados_add_customer_tab($tabs)
{
    $tabs[] = [
        'slug'     => 'qrassociados_tab',
        'name'     => 'QR Code & Estatísticas',
        'icon'     => 'fa fa-qrcode',
        'view'     => 'qrassociados/admin/customer_tab_wrapper',
        'position' => 50,
    ];
    return $tabs;
}

// Client portal menu
hooks()->add_action('clients_init', 'qrassociados_add_client_menu');
function qrassociados_add_client_menu()
{
    if (!is_client_logged_in()) {
        return;
    }
    add_theme_menu_item('qrassociados-my-qr', [
        'name'     => 'Meu QR Code',
        'href'     => site_url('qrassociados/client_qr/my_qr'),
        'icon'     => 'fa fa-qrcode',
        'position' => 15,
    ]);
}


/* Hide icon only for client menu item */
hooks()->add_action('app_customers_head', function(){
    echo '<style>#side-menu a[href*="qrassociados/client_qr/my_qr"] i{display:none!important}</style>';
});


// Hide only the icon for the client "Meu QR Code" menu item
hooks()->add_action('app_customers_head', function () {
    echo '<style>
      #side-menu a[href*="qrassociados"] i,
      .navbar-right a[href*="qrassociados"] i{display:none!important}
    </style>';
});



// Gamification: Top 10 most-read QR codes (last 30 days) in the client's dashboard
hooks()->add_action('customers_after_dashboard_content', function () {
    if (!is_client_logged_in()) { return; }
    $CI =& get_instance();
    $prefix = db_prefix();
    $hitsTable = $prefix.'qrassociados_hits';
    $clientsTable = $prefix.'clients';

    // Find likely FK/date columns
    $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';

    if (!$fk) { return; }

    $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();

    $me = null;
    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++;
        }
    }

    if (!defined('QRASSOC_TOP10_RENDERED')) { define('QRASSOC_TOP10_RENDERED', true); qrassociados_render_view('client/widget_top10', ['top'=>$top, 'me'=>$me]); }
});



// Fallback: render Top 10 widget at client footer on dashboard routes
hooks()->add_action('app_customers_footer', function () {
    if (!is_client_logged_in()) { return; }
    $CI =& get_instance();
    // Try to detect client's home/dashboard
    $class  = isset($CI->router->class) ? $CI->router->class : '';
    $method = isset($CI->router->method) ? $CI->router->method : '';
    $uri    = method_exists($CI->uri,'uri_string') ? $CI->uri->uri_string() : '';

    $is_dashboard = ($class === 'clients' || $class === 'home' || $uri === '' || $uri === 'clients' || $uri === 'clients/home');
    if (!$is_dashboard) { return; }

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

    // Columns detection
    $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';

    if (!$fk) { return; }

    $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();

    $me = null;
    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++;
        }
    }

    if (!defined('QRASSOC_TOP10_RENDERED')) { define('QRASSOC_TOP10_RENDERED', true); qrassociados_render_view('client/widget_top10', ['top'=>$top, 'me'=>$me]); }
});


// Safe renderer for module views (works with themes/paths and as absolute include fallback)
if (!function_exists('qrassociados_render_view')) {
    // Renderizador sem Loader: carrega a view por include direto.
    function qrassociados_render_view($rel, $vars = [])
    {
            // Guarda global para evitar duplicidade do widget Top 10
    if ($rel === 'client/widget_top10') {
        if (defined('QRASSOC_TOP10_RENDERED')) { return; }
        define('QRASSOC_TOP10_RENDERED', true);
    }
// Caminho base: modules/qrassociados/views/<rel>.php
        $abs = __DIR__ . '/views/' . $rel . '.php';

        // Fallback: tenta resolver via module_dir_path (se existir)
        if (!file_exists($abs) && function_exists('module_dir_path')) {
            $alt = module_dir_path('qrassociados', 'views/' . $rel . '.php');
            if ($alt && file_exists($alt)) {
                $abs = $alt;
            }
        }

        // Renderiza SEM usar $CI->load->view (evita "Unable to load the requested file")
        if (file_exists($abs)) {
            // Garante que as variáveis ($top, $me, etc.) existam no escopo da view
            if (is_array($vars)) {
                extract($vars, EXTR_SKIP);
            }
            ob_start();
            include $abs;
            echo ob_get_clean();
        } else {
            // Mensagem amigável (opcional) para caso de caminho incorreto
            echo '<div class="alert alert-warning" style="margin:10px 0;">';
            echo 'View não encontrada: <code>' . htmlspecialchars($abs) . '</code>';
            echo '</div>';
        }
    }
}

include_once __DIR__ . '/qrassociados_top10_boot.php';
require_once __DIR__ . '/patches/admin_ranking_filters.php';

