<?php
// =============================================
// SHARK CRM - Main Router (index.php)
// =============================================
session_start();

// Auth check
if (!isset($_SESSION['user_id'])) {
    $page = isset($_GET['page']) ? $_GET['page'] : '';
    if ($page !== 'login') {
        header('Location: index.php?page=login');
        exit;
    }
}

// Handle logout
if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: index.php?page=login');
    exit;
}

$page = isset($_GET['page']) ? $_GET['page'] : 'dashboard';

// Login page – no layout
if ($page === 'login') {
    include 'pages/login.php';
    exit;
}

// Load DB
require_once 'connect.php';

// Current user
$user_id    = $_SESSION['user_id'];
$account_id = $_SESSION['account_id'];
$user_name  = $_SESSION['user_name'];
$user_role  = $_SESSION['user_role'] ?? 'User';

// Pending reminders count
$rem_result = $conn->query("SELECT COUNT(*) as cnt FROM reminder WHERE account_id = $account_id AND status = 'pending' AND date <= CURDATE()");
$rem_count  = $rem_result ? (int)$rem_result->fetch_assoc()['cnt'] : 0;
$today_result = $conn->query("SELECT COUNT(*) as cnt FROM reminder WHERE account_id = $account_id AND status='pending' AND date = CURDATE()");
$today_rem_count = $today_result ? (int)$today_result->fetch_assoc()['cnt'] : 0;

// Navigation is loaded from config/pages.php and filtered by user permissions
$pages_config = crmPagesConfig();
$nav = [];
foreach ($pages_config as $key => $cfg) {
    if (pageAllowed($conn, $key)) {
        $item = ['page'=>$key, 'label'=>$cfg['label'], 'icon'=>$cfg['icon'] ?? 'grid'];
        if ($key === 'reminders') $item['badge'] = $rem_count;
        $nav[] = $item;
    }
}
if (!pageAllowed($conn, $page)) {
    header('Location: index.php?page=' . ($nav[0]['page'] ?? 'dashboard'));
    exit;
}

$current_permissions = [];
foreach ($pages_config as $k => $cfg) {
    $current_permissions[$k] = [];
    foreach (($cfg['actions'] ?? ['view']) as $act) {
        $current_permissions[$k][$act] = userCan($conn, $k, $act);
    }
}

$page_titles = [];
foreach ($pages_config as $key => $cfg) {
    $page_titles[$key] = [$cfg['label'], $key === 'dashboard' ? 'Overview & Statistics' : $cfg['label']];
}

$title    = $page_titles[$page][0] ?? 'Page';
$subtitle = $page_titles[$page][1] ?? '';

