<?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';
$accountHeaderSelect = columnExists($conn, 'accounts', 'default_leads_view') ? 'id, business_name, client_name, default_leads_view, price_decimals' : 'id, business_name, client_name';
$account_header = $conn->query("SELECT $accountHeaderSelect FROM accounts WHERE id=$account_id LIMIT 1")->fetch_assoc();
if ($page === 'leads' && !isset($_GET['view']) && (($account_header['default_leads_view'] ?? 'list') === 'pipeline')) { header('Location: index.php?page=pipeline'); exit; }

// 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;

// Header connection health
$header_email_ok = tableExists($conn,'accounts_email') && ($conn->query("SELECT id FROM accounts_email WHERE account_id=$account_id LIMIT 1")->num_rows > 0);
$header_wa_ok = tableExists($conn,'contact_phone') && ($conn->query("SELECT id FROM contact_phone WHERE account_id=$account_id LIMIT 1")->num_rows > 0);
$header_sms_ok = tableExists($conn,'communications');
$header_all_ok = $header_email_ok && $header_wa_ok && $header_sms_ok;

// 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>',
        'calendar'     => '<rect x="3" y="4" width="18" height="18" rx="2" ry="2"></rect><line x1="16" y1="2" x2="16" y2="6"></line><line x1="8" y1="2" x2="8" y2="6"></line><line x1="3" y1="10" x2="21" y2="10"></line>',
        '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>',
'send' => '<line x1="22" y1="2" x2="11" y2="13"></line><polygon points="22 2 15 22 11 13 2 9 22 2"></polygon>',
'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>',
        'dollar-sign' => '<line x1="12" y1="1" x2="12" y2="23"></line><path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"></path>',
    ];
    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">
    <button type="button" id="sidebar-toggle" title="Toggle sidebar" aria-label="Toggle sidebar"></button>
    <div class="sidebar-logo">
      <div class="logo-icon">🦈</div>
      <div class="logo-text">
          <p><?= htmlspecialchars($account_header['business_name'] ?: $account_header['client_name'] ?: 'SHARK CRM') ?></p>
          <p><span style="color:white;font-size:12px;letter-spacing:0">Hello, <?= htmlspecialchars($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 class="text-xs text-muted"><?= htmlspecialchars($account_header['business_name'] ?: $account_header['client_name'] ?: '') ?></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) ?><?php if (!empty($account_header['business_name']) || !empty($account_header['client_name'])): ?> / <strong><?= htmlspecialchars($account_header['business_name'] ?: $account_header['client_name']) ?></strong><?php endif; ?></div>
        <?php endif; ?>
      </div>

      <div class="header-actions">
        <div class="connection-pill <?= $header_all_ok ? 'ok' : 'issue' ?>" title="WhatsApp: <?= $header_wa_ok ? 'OK' : 'Issue' ?> | SMS: <?= $header_sms_ok ? 'OK' : 'Issue' ?> | Email: <?= $header_email_ok ? 'OK' : 'Issue' ?>"><span class="conn-dot"></span><span><?= $header_all_ok ? 'All connected' : 'Connection issue' ?></span></div>
        <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="top-account-pill"><span><?= htmlspecialchars($account_header['business_name'] ?: $account_header['client_name'] ?: ('Account #'.$account_id)) ?></span></div><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 'customer_report': include 'pages/customer_report.php'; break;
    case 'add_customer': include 'pages/add_customer.php'; break;
    case 'edit_customer': include 'pages/edit_customer.php'; break;
    case 'items':      include 'pages/items.php';      break;
    case 'quotations': include 'pages/quotations.php'; break;
    case 'deals':      include 'pages/deals.php';      break;
    case 'quotation_invoice': include 'pages/quotation_invoice.php'; break;
    case 'campaigns':  include 'pages/campaigns.php';  break; // NEW
    case 'campaign_add': include 'pages/campaign_form.php'; break;
    case 'campaign_edit': include 'pages/campaign_form.php'; break;
    case 'campaign_view': include 'pages/campaign_view.php'; break;
    case 'campaign_report': include 'pages/campaign_report.php'; break;
    case 'audience':   include 'pages/audience.php';   break;
    case 'audience_add': include 'pages/audience_form.php'; break;
    case 'audience_edit': include 'pages/audience_form.php'; break;
    case 'audience_view': include 'pages/audience_view.php'; break;
    case 'occasions': include 'pages/occasions.php'; break;
    case 'activities': include 'pages/activities.php'; break;
    case 'message_logs': include 'pages/message_logs.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) ?>;
window.CRM_PRICE_DECIMALS = <?= (int)($account_header['price_decimals'] ?? crmPriceDecimals($conn)) ?>;

(function () {
  const P = window.CRM_PERMISSIONS || {};
  const pageAliases = { lead:'leads', customer_view:'customers', customer_report:'customers', pipeline:'leads' };
  const currentPage = pageAliases[window.CRM_PAGE] || window.CRM_PAGE;
  function can(action, page) { return true; }

  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)}`);
    
    return;
  }

  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>
(function(){
  const btn=document.getElementById('sidebar-toggle');
  const wrap=document.getElementById('app-wrapper');
  if(btn){btn.addEventListener('click',()=>{wrap.classList.toggle('sidebar-collapsed');localStorage.setItem('crm_sidebar_collapsed',wrap.classList.contains('sidebar-collapsed')?'1':'0');});
  if(localStorage.getItem('crm_sidebar_collapsed')==='1') wrap.classList.add('sidebar-collapsed');}
})();
</script>
<script src="assets/js/main.js"></script>
<script src="assets/js/pipeline.js"></script>
</body>
</html>
