<?php
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../includes/db.php';
$___logo_url = null; $___company_name = 'SW Granite';
$___db = db();
$___has_logo = false;
$___chk = $___db->query("SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='".$___db->real_escape_string(DB_NAME)."' AND TABLE_NAME='shop_settings' AND COLUMN_NAME='logo_url' LIMIT 1");
if ($___chk && $___chk->fetch_row()) { $___has_logo = true; }
$___sql = $___has_logo ? 'SELECT logo_url, company_name FROM shop_settings LIMIT 1' : 'SELECT company_name FROM shop_settings LIMIT 1';
$___res = $___db->query($___sql);
if ($___res) {
  $___row = $___res->fetch_assoc();
  if ($___row){
    if ($___has_logo && !empty($___row['logo_url'])) $___logo_url = $___row['logo_url'];
    if (!empty($___row['company_name'])) $___company_name = $___row['company_name'];
  }
}
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>SW Granite</title>
  <link rel="icon" type="image/x-icon" href="<?php echo url_for('assets/uploads/favicon.png'); ?>">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">
  <link href="<?php echo url_for('assets/css/styles.css'); ?>" rel="stylesheet">
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
  <script src="<?php echo url_for('assets/js/app.js'); ?>" defer></script>
</head>
<body>
  <header class="app-header">
    <div class="d-flex align-items-center justify-content-between">
      <div class="brand d-flex align-items-center">
        <button id="btnSidebarToggle" class="btn btn-sm btn-outline-secondary me-2" type="button" title="Toggle menu" aria-label="Toggle menu">
          <i class="bi bi-list"></i>
        </button>
        <?php if (!empty($___logo_url)): ?>
          <img src="<?php echo htmlspecialchars($___logo_url); ?>" alt="Logo" style="height:60px;" class="me-2">
        <?php else: ?>
          <i class="bi bi-gem me-2"></i> SW Granite
        <?php endif; ?>
      </div>
      <div class="d-flex align-items-center gap-3">
        <ul class="nav nav-tabs border-0">
          <li class="nav-item"><a class="nav-link" href="<?php echo url_for('index.php?page=dashboard'); ?>">Dashboard</a></li>
          <li class="nav-item"><a class="nav-link" href="<?php echo url_for('index.php?page=expenditures'); ?>">Expenditures</a></li>
          <li class="nav-item"><a class="nav-link" href="<?php echo url_for('index.php?page=payroll'); ?>">Payroll</a></li>
        </ul>
        <button id="btnLicAlerts" class="btn btn-sm btn-outline-danger position-relative" title="License alerts">
          <i class="bi bi-exclamation-triangle"></i>
          <span id="licAlertsBadge" class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger d-none">0</span>
        </button>
        <button id="btnAlerts" class="btn btn-sm btn-outline-secondary position-relative" title="Invoice alerts">
          <i class="bi bi-bell"></i>
          <span id="alertsBadge" class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger d-none">0</span>
        </button>
        <div class="dropdown">
          <button class="btn btn-sm btn-outline-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">
            <i class="bi bi-person-circle me-1"></i>
            <span class="user-name"><?php echo htmlspecialchars((current_user()['full_name'] ?? current_user()['username'] ?? 'User')); ?></span>
          </button>
          <ul class="dropdown-menu dropdown-menu-end">
            <li><h6 class="dropdown-header"><?php echo htmlspecialchars(current_user()['username'] ?? ''); ?></h6></li>
            <li><a class="dropdown-item" href="<?php echo url_for('index.php?page=profile'); ?>"><i class="bi bi-gear me-2"></i>Profile</a></li>
            <li><hr class="dropdown-divider"></li>
            <li><a class="dropdown-item text-danger" href="<?php echo url_for('logout.php'); ?>"><i class="bi bi-box-arrow-right me-2"></i>Logout</a></li>
          </ul>
        </div>
      </div>
    </div>
  </header>

  <!-- Global Toast Container -->
  <div id="appToastContainer" class="toast-container position-fixed top-0 end-0 p-3" style="z-index: 1080;"></div>
  <script>
  (function(){
    function makeToast(title, body){
      const id = 't'+Math.random().toString(36).slice(2);
      const el = document.createElement('div');
      el.className = 'toast align-items-center text-bg-light border-0 show';
      el.id = id;
      el.setAttribute('role','alert'); el.setAttribute('aria-live','assertive'); el.setAttribute('aria-atomic','true');
      el.innerHTML = '<div class="d-flex"><div class="toast-body">'+body+'</div><button type="button" class="btn-close me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button></div>';
      document.getElementById('appToastContainer').appendChild(el);
      const inst = bootstrap.Toast.getOrCreateInstance(el, { delay: 6000 }); inst.show();
    }
    function loadAlerts(){
      // Next week due invoices (based on due date)
      const p1 = $.get('api/reports.php', { action:'outstanding', next_week:1, from:'1970-01-01', to:'2999-12-31' });
      // Invoices older than 7 days from invoice date and still unpaid
      const p2 = $.get('api/reports.php', { action:'outstanding', overdue_invoice_days:7, from:'1970-01-01', to:'2999-12-31' });
      // Expired company licenses
      const p3 = $.get('api/company_licenses.php', { action:'expired_summary' });

      $.when(p1, p2, p3).done(function(a,b,c){
        const nextRows = (a[0] && a[0].data) || []; const overRows = (b[0] && b[0].data) || [];
        const total = nextRows.length + overRows.length;
        const badge = document.getElementById('alertsBadge');
        if (total>0){ badge.textContent = total; badge.classList.remove('d-none'); }
        if (nextRows.length>0){
          makeToast('Alerts', nextRows.length+ ' invoice(s) due in next 7 days. <a href="<?php echo url_for('index.php?page=reports'); ?>#rpt-out" class="text-decoration-underline">View Outstanding</a>');
        }
        if (overRows.length>0){
          makeToast('Alerts', overRows.length+ ' invoice(s) older than 7 days and unpaid. <a href="<?php echo url_for('index.php?page=reports'); ?>#rpt-out" class="text-decoration-underline">View Outstanding</a>');
        }
        // On bell click, open reports Outstanding tab
        document.getElementById('btnAlerts')?.addEventListener('click', function(){ window.location.href = '<?php echo url_for('index.php?page=reports'); ?>'; });

        const licData = c[0] || {};
        const licCount = licData.count ? parseInt(licData.count, 10) : 0;
        const licBadge = document.getElementById('licAlertsBadge');
        const licBtn = document.getElementById('btnLicAlerts');
        if (licCount > 0){
          licBadge.textContent = licCount;
          licBadge.classList.remove('d-none');
          licBtn?.classList.remove('d-none');
        } else {
          // hide entire button if nothing expired
          licBtn?.classList.add('d-none');
        }
        licBtn?.addEventListener('click', function(){
          window.location.href = '<?php echo url_for('index.php?page=company_licenses'); ?>';
        });
      });
    }
    // Load after page ready
    if (window.jQuery) { $(loadAlerts); } else { document.addEventListener('DOMContentLoaded', loadAlerts); }
  })();
  </script>