// SVG icon helper
function nav_icon($name) {
    $icons = [
        'grid'         => '<rect x="3" y="3" width="7" height="7"></rect><rect x="14" y="3" width="7" height="7"></rect><rect x="14" y="14" width="7" height="7"></rect><rect x="3" y="14" width="7" height="7"></rect>',
        'trending-up'  => '<polyline points="23 6 13.5 15.5 8.5 10.5 1 18"></polyline><polyline points="17 6 23 6 23 12"></polyline>',
        'columns'      => '<rect x="3" y="3" width="6" height="18" rx="1"></rect><rect x="15" y="3" width="6" height="18" rx="1"></rect>',
        'users'        => '<path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path><circle cx="9" cy="7" r="4"></circle><path d="M23 21v-2a4 4 0 0 0-3-3.87"></path><path d="M16 3.13a4 4 0 0 1 0 7.75"></path>',
        'package'      => '<line x1="16.5" y1="9.4" x2="7.5" y2="4.21"></line><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"></path><polyline points="3.27 6.96 12 12.01 20.73 6.96"></polyline><line x1="12" y1="22.08" x2="12" y2="12"></line>',
        'bell'         => '<path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"></path><path d="M13.73 21a2 2 0 0 1-3.46 0"></path>',
        'settings'     => '<circle cx="12" cy="12" r="3"></circle><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"></path>',
        'activity'     => '<polyline points="22 12 18 12 15 21 9 3 6 12 2 12"></polyline>',
        'log-out'      => '<path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"></path><polyline points="16 17 21 12 16 7"></polyline><line x1="21" y1="12" x2="9" y2="12"></line>',
        // Add to the $icons array in nav_icon function:
'file-text' => '<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path><polyline points="14 2 14 8 20 8"></polyline><line x1="16" y1="13" x2="8" y2="13"></line><line x1="16" y1="17" x2="8" y2="17"></line><polyline points="10 9 9 9 8 9"></polyline>',
'mail' => '<path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"></path><polyline points="22,6 12,13 2,6"></polyline>',
    ];
    return '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">' . ($icons[$name] ?? '') . '</svg>';
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Shark CRM – <?= htmlspecialchars($title) ?></title>
<link rel="stylesheet" href="assets/css/style.css?v=<?php echo strtotime('now'); ?>">
</head>
<body>
<div id="toast-container"></div>

<div id="app-wrapper">
  <!-- ===================== SIDEBAR ===================== -->
  <aside id="sidebar">
    <div class="sidebar-logo">
      <div class="logo-icon">🦈</div>
      <div class="logo-text">
          <p>SHARK<span>CRM</span></p>
          <p><span style="    color: white;
    font-size: 12px;"><?php echo "Hello, ". $_SESSION['user_name'];   ?></span></p>
      </div>
      
    </div>

    <nav class="sidebar-nav">
      <div class="sidebar-section-title">Menu</div>
      <?php foreach ($nav as $item): ?>
      <a class="nav-item <?= $page === $item['page'] ? 'active' : '' ?>"
         href="index.php?page=<?= $item['page'] ?>">
        <?= nav_icon($item['icon']) ?>
        <?= $item['label'] ?>
        <?php if (!empty($item['badge']) && $item['badge'] > 0): ?>
          <span class="nav-badge"><?= $item['badge'] ?></span>
        <?php endif; ?>
      </a>
      <?php endforeach; ?>
    </nav>

    <div class="sidebar-user">
      <div class="user-avatar"><?= strtoupper(substr($user_name, 0, 2)) ?></div>
      <div class="user-info">
        <div class="user-name"><?= htmlspecialchars($user_name) ?></div>
        <div class="user-role"><?= htmlspecialchars($user_role) ?></div>
      </div>
      <a href="index.php?logout=1" class="btn-logout" title="Logout">
        <?= nav_icon('log-out') ?>
      </a>
    </div>
     <div class="sidebar-user" style="display: block;">
    <a class="nav-item "
         href="index.php?logout=1">
             <?= nav_icon('log-out') ?>
        Logout
       
      </a>
      </div>
      
  </aside>

  <!-- ===================== MAIN ===================== -->
  <div id="main-content">
    <!-- Header -->
    <header id="top-header">
      <div class="page-title-area">
        <div class="page-title"><?= htmlspecialchars($title) ?></div>
        <?php if ($subtitle): ?>
        <div class="page-breadcrumb">Shark CRM / <?= htmlspecialchars($subtitle) ?></div>
        <?php endif; ?>
      </div>

      <div class="header-actions">
        <a href="index.php?page=reminders" class="btn-icon reminder-badge" title="Reminders">
          🔔
          <?php if ($today_rem_count > 0): ?>
            <span class="nav-badge" style="position:absolute;right:-8px;top:-8px"><?= $today_rem_count ?></span>
          <?php elseif ($rem_count > 0): ?>
            <span class="dot"></span>
          <?php endif; ?>
        </a>
        <div class="user-avatar avatar-sm"><?= strtoupper(substr($user_name, 0, 2)) ?></div>
      </div>
    </header>

    <!-- Page Content -->
    <div id="page-content">
      <?php
   switch ($page) {
    case 'dashboard':  include 'pages/dashboard.php';  break;
    case 'leads':      include 'pages/leads.php';      break;
    case 'pipeline':   include 'pages/pipeline.php';   break;
    case 'customers':  include 'pages/customers.php';  break;
    case 'items':      include 'pages/items.php';      break;
    case 'quotations': include 'pages/quotations.php'; break;
    case 'quotation_invoice': include 'pages/quotation_invoice.php'; break;
    case 'campaigns':  include 'pages/campaigns.php';  break; // NEW
    case 'audience':   include 'pages/audience.php';   break;
    case 'activities': include 'pages/activities.php'; break;
    case 'reminders':  include 'pages/reminders.php';  break;
    case 'settings':   include 'pages/settings.php';   break;
    case 'lead':       include 'pages/lead.php';       break;
    case 'customer_view':       include 'pages/customer_view.php';       break;
    default:           include 'pages/dashboard.php';
}
      ?>
    </div>
  </div>
</div>


<script>



window.CRM_PAGE = <?= json_encode($_GET["page"]) ?>;
window.CRM_PERMISSIONS = <?= json_encode($current_permissions) ?>;

(function () {
  const P = window.CRM_PERMISSIONS || {};
  const pageAliases = { lead:'leads', customer_view:'customers', pipeline:'leads' };
  const currentPage = pageAliases[window.CRM_PAGE] || window.CRM_PAGE;
    console.log(currentPage);
  function can(action, page) {
      console.log("action "+action);
      console.log("page "+page);
    const pageKey = page || currentPage;
    return !!(P[pageKey] && P[pageKey][action]);
  }

  function protectElement(el) {
    const action = el.getAttribute('data-permission');
    if (!action) return;
    const page = el.getAttribute('data-page') || currentPage;
    
    // Debug logging
    console.log(`Checking permission for ${page}.${action}: ${can(action, page)}`);
    
    if (!can(action, page)) {
      console.log(`Removing element with permission ${action} on page ${page}`);
      el.remove();
    }
  }

  document.addEventListener('DOMContentLoaded', function () {
    // Check all elements with data-permission attribute
    document.querySelectorAll('[data-permission]').forEach(protectElement);
    
    // Also check for dynamically added elements
    const observer = new MutationObserver(function(mutations) {
      mutations.forEach(function(mutation) {
        mutation.addedNodes.forEach(function(node) {
          if (node.nodeType === 1 && node.matches && node.matches('[data-permission]')) {
            protectElement(node);
          }
        });
      });
    });
    
    observer.observe(document.body, { childList: true, subtree: true });
  });
})();
</script>

<script src="assets/js/main.js"></script>
<script src="assets/js/pipeline.js"></script>
</body>
</html>
