<?php defined('BASEPATH') or exit('No direct script access allowed'); ?>
<?php init_head(); ?>
<div id="wrapper">
  <div class="content">
    <div class="row">
      <div class="col-md-12">

        <div class="panel_s">
          <div class="panel-body">
            <h4 class="no-margin">
              Módulos <small class="text-muted">— planB view patch ativo</small>
            </h4>
          </div>
        </div>

        <?php
        // ---------------- Funções utilitárias ----------------
        function qr_mod_to_array($m) {
          if (is_array($m)) return $m;
          if (is_object($m)) return get_object_vars($m);
          return [];
        }

        function qr_guess_slug(array $m) {
          // possíveis nomes de chave que podem conter o slug
          foreach (['system_name','dir','slug','folder','module_dir','module','module_name'] as $k) {
            if (!empty($m[$k])) return strtolower(trim($m[$k]));
          }
          // se vier "QR Associados" como module_name (display), cria um slug plausível
          if (!empty($m['name'])) return strtolower(preg_replace('/\s+/', '', $m['name']));
          return '';
        }

        function qr_load_config_meta($baseDir, $slug) {
          $out = [];
          $cfg = rtrim($baseDir,'/').'/'.$slug.'/config.php';
          if (is_file($cfg)) {
            $module = [];
            include $cfg; // muitos módulos definem $module = [...]
            if (is_array($module)) $out = $module;
          }
          return $out;
        }

        function qr_human($slug) {
          $s = str_replace(['_', '-'], ' ', $slug);
          return ucwords($s);
        }

        // ---------------- Montagem da lista ----------------
        $baseDir = FCPATH . 'modules';
        $CI = get_instance();
        $db = isset($CI->db) ? $CI->db : null;

        // Se o controller passou $modules usamos, senão varremos /modules
        $source = [];
        if (isset($modules) && is_array($modules)) {
          $source = $modules;
        } else {
          if (is_dir($baseDir)) {
            foreach (scandir($baseDir) as $dir) {
              if ($dir=='.' || $dir=='..') continue;
              if (is_dir($baseDir.'/'.$dir)) {
                $source[] = ['system_name'=>$dir];
              }
            }
          }
        }

        // Normalização (sem avisos)
        $modules_list = [];
        foreach ($source as $row) {
          $m = qr_mod_to_array($row);

          $slug = qr_guess_slug($m);

          // caso o slug ainda não exista, mas exista "installed_version" e nada de slug,
          // tentamos usar chaves conhecidas para derivar
          if (!$slug && !empty($m['installed_version'])) {
            $slug = !empty($m['name']) ? strtolower(preg_replace('/\s+/', '', $m['name'])) : '';
          }

          // meta do config.php (friendly name, description etc.)
          $meta = $slug ? qr_load_config_meta($baseDir, $slug) : [];

          // exibição
          $display_name = $meta['module_name'] ?? ($m['name'] ?? ($m['module_name'] ?? ($slug ? qr_human($slug) : '')));
          $description  = $meta['description'] ?? ($m['description'] ?? '');
          $version      = $meta['version'] ?? ($m['installed_version'] ?? ($m['version'] ?? ''));
          $author       = $meta['author'] ?? ($m['author'] ?? '');

          // status ativo: preferir campo vindo do controller; fallback no banco
          $active = null;
          if (isset($m['active'])) {
            $active = (int)$m['active'];
          } elseif ($db && $slug) {
            $q = $db->get_where('tblmodules',['module_name'=>$slug])->row();
            $active = $q ? (int)$q->active : 0;
          } else {
            $active = 0;
          }

          // guardar item já consolidado
          $modules_list[] = [
            'slug'        => $slug,
            'name'        => $display_name,
            'description' => $description,
            'version'     => $version,
            'author'      => $author,
            'active'      => $active,
          ];
        }
        ?>

        <div class="panel_s">
          <div class="panel-body">
            <div class="row">
              <div class="col-md-8">
                <form method="post" enctype="multipart/form-data" action="">
                  <div class="form-group" style="max-width:520px;">
                    <label>Enviar módulo (.zip)</label>
                    <div class="input-group">
                      <input type="file" class="form-control" name="module_zip" accept=".zip">
                      <span class="input-group-btn">
                        <button type="submit" class="btn btn-primary">Enviar e instalar</button>
                      </span>
                    </div>
                    <p class="text-muted mtop10">O arquivo será extraído em <code>/modules</code>.</p>
                  </div>
                </form>
              </div>
              <div class="col-md-4 text-right">
                <a href="?refresh=1" class="btn btn-default">
                  <i class="fa fa-refresh"></i> Atualizar
                </a>
              </div>
            </div>

            <div class="table-responsive">
              <table class="table dt-table">
                <thead>
                  <tr>
                    <th>Nome</th>
                    <th>Descrição</th>
                    <th>Versão</th>
                    <th>Autor</th>
                    <th>Status</th>
                    <th class="text-right">Ações</th>
                  </tr>
                </thead>
                <tbody>
                <?php if (!empty($modules_list)): ?>
                  <?php foreach ($modules_list as $m): ?>
                    <tr>
                      <td><?php echo htmlspecialchars($m['name'] ?? ''); ?></td>
                      <td class="text-muted" style="max-width:520px;">
                        <?php echo htmlspecialchars($m['description'] ?? ''); ?>
                      </td>
                      <td><?php echo htmlspecialchars($m['version'] ?? ''); ?></td>
                      <td><?php echo htmlspecialchars($m['author'] ?? ''); ?></td>
                      <td>
                        <?php if ((string)($m['active'] ?? '0') === '1'): ?>
                          <span class="label label-success">Ativo</span>
                        <?php else: ?>
                          <span class="label label-default">Inativo</span>
                        <?php endif; ?>
                      </td>
                      <td class="text-right">
                        <?php
                          $slug = urlencode($m['slug'] ?? '');
                          if ($slug):
                            if ((string)($m['active'] ?? '0') === '1'): ?>
                              <a href="<?php echo current_url().'?toggle='.$slug.'&state=0'; ?>" class="btn btn-danger btn-sm">Desativar</a>
                            <?php else: ?>
                              <a href="<?php echo current_url().'?toggle='.$slug.'&state=1'; ?>" class="btn btn-success btn-sm">Ativar</a>
                            <?php endif;
                          endif;
                        ?>
                      </td>
                    </tr>
                  <?php endforeach; ?>
                <?php else: ?>
                  <tr>
                    <td colspan="6" class="text-center text-muted">Nenhum módulo encontrado.</td>
                  </tr>
                <?php endif; ?>
                </tbody>
              </table>
            </div>

          </div>
        </div>

      </div>
    </div>
  </div>
</div>
<?php init_tail(); ?>
