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

/**
 * Custom hooks/filters for your CRM
 */

hooks()->add_filter('before_get_project_statuses', 'oppein_add_project_status_active');
function oppein_add_project_status_active($current_statuses)
{
    $current_statuses[] = [
        'id'             => 50,
        'color'          => '#1e90ff',
        'name'           => 'Active',
        'order'          => 3,
        'filter_default' => true,
    ];

    return $current_statuses;
}

hooks()->add_action('app_admin_footer', 'oppein_project_rows_soft_color');
function oppein_project_rows_soft_color()
{
    // Admin ekranı değilse hiç basma
    if (!function_exists('is_staff_logged_in') || !is_staff_logged_in()) {
        return;
    }

    // İstersen sadece projects sayfasına kilitle (yanlışsa yorum satırı yap)
    $CI =& get_instance();
    if (isset($CI->router) && method_exists($CI->router, 'fetch_class')) {
        $class = $CI->router->fetch_class();
        if ($class !== 'projects') {
            return;
        }
    }

    $js = <<<JS
(function () {
  var ALPHA = 25.07;

  function parseRgb(str) {
    if (!str) return null;
    var m = str.match(/rgba?\\s*\\(\\s*(\\d+)[,\\s]+(\\d+)[,\\s]+(\\d+)/i);
    if (!m) return null;
    return { r: +m[1], g: +m[2], b: +m[3] };
  }

  function getBadgeColor(el) {
    var cs = window.getComputedStyle(el);
    var bg = cs.backgroundColor;
    var rgb = parseRgb(bg);

    if (!rgb || bg === 'transparent' || bg === 'rgba(0, 0, 0, 0)') {
      var bc = cs.borderTopColor || cs.borderColor;
      rgb = parseRgb(bc);
    }

    if (!rgb) rgb = parseRgb(cs.color);
    return rgb;
  }

  function applyRowColors() {
    var rows = document.querySelectorAll('table tbody tr');
    rows.forEach(function (tr) {
      var badge =
        tr.querySelector('.label, .badge') ||
        tr.querySelector('[class*="status"]') ||
        tr.querySelector('.project-status');

      if (!badge) return;

      var rgb = getBadgeColor(badge);
      if (!rgb) return;

      var rowBg = 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + ALPHA + ')';
      tr.style.setProperty('background-color', rowBg, 'important');
      tr.classList.add('oppein-row-colored');
    });
  }

  document.addEventListener('DOMContentLoaded', function () {
    applyRowColors();
    setTimeout(applyRowColors, 700);
  });

  document.addEventListener('draw.dt', function () {
    applyRowColors();
  });

  if (window.jQuery) {
    window.jQuery(document).ajaxComplete(function () {
      applyRowColors();
    });
  }
})();
JS;

    echo '<script>' . $js . '</script>';
    echo '<style>tr.oppein-row-colored:hover{filter:brightness(0.985);}</style>';
}

hooks()->add_action('app_admin_footer', 'oppein_inline_status_click_change');

function oppein_inline_status_click_change()
{
    if (!function_exists('is_staff_logged_in') || !is_staff_logged_in()) return;

    $CI =& get_instance();
    if (isset($CI->router) && method_exists($CI->router, 'fetch_class')) {
        if ($CI->router->fetch_class() !== 'projects') return;
    }

    // Status listesi bazen boş dönebiliyor; boşsa fallback veriyoruz.
    $statuses = function_exists('get_project_statuses') ? get_project_statuses() : [];
    if (empty($statuses)) {
        $statuses = [
            ['id'=>1,'name'=>'Not Started'],
            ['id'=>2,'name'=>'In Progress'],
            ['id'=>3,'name'=>'On Hold'],
            ['id'=>5,'name'=>'Cancelled'],
            ['id'=>4,'name'=>'Finished'],
            ['id'=>50,'name'=>'Active'],
        ];
    }
    $statuses_json = json_encode(array_values($statuses));

    $js = <<<JS
(function () {
  var STATUSES = $statuses_json;
  var menuEl = null;
  var current = { projectId: null, dt: null };

  function getDT(){
    if (!window.jQuery || !jQuery.fn || !jQuery.fn.dataTable) return null;
    var tables = jQuery('table');
    for (var i=0;i<tables.length;i++){
      if (jQuery.fn.dataTable.isDataTable(tables[i])) return jQuery(tables[i]).DataTable();
    }
    return null;
  }

  function adminBase(){
    // sende /adm/ var; Perfex genelde window.admin_url basar
    var a = (window.admin_url || '');
    if (a) return a.endsWith('/') ? a : (a + '/');

    // fallback: URL'den /adm/ veya /admin/ yakala
    var p = location.pathname;
    var m = p.match(/^(.*\\/(?:admin|adm)\\/)/i);
    return m ? m[1] : '/adm/';
  }

  function csrfAppend(data){
    if (window.csrfData && window.csrfData.token_name && window.csrfData.hash) {
      data[window.csrfData.token_name] = window.csrfData.hash;
    }
    return data;
  }

  function findProjectId(tr){
    var a = tr.querySelector('a[href*="projects/view/"]');
    if (!a) return null;
    var href = a.getAttribute('href') || '';
    var m = href.match(/projects\\/view\\/(\\d+)/i);
    return m ? m[1] : null;
  }

  function statusColIndex(table){
    var ths = table.querySelectorAll('thead th');
    for (var i=0;i<ths.length;i++){
      var t = (ths[i].textContent || '').trim().toLowerCase();
      if (t === 'status') return i;
    }
    return -1;
  }

  function ensureMenu(){
    if (menuEl) return menuEl;

    menuEl = document.createElement('div');
    menuEl.className = 'oppein-status-menu';
    menuEl.style.display = 'none';

    // menüye tıklayınca kapanmasın
    menuEl.addEventListener('mousedown', function(e){ e.stopPropagation(); });
    menuEl.addEventListener('click', function(e){ e.stopPropagation(); });

    // içerik
    if (Array.isArray(STATUSES) && STATUSES.length) {
      STATUSES.forEach(function(st){
        var item = document.createElement('div');
        item.className = 'oppein-status-item';
        item.dataset.id = st.id;
        item.textContent = st.name;
        menuEl.appendChild(item);
      });
    } else {
      var empty = document.createElement('div');
      empty.className = 'oppein-status-empty';
      empty.textContent = 'No statuses found';
      menuEl.appendChild(empty);
    }

    document.body.appendChild(menuEl);
    return menuEl;
  }

  function showMenuNear(el){
    var m = ensureMenu();

    // önce görünmez aç -> ölç -> ekranda taşmasın
    m.style.visibility = 'hidden';
    m.style.display = 'block';

    var rect = el.getBoundingClientRect();
    var x = rect.left + window.scrollX;
    var y = rect.bottom + window.scrollY + 6;

    var mw = m.offsetWidth || 200;
    var mh = m.offsetHeight || 240;

    var maxX = window.scrollX + window.innerWidth - mw - 10;
    var maxY = window.scrollY + window.innerHeight - mh - 10;

    if (x > maxX) x = maxX;
    if (y > maxY) y = Math.max(window.scrollY + 10, rect.top + window.scrollY - mh - 6);

    m.style.left = x + 'px';
    m.style.top  = y + 'px';
    m.style.visibility = 'visible';
  }

  function hideMenu(){
    if (menuEl) menuEl.style.display = 'none';
  }

  function postMarkAs(projectId, statusId, dt){
    var url = adminBase() + 'projects/mark_as'; // sende çalıştı: /adm/projects/mark_as
    var data = csrfAppend({ project_id: projectId, status_id: statusId });

    return jQuery.post(url, data).done(function(){
      // tabloyu yenile
      if (dt && dt.ajax && typeof dt.ajax.reload === 'function') {
        dt.ajax.reload(null, false);
      } else if (dt) {
        dt.draw(false);
      } else {
        location.reload();
      }
    }).fail(function(xhr){
      alert('Status update failed: ' + (xhr.status || ''));
    });
  }

  function wire(){
    var dt = getDT();
    if (!dt) return;

    var table = dt.table().node();
    if (!table) return;

    var idx = statusColIndex(table);
    if (idx === -1) return;

    table.querySelectorAll('tbody tr').forEach(function(tr){
      var tds = tr.querySelectorAll('td');
      if (!tds[idx]) return;

      var cell = tds[idx];

      // hücre içinde badge/label bul -> onu "buton" gibi yap
      var badge = cell.querySelector('.badge, .label') || cell;
      badge.classList.add('oppein-status-trigger');

      if (cell.dataset.oppeinWired === '1') return;
      cell.dataset.oppeinWired = '1';

      cell.addEventListener('mousedown', function(e){
        e.stopPropagation(); // document handler menüyü hemen kapatmasın
      });

      cell.addEventListener('click', function(e){
        e.stopPropagation();

        var projectId = findProjectId(tr);
        if (!projectId) return;

        current.projectId = projectId;
        current.dt = dt;

        showMenuNear(badge);
      });
    });
  }

  // Menü item seçimi
  document.addEventListener('click', function(){
    hideMenu();
  });

  document.addEventListener('click', function(e){
    if (!menuEl || menuEl.style.display === 'none') return;

    var item = e.target && e.target.classList && e.target.classList.contains('oppein-status-item') ? e.target : null;
    if (!item) return;

    e.stopPropagation();
    hideMenu();

    var statusId = item.dataset.id;
    if (!window.jQuery) return;
    postMarkAs(current.projectId, statusId, current.dt);
  }, true);

  document.addEventListener('DOMContentLoaded', function(){
    wire();
    setTimeout(wire, 800);
  });

  document.addEventListener('draw.dt', function(){
    wire();
  });

  if (window.jQuery) {
    jQuery(document).ajaxComplete(function(){ wire(); });
  }
})();
JS;

    echo '<script>' . $js . '</script>';

    // Statusları buton gibi göster + menu tasarımı
    echo '<style>
      .oppein-status-trigger{
        display:inline-flex;
        align-items:center;
        gap:6px;
        padding:6px 12px;
        border-radius:999px;
        cursor:pointer !important;
        user-select:none;
        box-shadow:0 1px 0 rgba(0,0,0,.05);
      }
      .oppein-status-trigger:after{
        content:"▾";
        font-size:12px;
        opacity:.55;
      }

      .oppein-status-menu{
        position:absolute;
        z-index:2147483647;
        min-width:200px;
        background:#fff;
        border:1px solid rgba(0,0,0,.10);
        border-radius:14px;
        box-shadow:0 12px 40px rgba(0,0,0,.16);
        padding:6px;
        max-height:300px;
        overflow:auto;
      }
      .oppein-status-item{
        padding:9px 10px;
        border-radius:12px;
        cursor:pointer;
        font-size:13px;
      }
      .oppein-status-item:hover{
        background:rgba(0,0,0,.06);
      }
      .oppein-status-empty{
        padding:10px;
        opacity:.7;
        font-size:13px;
      }
    </style>';
}


