/* Zabibu Residence - Admin Panel JS */
$(document).ready(function () {

  // Sidebar toggle (mobile)
  $('#sidebarToggleBtn, #sidebarToggle').on('click', function () {
    $('#sidebar').toggleClass('show');
    $('body').toggleClass('sidebar-overlay');
  });

  // Click outside to close on mobile
  $(document).on('click', function (e) {
    if ($(window).width() < 992) {
      if (!$(e.target).closest('#sidebar, #sidebarToggleBtn, #sidebarToggle').length) {
        $('#sidebar').removeClass('show');
        $('body').removeClass('sidebar-overlay');
      }
    }
  });

  // DataTable init (if table has class datatable)
  if ($.fn.DataTable && $('.datatable').length) {
    $('.datatable').DataTable({
      pageLength: 15,
      order: [[0, 'desc']],
      language: { search: '', searchPlaceholder: 'Search...' },
      responsive: true
    });
  }

  // AJAX status update
  $(document).on('change', '.status-select', function () {
    var $sel = $(this);
    var url  = $sel.data('url');
    var val  = $sel.val();
    $.post(url, { status: val, _csrf_token: $('meta[name=csrf]').attr('content') }, function (res) {
      if (res.success) {
        showToast('Status updated successfully', 'success');
      }
    }).fail(function () {
      showToast('Failed to update status', 'danger');
    });
  });

  // Quick action shortcuts
  $(document).on('keydown', function (e) {
    if (e.ctrlKey && e.key === 'k') {
      e.preventDefault();
      $('#globalSearch').focus();
    }
  });

  // Toast notification
  window.showToast = function (message, type) {
    type = type || 'success';
    var id = 'toast_' + Date.now();
    var html = '<div id="' + id + '" class="toast align-items-center text-white bg-' + type + ' border-0 position-fixed bottom-0 end-0 m-3" role="alert" style="z-index:9999">'
      + '<div class="d-flex"><div class="toast-body"><i class="bi bi-' + (type==='success'?'check-circle':'exclamation-triangle') + ' me-2"></i>' + message + '</div>'
      + '<button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button></div></div>';
    $('body').append(html);
    var toast = new bootstrap.Toast(document.getElementById(id), { delay: 3500 });
    toast.show();
    setTimeout(function () { $('#' + id).remove(); }, 4000);
  };

  // Confirm delete forms
  $(document).on('submit', '.form-delete', function (e) {
    if (!confirm('Delete this record permanently?')) e.preventDefault();
  });

  // Initialize charts if page has them
  initDashboardCharts();
});

function initDashboardCharts() {
  var isDark = document.documentElement.getAttribute('data-bs-theme') === 'dark';
  var tickColor  = isDark ? '#e2e8f0' : '#1e293b';

  // Set Chart.js global defaults so all charts inherit correct colors
  if (typeof Chart !== 'undefined') {
    Chart.defaults.color = tickColor;
    Chart.defaults.borderColor = isDark ? 'rgba(255,255,255,0.08)' : 'rgba(0,0,0,0.06)';
  }
  var gridColor  = isDark ? 'rgba(255,255,255,0.08)' : 'rgba(0,0,0,0.06)';
  var lineColor  = isDark ? '#60a5fa' : '#1a3c5e';
  var lineFill   = isDark ? 'rgba(96,165,250,0.10)' : 'rgba(26,60,94,0.08)';

  // Revenue chart
  var $revenueCanvas = document.getElementById('revenueChart');
  if ($revenueCanvas) {
    var data = JSON.parse($revenueCanvas.dataset.values || '{}');
    new Chart($revenueCanvas, {
      type: 'line',
      data: {
        labels: data.labels || [],
        datasets: [{
          label: 'Revenue (TZS)',
          data: data.values || [],
          borderColor: lineColor,
          backgroundColor: lineFill,
          borderWidth: 2.5,
          fill: true,
          tension: 0.4,
          pointBackgroundColor: lineColor,
          pointRadius: 4,
          pointHoverRadius: 6
        }]
      },
      options: {
        responsive: true, maintainAspectRatio: false,
        plugins: { legend: { display: false } },
        scales: {
          y: {
            grid: { color: gridColor },
            ticks: {
              color: tickColor,
              font: { size: 11 },
              callback: function(v){ return 'TZS '+Number(v).toLocaleString(); }
            }
          },
          x: {
            grid: { display: false },
            ticks: { color: tickColor, font: { size: 11 } }
          }
        }
      }
    });
  }

  // Occupancy donut
  var $occCanvas = document.getElementById('occupancyChart');
  if ($occCanvas) {
    var occ = JSON.parse($occCanvas.dataset.values || '{}');
    new Chart($occCanvas, {
      type: 'doughnut',
      data: {
        labels: ['Occupied', 'Available', 'Maintenance'],
        datasets: [{
          data: [occ.occupied || 0, occ.available || 0, occ.maintenance || 0],
          backgroundColor: ['#1a3c5e', '#22c55e', '#f59e0b'],
          borderWidth: 0, hoverOffset: 6
        }]
      },
      options: {
        responsive: true, maintainAspectRatio: false,
        plugins: {
          legend: { position: 'bottom', labels: { padding: 16, usePointStyle: true, pointStyle: 'circle', color: tickColor } }
        },
        cutout: '70%'
      }
    });
  }

  // Payment methods pie
  var $pmCanvas = document.getElementById('paymentMethodChart');
  if ($pmCanvas) {
    var pm = JSON.parse($pmCanvas.dataset.values || '{}');
    new Chart($pmCanvas, {
      type: 'bar',
      data: {
        labels: pm.labels || [],
        datasets: [{
          data: pm.values || [],
          backgroundColor: ['#1a3c5e','#2563eb','#16a34a','#ca8a04','#7c3aed','#ea580c','#14b8a6'],
          borderRadius: 6
        }]
      },
      options: {
        responsive: true, maintainAspectRatio: false,
        plugins: { legend: { display: false } },
        scales: { x: { grid: { display: false } }, y: { grid: { color: 'rgba(0,0,0,0.04)' } } }
      }
    });
  }
}
