<?php
session_start();
include 'forms/db_connect.php'; 
$current_page = basename($_SERVER['PHP_SELF']);

if (!isset($_SESSION['id_user'])) {
    header('Location: forms/login.php');
    exit;
}

$full_name = $_SESSION['full_name'] ?? 'Invité';
$result = $conn->query("SELECT COUNT(*) AS total FROM employes");

if (!$result) {
    die("Erreur SQL : " . $conn->error); 
}

$employeesCount = $result->fetch_assoc()['total'] ?? 0;

$result = $conn->query("SELECT COUNT(*) AS total FROM citizens");

if (!$result) {
    die("Erreur SQL sur citizens: " . $conn->error);
}

$citizensCount = $result->fetch_assoc()['total'] ?? 0;

$result = $conn->query("SELECT COUNT(*) AS total FROM departments");

if (!$result) {
    die("Erreur SQL sur citizens: " . $conn->error);
}

$departmentsCount = $result->fetch_assoc()['total'] ?? 0;

$result = $conn->query("SELECT COUNT(*) AS total FROM incident");

if (!$result) {
    die("Erreur SQL sur citizens: " . $conn->error);
}

$incidentsCount = $result->fetch_assoc()['total'] ?? 0;


$typesOfIncidentsCount = 2;
$selectedYear = isset($_GET['year']) ? (int)$_GET['year'] : date('Y'); 
$selectedMonth = isset($_GET['month']) ? (int)$_GET['month'] : 0;    

$labels = [];
$totals = [];
$limit = $selectedMonth ? 20 : 200;

$sql = "
    SELECT c.full_name, COUNT(i.id_incident) AS total_incidents
    FROM citizens c
    LEFT JOIN incident i 
      ON c.id_citizen = i.ditNavn
     AND YEAR(i.dato) = ?
";

$params = [$selectedYear];
$types = "i";

if ($selectedMonth) {
    $sql .= " AND MONTH(i.dato) = ? ";
    $params[] = $selectedMonth;
    $types .= "i";
}

$sql .= " 
    GROUP BY c.id_citizen
    ORDER BY total_incidents DESC
    LIMIT $limit
";
$stmt = $conn->prepare($sql);
if (!$stmt) die("Erreur SQL: " . $conn->error);


if (count($params) > 0) $stmt->bind_param($types, ...$params);

$stmt->execute();
$result = $stmt->get_result();

if ($result && $result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $labels[] = $row['full_name'];
        $totals[] = (int)$row['total_incidents'];
    }
} else {
    $labels = ["Aucun citoyen"];
    $totals = [0];
}

$labelsJSON = json_encode($labels);
$totalsJSON = json_encode($totals);

$stmt->close();

$selectedYearEmp = isset($_GET['year']) ? (int)$_GET['year'] : date('Y');
$selectedMonthEmp = isset($_GET['month']) ? (int)$_GET['month'] : 0;

$labelsEmp = [];
$totalsEmp = [];
$limitEmp = $selectedMonthEmp ? 20 : 200;

$sqlEmp = "
    SELECT e.full_name, COUNT(i.id_incident) AS total_incidents
    FROM employes e
    LEFT JOIN incident i 
      ON e.id_employe = i.overfaldsNavn
     AND YEAR(i.dato) = ?
";

$paramsEmp = [$selectedYearEmp];
$typesEmp = "i";

if ($selectedMonthEmp) {
    $sqlEmp .= " AND MONTH(i.dato) = ? ";
    $paramsEmp[] = $selectedMonthEmp;
    $typesEmp .= "i";
}

$sqlEmp .= " GROUP BY e.id_employe ORDER BY total_incidents DESC LIMIT $limitEmp";

$stmtEmp = $conn->prepare($sqlEmp);
if (!$stmtEmp) die("Erreur SQL: " . $conn->error);
$stmtEmp->bind_param($typesEmp, ...$paramsEmp);
$stmtEmp->execute();
$resultEmp = $stmtEmp->get_result();

while ($row = $resultEmp->fetch_assoc()) {
    $labelsEmp[] = $row['full_name'];
    $totalsEmp[] = (int)$row['total_incidents'];
}

$labelsEmpJSON = json_encode($labelsEmp);
$totalsEmpJSON = json_encode($totalsEmp);

$stmtEmp->close();
if (isset($_GET['action']) && $_GET['action'] === 'get_emp_citizen_stats') {
    header('Content-Type: application/json; charset=utf-8');

    $year = isset($_GET['year']) ? (int)$_GET['year'] : date('Y');
    $month = isset($_GET['month']) ? (int)$_GET['month'] : 0;

    $sql = "
        SELECT e.full_name AS employee_name, c.full_name AS citizen_name, COUNT(i.id_incident) AS total
        FROM incident i
        LEFT JOIN employes e ON i.overfaldsNavn = e.id_employe
        LEFT JOIN citizens c ON i.ditNavn = c.id_citizen
        WHERE YEAR(i.dato) = ?
    ";
    $params = [$year];
    $types = "i";

    if ($month) {
        $sql .= " AND MONTH(i.dato) = ?";
        $params[] = $month;
        $types .= "i";
    }

    $sql .= " GROUP BY e.id_employe, c.id_citizen ORDER BY e.full_name, c.full_name";

    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        echo json_encode(['error' => 'Erreur SQL: ' . $conn->error]);
        exit;
    }

    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $result = $stmt->get_result();

    $employees = [];
    $citizensSet = [];

    while ($row = $result->fetch_assoc()) {
        $emp = $row['employee_name'] ?? 'Ukendt medarbejder';
        $cit = $row['citizen_name'] ?? 'Ukendt borger';
        $total = (int)$row['total'];

        if (!isset($employees[$emp])) $employees[$emp] = [];
        $employees[$emp][$cit] = $total;
        if ($cit) $citizensSet[$cit] = true;
    }

    $labelsEmployees = array_keys($employees);
    $citizens = array_keys($citizensSet);

    $datasets = [];
    foreach ($citizens as $citizen) {
        $data = [];
        foreach ($labelsEmployees as $emp) {
            $data[] = $employees[$emp][$citizen] ?? 0;
        }
        $datasets[] = [
            'label' => $citizen,
            'data' => $data,
            'backgroundColor' => sprintf('rgba(%d,%d,%d,0.6)', rand(50,200), rand(50,200), rand(50,200)),
            'borderColor' => '#e731c0ff',
            'borderWidth' => 1
        ];
    }

    echo json_encode([
        'labels' => $labelsEmployees,
        'datasets' => $datasets
    ], JSON_UNESCAPED_UNICODE);

    exit;
}   
 if (isset($_GET['action']) && $_GET['action'] === 'get_department_stats') {
    $year = isset($_GET['year']) ? (int)$_GET['year'] : date('Y');
    $month = isset($_GET['month']) ? (int)$_GET['month'] : 0;

    $sql = "SELECT d.name, COUNT(i.id_incident) AS total
            FROM departments d
            INNER JOIN citizens e ON d.id_department = e.department
            INNER JOIN incident i ON i.ditNavn = e.id_citizen
            WHERE YEAR(i.dato) = ?";
    $params = [$year];
    $types = "i";

    if ($month) {
        $sql .= " AND MONTH(i.dato) = ? ";
        $params[] = $month;
        $types .= "i";
    }

    $sql .= " GROUP BY d.id_department ORDER BY total DESC";

    $stmt = $conn->prepare($sql);
    if ($stmt) {
        $stmt->bind_param($types, ...$params);
        $stmt->execute();
        $res = $stmt->get_result();

        $labels = [];
        $totals = [];
        while ($row = $res->fetch_assoc()) {
            $labels[] = $row['name'];
            $totals[] = (int)$row['total'];
        }

        header('Content-Type: application/json');
        echo json_encode(['labels' => $labels, 'totals' => $totals]);
    } else {
        echo json_encode(['error' => $conn->error]);
    }
    exit;
}


$selectedYear = date('Y');

if (isset($_GET['action']) && $_GET['action'] === 'get_department_stats') {
    header('Content-Type: application/json; charset=utf-8');

    $year = isset($_GET['year']) ? (int)$_GET['year'] : date('Y');
    $month = isset($_GET['month']) ? (int)$_GET['month'] : 0;

    $sql = "SELECT d.name, COUNT(i.id_incident) AS total
            FROM departments d
            INNER JOIN citizens e ON d.id_department = e.department
            INNER JOIN incident i ON i.ditNavn = e.id_citizen
            WHERE YEAR(i.dato) = ?";
    $params = [$year];
    $types = "i";

    if ($month) {
        $sql .= " AND MONTH(i.dato) = ? ";
        $params[] = $month;
        $types .= "i";
    }

    $sql .= " GROUP BY d.id_department ORDER BY total DESC LIMIT 10";

    $stmt = $conn->prepare($sql);
    if ($stmt) {
        $stmt->bind_param($types, ...$params);
        $stmt->execute();
        $res = $stmt->get_result();

        $labels = [];
        $totals = [];
        while ($row = $res->fetch_assoc()) {
            $labels[] = $row['name'];
            $totals[] = (int)$row['total'];
        }

        echo json_encode(['labels' => $labels, 'totals' => $totals]);
    } else {
        echo json_encode(['error' => $conn->error]);
    }
    exit;
}
if (isset($_GET['type']) && !empty($_GET['type'])) {
    header('Content-Type: application/json');

    $type = $_GET['type'];

    if (!$conn) {
        echo json_encode(['error' => 'Erreur de connexion à la base']);
        exit;
    }


    $stmt = mysqli_prepare($conn, "
        SELECT c.full_name AS borger, COUNT(*) AS antal
        FROM incident i
        JOIN citizens c ON i.ditNavn = c.id_citizen
        WHERE CONCAT(';', REPLACE(i.fysiskVold, ' ', ''), ';') LIKE CONCAT('%;', REPLACE(?, ' ', ''), ';%')
        GROUP BY c.full_name
        ORDER BY antal DESC
    ");

    if ($stmt) {
        mysqli_stmt_bind_param($stmt, "s", $type);
        mysqli_stmt_execute($stmt);
        $result = mysqli_stmt_get_result($stmt);

        $labels = [];
        $values = [];

        while ($row = mysqli_fetch_assoc($result)) {
            $labels[] = $row['borger'];
            $values[] = $row['antal'];
        }

        echo json_encode(['labels' => $labels, 'values' => $values]);
        mysqli_stmt_close($stmt);
    } else {
        echo json_encode(['error' => 'Erreur préparation requête SQL']);
    }

    exit;
}

if (isset($_GET['typeVold']) && !empty($_GET['typeVold'])) {
    header('Content-Type: application/json');

    $typeVold = $_GET['typeVold'];

    if (!$conn) {
        echo json_encode(['error' => 'Erreur de connexion à la base']);
        exit;
    }

    $stmt = mysqli_prepare($conn, "
        SELECT c.full_name AS borger, COUNT(*) AS antal
        FROM incident i
        JOIN citizens c ON i.ditNavn = c.id_citizen
        WHERE CONCAT(';', REPLACE(i.psykiskVold, ' ', ''), ';') LIKE CONCAT('%;', REPLACE(?, ' ', ''), ';%')
        GROUP BY c.full_name
        ORDER BY antal DESC
    ");

    if ($stmt) {
        mysqli_stmt_bind_param($stmt, "s", $typeVold);
        mysqli_stmt_execute($stmt);
        $result = mysqli_stmt_get_result($stmt);

        $labels = [];
        $values = [];

        while ($row = mysqli_fetch_assoc($result)) {
            $labels[] = $row['borger'];
            $values[] = $row['antal'];
        }

        echo json_encode(['labels' => $labels, 'values' => $values]);
        mysqli_stmt_close($stmt);
    } else {
        echo json_encode(['error' => 'Erreur préparation requête SQL']);
    }

    exit;
}
if (isset($_GET['action']) && $_GET['action'] === 'get_employee_stats') {
    $year = isset($_GET['year']) ? (int)$_GET['year'] : date('Y');
    $month = isset($_GET['month']) ? (int)$_GET['month'] : 0;

    $sql = "
        SELECT e.full_name, COUNT(i.id_incident) AS total_incidents
        FROM employes e
        LEFT JOIN incident i 
          ON e.id_employe = i.overfaldsNavn
         AND YEAR(i.dato) = ?
    ";

    $params = [$year];
    $types = "i";

    if ($month) {
        $sql .= " AND MONTH(i.dato) = ? ";
        $params[] = $month;
        $types .= "i";
    }

    $sql .= " GROUP BY e.id_employe ORDER BY total_incidents DESC LIMIT 200";

    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        echo json_encode(['error' => $conn->error]);
        exit;
    }
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $res = $stmt->get_result();

    $labels = [];
    $values = [];
    while ($row = $res->fetch_assoc()) {
        $labels[] = $row['full_name'];
        $values[] = (int)$row['total_incidents'];
    }

    echo json_encode(['labels' => $labels, 'values' => $values]);
    exit;
}
if (isset($_GET['action']) && $_GET['action'] === 'get_citizen_stats') {
    $year = isset($_GET['year']) ? (int)$_GET['year'] : date('Y');
    $month = isset($_GET['month']) ? (int)$_GET['month'] : 0;

    $sql = "
        SELECT c.full_name, COUNT(i.id_incident) AS total_incidents
        FROM citizens c
        LEFT JOIN incident i 
          ON c.id_citizen = i.ditNavn
         AND YEAR(i.dato) = ?
    ";

    $params = [$year];
    $types = "i";

    if ($month) {
        $sql .= " AND MONTH(i.dato) = ? ";
        $params[] = $month;
        $types .= "i";
    }

    $sql .= " 
        GROUP BY c.id_citizen
        ORDER BY total_incidents DESC
        LIMIT 200
    ";

    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        echo json_encode(['error' => $conn->error]);
        exit;
    }

    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $result = $stmt->get_result();

    $labels = [];
    $values = [];

    while ($row = $result->fetch_assoc()) {
        $labels[] = $row['full_name'];
        $values[] = (int)$row['total_incidents'];
    }

    echo json_encode(['labels' => $labels, 'values' => $values]);
    exit;
}

?>




<!DOCTYPE html>
<html lang="en">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <title>Händelserapportering </title>
    <meta
      content="width=device-width, initial-scale=1.0, shrink-to-fit=no"
      name="viewport"
    />

    <script src="assets/js/plugin/webfont/webfont.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

    <script>
      WebFont.load({
        google: { families: ["Public Sans:300,400,500,600,700"] },
        custom: {
          families: [
            "Font Awesome 5 Solid",
            "Font Awesome 5 Regular",
            "Font Awesome 5 Brands",
            "simple-line-icons",
          ],
          urls: ["assets/css/fonts.min.css"],
        },
        active: function () {
          sessionStorage.fonts = true;
        },
      });
    </script>
    <link rel="stylesheet" href="assets/css/bootstrap.min.css" />
    <link rel="stylesheet" href="assets/css/plugins.min.css" />
    <link rel="stylesheet" href="assets/css/kaiadmin.min.css" />

<script src="assets/js/core/jquery-3.7.1.min.js"></script>
<script src="assets/js/core/popper.min.js"></script>
<script src="assets/js/core/bootstrap.min.js"></script>

<script src="assets/js/plugin/jquery-scrollbar/jquery.scrollbar.min.js"></script>

<script src="assets/js/kaiadmin.min.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" rel="stylesheet">
    <style>
.icon-circle {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
}
.card-category {
  font-size: 0.9rem;
  color: #555;
}
.card-title {
  font-size: 1.4rem;
  color: #111;
}
@media(max-width:768px) {
  .card-title { font-size: 1.2rem; }
  .card-category { font-size: 0.8rem; }
  .icon-circle { width:50px; height:50px; }
}
</style>
    <style>
      #dashboardContent {
    width: 100%;
    min-height: 100vh; 
    overflow-y: auto; 
}

    </style>

<style>

@media (max-width: 768px) {
  .navbar-nav.topbar-nav {
    display: flex !important;
    flex-direction: row;
    align-items: center;
    gap: 10px;
  }

  .nav-item.topbar-user {
    display: flex !important;
  }

  .nav-item.topbar-user .avatar-sm {
    width: 32px !important;
    height: 32px !important;
  }

  .nav-item.topbar-user .profile-pic {
    padding: 5px 8px;
  }
  .nav-item.topbar-user .fas.fa-sign-out-alt {
    font-size: 18px;
    color: black;
  }

  .nav-item.topbar-user a:active {
    background: rgba(0,0,0,0.05);
    border-radius: 8px;
  }
}

@media (min-width: 769px) {
  .profile-username {
    margin-left: 8px;
  }
}
</style>
    <link rel="stylesheet" href="assets/css/demo.css" />
  </head>
  <body>
    <div class="wrapper">
      <div class="sidebar" data-background-color="dark">
        <div class="sidebar-logo">
          <div class="logo-header" data-background-color="white">
            <a href="index.html" class="logo">
               Händelserapportering
              
            </a>
            <div class="nav-toggle">
              <button class="btn btn-toggle toggle-sidebar">
                <i class="gg-menu-right"></i>
              </button>
              <button class="btn btn-toggle sidenav-toggler">
                <i class="gg-menu-left"></i>
              </button>
            </div>
            <button class="topbar-toggler more">
              <i class="gg-more-vertical-alt"></i>
            </button>
          </div>
        </div>
        <div class="sidebar-wrapper scrollbar scrollbar-inner">
          <div class="sidebar-content">
            <ul class="nav nav-secondary">
              <li class="nav-item active">
                <a
                  data-bs-toggle="collapse"
                  href="#dashboard"
                  class="collapsed"
                  aria-expanded="false"
                >
                  <i class="fas fa-home"></i>
                  <p>Betjeningspanel</p>
                
                </a>
            
              </li>
              <li class="nav-item">
  <a href="#" id="loadDepartments">
    <i class="fas fa-building"></i>
    <p>Afdelinger</p>
  </a>
</li>


              <li class="nav-item">
  <a href="#" id="loadEmployees">
    <i class="fas fa-user-tie"></i>
    <p>Medarbejdere</p>
  </a>
</li>



              <li class="nav-item">
  <a href="#" id="loadCitizens">
    <i class="fas fa-users"></i>
    <p>Borgere</p>
  </a>
</li>

              <li class="nav-item">
  <a href="#" id="loadIncidents">
    <i class="fas fa-exclamation-triangle"></i>
    <p>Hændelser</p>
  </a>
</li>
<li class="nav-item">
  <a href="#" id="loadHistoryEmploye">
    <i class="fa-solid fa-user-clock"></i>
    <p>Medarbejderhistorik</p>
  </a>
</li>

<li class="nav-item">
  <a href="#" id="loadHistoryCitizen">
    <i class="fa-solid fa-users-gear"></i>
    <p>Borgerhistorik</p>
  </a>
</li>
            </ul>
          </div>
        </div>
      </div>
      <div class="main-panel">
        <div class="main-header">
          <div class="main-header-logo">
            <div class="logo-header" data-background-color="white">
              <a href="index.html" class="logo">
                 Händelserapportering
               
              </a>
              <div class="nav-toggle">
                <button class="btn btn-toggle toggle-sidebar">
                  <i class="gg-menu-right"></i>
                </button>
                <button class="btn btn-toggle sidenav-toggler">
                  <i class="gg-menu-left"></i>
                </button>
              </div>
              <button class="topbar-toggler more">
                <i class="gg-more-vertical-alt"></i>
              </button>
            </div>
          </div>
          <nav class="navbar navbar-header navbar-header-transparent navbar-expand-lg border-bottom">
  <div class="container-fluid">
    <nav class="navbar navbar-header-left navbar-expand-lg navbar-form nav-search p-0 d-none d-lg-flex">
    </nav>

    <ul class="navbar-nav topbar-nav ms-md-auto align-items-center">
<li class="nav-item topbar-user dropdown hidden-caret">
  <a class="dropdown-toggle profile-pic" 
     data-bs-toggle="dropdown" 
     href="#" 
     aria-expanded="false"
     data-bs-placement="bottom"
     data-bs-toggle="tooltip"
     data-bs-title="Hej, <?php echo htmlspecialchars($full_name); ?>"
     title="Hej, <?php echo htmlspecialchars($full_name); ?>">
    
    <div class="avatar-sm" style="width:30px; height:30px;">
      <img src="assets/img/humain.png" 
           alt="User" 
           class="avatar-img rounded-circle" 
           style="width:100%; height:100%; object-fit:cover;" />
    </div>
    <span class="profile-username d-none d-md-inline">
      <span class="op-7">Hej,</span>
      <span class="fw-bold"><?php echo htmlspecialchars($full_name); ?></span>
    </span>

    <span class="tooltip-indicator d-md-none"></span>
  </a>
</li>

<style>

@media (max-width: 768px) {

  .nav-item.topbar-user .avatar-sm {
    position: relative;
    transition: transform 0.3s ease;
  }

  .nav-item.topbar-user .profile-pic:hover .avatar-sm,
  .nav-item.topbar-user .profile-pic:active .avatar-sm {
    transform: scale(1.1);
  }

  .tooltip {
    font-size: 13px !important;
  }

  .tooltip-inner {
    background-color: rgba(0, 0, 0, 0.9) !important;
    padding: 8px 12px !important;
    border-radius: 8px !important;
    font-weight: 500;
    box-shadow: 0 4px 12px rgba(0,0,0,0.3);
  }

  .tooltip-arrow {
    display: none; 
  }

  .tooltip-indicator {
    position: absolute;
    width: 8px;
    height: 8px;
    background: #4CAF50;
    border-radius: 50%;
    bottom: 0;
    right: 0;
    border: 2px solid white;
    animation: pulse 2s infinite;
  }

  @keyframes pulse {
    0%, 100% { opacity: 1; }
    50% { opacity: 0.5; }
  }


  .nav-item.topbar-user .profile-pic:active {
    background: rgba(0,0,0,0.05);
    border-radius: 12px;
  }
}


@media (min-width: 769px) {
  .tooltip-indicator {
    display: none !important;
  }
}
</style>

<style>
.custom-mobile-tooltip {
  background: rgba(0, 0, 0, 0.9);
  color: white;
  padding: 10px 16px;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  box-shadow: 0 4px 12px rgba(0,0,0,0.3);
  white-space: nowrap;
  opacity: 1;
  transition: opacity 0.3s ease;
  pointer-events: none;
}

.custom-mobile-tooltip::before {
  content: '';
  position: absolute;
  top: -6px;
  left: 50%;
  transform: translateX(-50%);
  width: 0;
  height: 0;
  border-left: 6px solid transparent;
  border-right: 6px solid transparent;
  border-bottom: 6px solid rgba(0, 0, 0, 0.9);
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateX(-50%) translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateX(-50%) translateY(0);
  }
}

.custom-mobile-tooltip {
  animation: fadeInUp 0.3s ease;
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {

  const isMobile = window.innerWidth < 769;
  
  if (isMobile) {

    const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    const tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
      return new bootstrap.Tooltip(tooltipTriggerEl, {
        trigger: 'hover focus', 
        placement: 'bottom',
        offset: [0, 10]
      });
    });

    
    const avatarLink = document.querySelector('.nav-item.topbar-user .profile-pic');
    let customTooltip = null;

    avatarLink?.addEventListener('click', function(e) {
      
      if (window.innerWidth < 769) {
        e.preventDefault();
        
        
        if (customTooltip && customTooltip.parentNode) {
          customTooltip.remove();
          customTooltip = null;
        } else {
          showCustomTooltip(this);
        }
      }
    });

    function showCustomTooltip(element) {
      const userName = "<?php echo htmlspecialchars($full_name); ?>";
      
      
      customTooltip = document.createElement('div');
      customTooltip.className = 'custom-mobile-tooltip';
      customTooltip.innerHTML = `<strong>Hej, ${userName}</strong>`;
      
      
      document.body.appendChild(customTooltip);
      
      const rect = element.getBoundingClientRect();
      customTooltip.style.position = 'fixed';
      customTooltip.style.top = (rect.bottom + 10) + 'px';
      customTooltip.style.left = (rect.left + rect.width / 2) + 'px';
      customTooltip.style.transform = 'translateX(-50%)';
      customTooltip.style.zIndex = '9999';
      
     
      setTimeout(() => {
        if (customTooltip && customTooltip.parentNode) {
          customTooltip.style.opacity = '0';
          setTimeout(() => customTooltip.remove(), 300);
        }
      }, 3000);
    }

    
    document.addEventListener('click', function(e) {
      if (customTooltip && !e.target.closest('.nav-item.topbar-user')) {
        customTooltip.remove();
        customTooltip = null;
      }
    });
  }
});
</script>


     
      <li class="nav-item topbar-user">
        <a href="forms/logout.php" class="profile-pic d-flex align-items-center" title="Log ud">
          
          <span class="fw-bold d-none d-md-inline">Log ud</span>
        
          <i class="fas fa-sign-out-alt ms-1"></i>
        </a>
      </li>

    </ul>
  </div>
</nav>
        </div>

        <div class="container">
  <div class="page-inner" id="dashboardContent">
    <h3 class="fw-bold mb-4">Betjeningspanel</h3>

    <div class="d-flex justify-content-between flex-wrap gap-3">

      <div class="card flex-fill shadow-sm rounded-4" style="min-width: 200px;">
        <div class="card-body d-flex align-items-center p-3">
          <div class="icon-circle me-3" style="background-color:#3498db; width:30px; height:30px; border-radius:50%; display:flex; align-items:center; justify-content:center;">
            <i class="fas fa-users text-white fa-sm"></i>
          </div>
          <div>
            <p class="card-category mb-0 fw-semibold small">Medarbejdere</p>
            <h4 class="card-title mb-0"><?php echo $employeesCount; ?></h4>
          </div>
        </div>
      </div>
      <div class="card flex-fill shadow-sm rounded-4" style="min-width: 200px;">
        <div class="card-body d-flex align-items-center p-3">
          <div class="icon-circle me-3" style="background-color:#9b59b6; width:30px; height:30px; border-radius:50%; display:flex; align-items:center; justify-content:center;">
            <i class="fas fa-user text-white fa-sm"></i>
          </div>
          <div>
            <p class="card-category mb-0 fw-semibold small">Borgere</p>
            <h4 class="card-title mb-0"><?php echo $citizensCount; ?></h4>
          </div>
        </div>
      </div>

      <div class="card flex-fill shadow-sm rounded-4" style="min-width: 200px;">
        <div class="card-body d-flex align-items-center p-3">
          <div class="icon-circle me-3" style="background-color:#f1c40f; width:30px; height:30px; border-radius:50%; display:flex; align-items:center; justify-content:center;">
            <i class="fas fa-building text-white fa-sm"></i>
          </div>
          <div>
            <p class="card-category mb-0 fw-semibold small">Afdelinger</p>
            <h4 class="card-title mb-0"><?php echo $departmentsCount; ?></h4>
          </div>
        </div>
      </div>

      <div class="card flex-fill shadow-sm rounded-4" style="min-width: 200px;">
        <div class="card-body d-flex align-items-center p-3">
          <div class="icon-circle me-3" style="background-color:#e74c3c; width:30px; height:30px; border-radius:50%; display:flex; align-items:center; justify-content:center;">
            <i class="fas fa-exclamation-triangle text-white fa-sm"></i>
          </div>
          <div>
            <p class="card-category mb-0 fw-semibold small">Hændelser</p>
            <h4 class="card-title mb-0"><?php echo $incidentsCount; ?></h4>
          </div>
        </div>
      </div>
      <div class="card flex-fill shadow-sm rounded-4" style="min-width: 200px;">
        <div class="card-body d-flex align-items-center p-3">
          <div class="icon-circle me-3" style="background-color:#2ecc71; width:30px; height:30px; border-radius:50%; display:flex; align-items:center; justify-content:center;">
            <i class="fas fa-tags text-white fa-sm"></i>
          </div>
          <div>
            <p class="card-category mb-0 fw-semibold small">Typer af hændelser</p>
            <h4 class="card-title mb-0"><?php echo $typesOfIncidentsCount; ?></h4>
          </div>
        </div>
      </div>
    </div> 
    <?php if ($current_page === 'index.php'): ?>
<div class="row mt-4">
  <div class="col-12">
    <div class="card shadow-sm border-0 rounded-4">
      <div class="card-header text-white py-3 px-4 d-flex justify-content-between align-items-center" style="background-color: #22a5e2ff;">
        <h5 class="card-title mb-0">Antal hændelser pr. borger</h5>
        <form id="filterCitizen" class="d-flex gap-2 align-items-center mb-0" method="GET">
          <div>
            <label for="year_citizen" class="form-label fw-semibold mb-0">År</label>
            <select name="year" id="year_citizen" class="form-select form-select-sm shadow-sm">
              <?php 
              $startYear = 2020;
              $endYear = 2030;
              
              
              for($y = $startYear; $y <= $endYear; $y++): ?>
                <option value="<?= $y ?>" <?= ($selectedYear == $y ? 'selected' : '') ?>><?= $y ?></option>
              <?php endfor; ?>
            </select>
          </div>
          <div>
            <label for="month_citizen" class="form-label fw-semibold mb-0">Måned</label>
            <select name="month" id="month_citizen" class="form-select form-select-sm shadow-sm">
              <option value="0" <?= ($selectedMonth == 0 ? 'selected' : '') ?>>Alle</option>
              <?php for($m = 1; $m <= 12; $m++): ?>
                <option value="<?= $m ?>" <?= ($selectedMonth == $m ? 'selected' : '') ?>><?= str_pad($m, 2, '0', STR_PAD_LEFT) ?></option>
              <?php endfor; ?>
            </select>
          </div>
          <div>
            <button type="submit" class="btn btn-light btn-sm mt-4">
              <i class="bi bi-funnel-fill me-1"></i> Filtrér
            </button>
          </div>
        </form>
      </div>
      <div class="card-body p-4">
        <div class="chart-container p-3" style="min-height: 450px; background: #f9f9f9; border-radius: 15px;">
          <canvas id="statisticsChart1"></canvas>
        </div>
      </div>
    </div>
  </div>
</div>


<div class="row mt-4">
  <div class="col-12">
    <div class="card shadow-sm border-0 rounded-4">
      <div class="card-header text-white py-3 px-4 d-flex justify-content-between align-items-center" style="background-color: #0fa175ff;">
        <h5 class="card-title mb-0">Antal hændelser pr. medarbejder</h5>
        <form id="filterEmployee" class="d-flex gap-2 align-items-center mb-0">
          <div>
            
            <label for="year_emp" class="form-label fw-semibold mb-0">År</label>
            <select id="year_emp" class="form-select form-select-sm shadow-sm">
              <?php 
              $startYear = 2020;
              $endYear = 2030;
              for($y = $startYear; $y <= $endYear; $y++): ?>
                <option value="<?= $y ?>" <?= ($selectedYearEmp == $y ? 'selected' : '') ?>><?= $y ?></option>
              <?php endfor; ?>
            </select>
          </div>
          <div>
            <label for="month_emp" class="form-label fw-semibold mb-0">Måned</label>
            <select id="month_emp" class="form-select form-select-sm shadow-sm">
              <option value="0" <?= ($selectedMonthEmp == 0 ? 'selected' : '') ?>>Alle</option>
              <?php for($m = 1; $m <= 12; $m++): ?>
                <option value="<?= $m ?>" <?= ($selectedMonthEmp == $m ? 'selected' : '') ?>><?= str_pad($m,2,'0',STR_PAD_LEFT) ?></option>
              <?php endfor; ?>
            </select>
          </div>
          <div>
            <button type="submit" class="btn btn-light btn-sm mt-4">
              <i class="bi bi-funnel-fill me-1"></i> Filtrér
            </button>
          </div>
        </form>
      </div>

      <div class="card-body p-4">
        <div class="chart-container p-3" style="min-height: 450px; background: #f9f9f9; border-radius: 15px;">
          <canvas id="statisticsChart2"></canvas>
        </div>
      </div>
    </div>
  </div>
</div>



<div class="row mt-4">
  <div class="col-12">
    <div class="card shadow-sm border-0 rounded-4">
      <div class="card-header text-white py-3 px-4 d-flex justify-content-between align-items-center" style="background-color: #b72ec9ff;">
        <h5 class="card-title mb-0">Hændelser pr. medarbejder og borger</h5>
        <form id="filterEmpCitizen" class="d-flex gap-2 align-items-center mb-0">
          <div>
            <label for="year_emp_citizen" class="form-label fw-semibold mb-0">År</label>
            <select id="year_emp_citizen" class="form-select form-select-sm shadow-sm">
              <?php 
               $startYear = 2020;
              $endYear = 2030;
              for($y = $startYear; $y <= $endYear; $y++): ?>
                <option value="<?= $y ?>"><?= $y ?></option>
              <?php endfor; ?>
            </select>
          </div>
          <div>
            <label for="month_emp_citizen" class="form-label fw-semibold mb-0">Måned</label>
            <select id="month_emp_citizen" class="form-select form-select-sm shadow-sm">
              <option value="0">Alle</option>
              <?php for($m = 1; $m <= 12; $m++): ?>
                <option value="<?= $m ?>"><?= str_pad($m,2,'0',STR_PAD_LEFT) ?></option>
              <?php endfor; ?>
            </select>
          </div>
          <div>
            <button type="submit" class="btn btn-light btn-sm mt-4">
              <i class="bi bi-funnel-fill me-1"></i> Filtrér
            </button>
          </div>
        </form>
      </div>

      <div class="card-body p-4">
        <div class="chart-container p-3" style="min-height: 450px; background: #f9f9f9; border-radius: 15px;">
          <canvas id="chartEmpCitizen"></canvas>
        </div>
      </div>
    </div>
  </div>
</div>



 <div class="row mt-4">
  <div class="col-12">
    <div class="card shadow-sm border-0 rounded-4">
      <div class="card-header text-white py-3 px-4 d-flex justify-content-between align-items-center" style="background-color: #FF69B4;">

        <h5 class="card-title mb-0">Hændelser pr. afdeling</h5>
        <form id="filterDepartment" class="d-flex gap-2 align-items-center mb-0">
          <div>
            <label for="year_department" class="form-label fw-semibold mb-0">År</label>
            <select id="year_department" class="form-select form-select-sm shadow-sm">
              <?php 
              $startYear = 2020;
              $endYear = 2030;
              for($y = $startYear; $y <= $endYear; $y++): ?>
                <option value="<?= $y ?>"><?= $y ?></option>
              <?php endfor; ?>
            </select>
          </div>
          <div>
            <label for="month_department" class="form-label fw-semibold mb-0">Måned</label>
            <select id="month_department" class="form-select form-select-sm shadow-sm">
              <option value="0">Alle</option>
              <?php for($m = 1; $m <= 12; $m++): ?>
                <option value="<?= $m ?>"><?= str_pad($m,2,'0',STR_PAD_LEFT) ?></option>
              <?php endfor; ?>
            </select>
          </div>
          <div>
            <button type="submit" class="btn btn-light btn-sm mt-4">
              <i class="bi bi-funnel-fill me-1"></i> Filtrér
            </button>
          </div>
        </form>
      </div>

      <div class="card-body p-4">
        <div class="chart-container p-3" style="min-height: 450px; background: #f9f9f9; border-radius: 15px;">
          <canvas id="chartDepartment"></canvas>
        </div>
      </div>
    </div>
  </div>
</div>

  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

  <div class="row mt-4">
  <div class="col-12">
    <div class="card shadow-sm border-0 rounded-4">
      <div class="card-header text-white py-3 px-4 d-flex justify-content-between align-items-center" style="background-color: #aa9414ff;">
        <h5 class="card-title mb-0">Borger pr. Psykisk Vold</h5>
        <form id="filterPsykisk" class="d-flex gap-2 align-items-center mb-0">
          <div>
            <label for="psyOption" class="form-label fw-semibold mb-0">Psykisk Vold</label>
            <select id="psyOption" class="form-select form-select-sm shadow-sm">
              <?php 
              $psyOptions = ["Råb, skrig","Truende adfærd","Verbale trusler, tilråb, overfusning","Trusler om fysisk vold","Seksuelle krænkelser","Andet"];
              foreach($psyOptions as $option): ?>
                <option value="<?= $option ?>"><?= $option ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div>
            <button type="submit" class="btn btn-light btn-sm mt-4">
              <i class="bi bi-funnel-fill me-1"></i> Filtrér
            </button>
          </div>
        </form>
      </div>
      <div class="card-body p-4">
        <div class="chart-container p-3" style="min-height: 450px; background: #f9f9f9; border-radius: 15px;">
          <canvas id="chartPsykisk"></canvas>
        </div>
      </div>
    </div>
  </div>
</div>
<div class="row mt-4">
  <div class="col-12">
    <div class="card shadow-sm border-0 rounded-4">
      <div class="card-header bg-primary text-white py-3 px-4 d-flex justify-content-between align-items-center">
        <h5 class="card-title mb-0">Borger pr. Fysisk vold</h5>
        <form id="filterFysisk" class="d-flex gap-2 align-items-center mb-0">
          <div>
            <label for="fysOption" class="form-label fw-semibold mb-0">Fysisk Vold</label>
            <select id="fysOption" class="form-select form-select-sm shadow-sm">
              <?php 
              $fysOptions = ["Slag","Spark","Bid, riv, niv","Krads","Spyttet på","Nikket en skalle","Kast med genstand, inventar, bestik e.lign.","Andet"];
              foreach($fysOptions as $option): ?>
                <option value="<?= $option ?>"><?= $option ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div>
            <button type="submit" class="btn btn-light btn-sm mt-4">
              <i class="bi bi-funnel-fill me-1"></i> Filtrér
            </button>
          </div>
        </form>
      </div>

      <div class="card-body p-4">
        <div class="chart-container p-3" style="min-height: 450px; background: #f9f9f9; border-radius: 15px;">
          <canvas id="chartFysisk"></canvas>
        </div>
      </div>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
const ctxFys = document.getElementById('chartFysisk').getContext('2d');
let chartFysisk = new Chart(ctxFys, {
    type: 'bar',
    data: {
        labels: [],
        datasets: [{
            label: 'Antal hændelser',
            data: [],
            backgroundColor: 'rgba(33, 102, 206, 0.6)',
            borderColor: 'rgba(21, 6, 59, 1)',
            borderWidth: 1
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        scales: { y: { beginAtZero: true } }
    }
});


async function loadFysiskData(type) {
    const response = await fetch('index.php?type=' + encodeURIComponent(type));
    const text = await response.text();
    console.log('Réponse brute du serveur:', text); 
    let data;
    try {
        data = JSON.parse(text);
    } catch (err) {
        console.error('Erreur de parsing JSON:', err);
        alert('Erreur côté serveur. Vérifie la console.');
        return;
    }

    if (data.error) {
        alert('Erreur SQL: ' + data.error);
        return;
    }

    chartFysisk.data.labels = data.labels;
    chartFysisk.data.datasets[0].data = data.values;
    chartFysisk.update();
}

document.getElementById('filterFysisk').addEventListener('submit', (e) => {
    e.preventDefault();
    const selectedType = document.getElementById('fysOption').value;
    loadFysiskData(selectedType);
});

window.addEventListener('DOMContentLoaded', () => {
    document.getElementById('fysOption').value = 'Slag'; 
    loadFysiskData('Slag'); 
});


</script>
<script>
const ctxPsy = document.getElementById('chartPsykisk').getContext('2d');
let chartPsykisk = new Chart(ctxPsy, {
    type: 'bar',
    data: {
        labels: [],
        datasets: [{
            label: 'Antal hændelser',
            data: [],
            backgroundColor: 'rgba(238, 223, 10, 0.6)',
            borderColor: 'rgba(156, 163, 53, 1)',
            borderWidth: 1
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        scales: { y: { beginAtZero: true } }
    }
});

async function loadPsykiskData(type) {
    const response = await fetch('index.php?typeVold=' + encodeURIComponent(type));
    const text = await response.text();
    console.log('Réponse brute du serveur:', text); 
    let data;
    try {
        data = JSON.parse(text);
    } catch (err) {
        console.error('Erreur de parsing JSON:', err);
        alert('Erreur côté serveur. Vérifie la console.');
        return;
    }

    if (data.error) {
        alert('Erreur SQL: ' + data.error);
        return;
    }

    chartPsykisk.data.labels = data.labels;
    chartPsykisk.data.datasets[0].data = data.values;
    chartPsykisk.update();
}

document.getElementById('filterPsykisk').addEventListener('submit', (e) => {
    e.preventDefault();
    const selectedType = document.getElementById('psyOption').value;
    loadPsykiskData(selectedType);
});
window.addEventListener('DOMContentLoaded', () => {
    document.getElementById('psyOption').value = 'Råb, skrig'; 
    loadPsykiskData('Råb, skrig'); 
});

</script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
document.addEventListener('DOMContentLoaded', async () => {
  const ctx = document.getElementById('statisticsChart1').getContext('2d');
  let chartCitizen;
  function renderChart(labels = [], totals = []) {
    if (chartCitizen) chartCitizen.destroy();

    chartCitizen = new Chart(ctx, {
      type: 'bar',
      data: {
        labels,
        datasets: [{
          label: 'Antal hændelser',
          data: totals,
          backgroundColor: 'rgba(23, 155, 207, 0.6)',
          borderColor: 'rgba(84, 176, 230, 1)',
          borderWidth: 1,
          borderRadius: 6,
          barPercentage: 0.6
        }]
      },
      options: {
        responsive: true,
        plugins: {
          legend: { display: true, position: 'top' },
          tooltip: { enabled: true }
        },
        scales: {
          y: { beginAtZero: true, title: { display: true, text: 'Number of Incidents' } },
          x: { title: { display: true, text: 'Citizen' } }
        }
      }
    });
  }

  async function fetchCitizenData(year, month) {
    try {
      const resp = await fetch(`?action=get_citizen_stats&year=${year}&month=${month}`);
      const data = await resp.json();

      if (data.error) {
        alert('Fejl fra serveren: ' + data.error);
        return;
      }

      renderChart(data.labels, data.values);
    } catch (err) {
      console.error('Erreur lors du chargement des données:', err);
      alert('Erreur lors du chargement des données. Vérifie la console.');
    }
  }

  const yearSelect = document.getElementById('year_citizen');
  const monthSelect = document.getElementById('month_citizen');

  yearSelect.value = '2025';
  await fetchCitizenData(2025, 0);

  document.getElementById('filterCitizen').addEventListener('submit', async (e) => {
    e.preventDefault();
    const year = yearSelect.value || 2025;
    const month = monthSelect.value || 0;
    await fetchCitizenData(year, month);
  });
});
</script>

<script>
document.addEventListener('DOMContentLoaded', async () => {
  const ctxEmp = document.getElementById('statisticsChart2').getContext('2d');
  let chartEmp;

  function renderChart(labels = [], totals = []) {
    if (chartEmp) chartEmp.destroy();

    chartEmp = new Chart(ctxEmp, {
      type: 'bar',
      data: {
        labels,
        datasets: [{
          label: 'Antal hændelser',
          data: totals,
          backgroundColor: 'rgba(31, 194, 104, 0.7)',
          borderColor: 'rgba(53, 158, 106, 1)',
          borderWidth: 1,
          borderRadius: 6,
          barPercentage: 0.6
        }]
      },
      options: {
        responsive: true,
        plugins: {
          legend: { display: true, position: 'top', labels: { font: { size: 14 } } },
          tooltip: { enabled: true, titleFont: { weight: 'bold' } }
        },
        scales: {
          y: {
            beginAtZero: true,
            title: { display: true, text: 'Antal hændelser', font: { size: 14, weight: 'bold' } }
          },
          x: { title: { display: true, text: 'Medarbejder', font: { size: 14, weight: 'bold' } } }
        }
      }
    });
  }

  async function fetchData(year, month) {
    try {
      const response = await fetch(`?action=get_employee_stats&year=${year}&month=${month}`);
      const data = await response.json();

      if (data.error) {
        alert('Fejl fra serveren: ' + data.error);
        return;
      }

      renderChart(data.labels, data.values);
    } catch (err) {
      console.error('Erreur lors du chargement des données:', err);
      alert('Erreur lors du chargement des données. Vérifie la console.');
    }
  }
  const yearSelect = document.getElementById('year_emp');
  const monthSelect = document.getElementById('month_emp');
  yearSelect.value = '2025';
  await fetchData(2025, 0);
  document.getElementById('filterEmployee').addEventListener('submit', async (e) => {
    e.preventDefault();
    const year = yearSelect.value || 2025;
    const month = monthSelect.value || 0;
    await fetchData(year, month);
  });
});
</script>

</script>
<script>
document.addEventListener('DOMContentLoaded', async () => {
    const ctx = document.getElementById('chartEmpCitizen').getContext('2d');
    let chart;

    function updateChart(labels = [], datasets = []) {
        if(chart) chart.destroy();

        
        datasets = datasets.map(ds => ({
            ...ds,
            backgroundColor: 'rgba(214, 27, 205, 0.6)', 
            borderColor: '#e731c0ff',
            borderWidth: 1
        }));

        chart = new Chart(ctx, {
            type: 'bar',
            data: { labels, datasets },
            options: {
                responsive: true,
                plugins: {
                    legend: { position: 'top' },
                    tooltip: { mode: 'index', intersect: false }
                },
                scales: {
                    x: { stacked: true, title: { display: true, text: 'Medarbejder' } },
                    y: { stacked: true, beginAtZero: true, title: { display: true, text: 'Antal hændelser' } }
                }
            }
        });
    }

    async function fetchAndUpdate(year, month) {
        try {
            const resp = await fetch(`?action=get_emp_citizen_stats&year=${year}&month=${month}`);
            const json = await resp.json();
            if (json.error) {
                alert(json.error);
                return;
            }
            updateChart(json.labels, json.datasets);
        } catch (err) {
            console.error('Erreur de récupération:', err);
            alert('Fejl ved hentning af data');
        }
    }

    
    const yearSelect = document.getElementById('year_emp_citizen');
    const monthSelect = document.getElementById('month_emp_citizen');

    if (yearSelect) {
        yearSelect.value = '2025'; 
    }
    await fetchAndUpdate(2025, 0);
    document.getElementById('filterEmpCitizen').addEventListener('submit', async e => {
        e.preventDefault();
        const year = yearSelect.value || 2025;
        const month = monthSelect.value || 0;
        await fetchAndUpdate(year, month);
    });
});
</script>


<script>
document.addEventListener('DOMContentLoaded', () => {
    const ctx = document.getElementById('chartDepartment').getContext('2d');
    let chart;

    function updateChart(labels = [], data = []) {
        if(chart) chart.destroy();
        chart = new Chart(ctx, {
            type: 'bar',
            data: {
                labels,
                datasets: [{
                    label: 'Antal hændelser',
                    data,
                    backgroundColor: 'rgba(235, 77, 195, 0.7)',
                    borderColor: 'rgba(238, 40, 195, 1)',
                    borderWidth: 1,
                    borderRadius: 6,
                    barPercentage: 0.6
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    legend: { display: true, position: 'top' },
                    tooltip: { enabled: true }
                },
                scales: {
                    x: { title: { display: true, text: 'Afdeling' } },
                    y: { beginAtZero: true, title: { display: true, text: 'Antal hændelser' } }
                }
            }
        });
    }

    fetch(`?action=get_department_stats&year=<?= date('Y') ?>&month=0`)
        .then(resp => resp.json())
        .then(json => updateChart(json.labels, json.totals))
        .catch(err => console.error('Erreur initiale:', err));

    document.getElementById('filterDepartment').addEventListener('submit', async e => {
        e.preventDefault();
        const year = document.getElementById('year_department').value || new Date().getFullYear();
        const month = document.getElementById('month_department').value || 0;

        try {
            const resp = await fetch(`?action=get_department_stats&year=${year}&month=${month}`);
            const json = await resp.json();
            if(json.error) {
                alert(json.error);
                return;
            }
            updateChart(json.labels, json.totals);
        } catch(err) {
            console.error(err);
            alert('Erreur lors du chargement des données');
        }
    });
});
</script>

<script>
document.addEventListener('DOMContentLoaded', () => {
  const ctx = document.getElementById('chartDepartment').getContext('2d');
  let chart;

  function updateChart(labels = [], data = []) {
    if (chart) chart.destroy();
    chart = new Chart(ctx, {
      type: 'bar',
      data: {
        labels,
        datasets: [{
          label: 'Antal hændelser',
          data,
          backgroundColor: 'rgba(184, 17, 17, 0.6)',
          borderColor: 'rgba(173, 6, 42, 1)',
          borderWidth: 1,
          borderRadius: 8
        }]
      },
      options: {
        responsive: true,
        plugins: {
          title: {
            display: true,
            text: 'Top Risikoområder (' + new Date().getFullYear() + ')',
            font: { size: 18 }
          },
          legend: { display: false },
          tooltip: { enabled: true }
        },
        scales: {
          x: { title: { display: true, text: 'Afdeling / Område' } },
          y: { beginAtZero: true, title: { display: true, text: 'Antal hændelser' } }
        }
      }
    });
  }

  async function fetchData(year, month) {
    const resp = await fetch(`?action=get_department_stats&year=${year}&month=${month}`);
    const json = await resp.json();
    if (json.error) {
      alert('Fejl: ' + json.error);
      return;
    }
    updateChart(json.labels, json.totals);
  }
  const currentYear = new Date().getFullYear();
  fetchData(currentYear, 0);
  document.getElementById('filterDepartment').addEventListener('submit', e => {
    e.preventDefault();
    const year = document.getElementById('year_department').value;
    const month = document.getElementById('month_department').value;
    fetchData(year, month);
  });
});
</script>
<script>
document.addEventListener('DOMContentLoaded', () => {
  const ctx = document.getElementById('chartDepartment').getContext('2d');
  let chart;

  function updateChart(labels = [], data = []) {
    if (chart) chart.destroy();
    chart = new Chart(ctx, {
      type: 'bar',
      data: {
        labels,
        datasets: [{
          label: 'Antal hændelser',
          data,
          backgroundColor: 'rgba(255, 99, 132, 0.6)',
          borderColor: 'rgba(255, 99, 132, 1)',
          borderWidth: 1,
          borderRadius: 8
        }]
      },
      options: {
        responsive: true,
        plugins: {
          title: {
            display: true,
            text: 'Top Risikoområder (' + new Date().getFullYear() + ')',
            font: { size: 18 }
          },
          legend: { display: false },
          tooltip: { enabled: true }
        },
        scales: {
          x: { title: { display: true, text: 'Afdeling / Område' } },
          y: { beginAtZero: true, title: { display: true, text: 'Antal hændelser' } }
        }
      }
    });
  }

  async function fetchData(year, month) {
    const resp = await fetch(`?action=get_department_stats&year=${year}&month=${month}`);
    const json = await resp.json();
    if (json.error) {
      alert('Fejl: ' + json.error);
      return;
    }
    updateChart(json.labels, json.totals);
  }
  const currentYear = new Date().getFullYear();
  fetchData(currentYear, 0);


  document.getElementById('filterDepartment').addEventListener('submit', e => {
    e.preventDefault();
    const year = document.getElementById('year_department').value;
    const month = document.getElementById('month_department').value;
    fetchData(year, month);
  });
});
</script>
<?php endif; ?>

  </div>
  </div>
<footer class="footer bg-light py-3">
  <div class="container d-flex justify-content-center">
    <p class="mb-0 text-center">
      &copy; <?php echo date("Y"); ?>, 
      <strong style="color:blue;">Fonden Svennebjerggaard</strong>. 
      Alle rettigheder forbeholdes. 
      Developed by 
      <strong>
        <a href="https://landynamic.com" target="_blank" style="color:#007bff; text-decoration:none;">
          LAN Dynamic
        </a>
      </strong>.
    </p>
  </div>
</footer>
    <script src="assets/js/core/jquery-3.7.1.min.js"></script>
    <script src="assets/js/core/popper.min.js"></script>
    <script src="assets/js/core/bootstrap.min.js"></script>
    <script src="assets/js/plugin/jquery-scrollbar/jquery.scrollbar.min.js"></script>
    <script src="assets/js/plugin/chart.js/chart.min.js"></script>
    <script src="assets/js/plugin/jquery.sparkline/jquery.sparkline.min.js"></script>
    <script src="assets/js/plugin/chart-circle/circles.min.js"></script>
    <script src="assets/js/plugin/datatables/datatables.min.js"></script>
    <script src="assets/js/plugin/bootstrap-notify/bootstrap-notify.min.js"></script>
    <script src="assets/js/plugin/jsvectormap/jsvectormap.min.js"></script>
    <script src="assets/js/plugin/jsvectormap/world.js"></script>
    <script src="assets/js/plugin/sweetalert/sweetalert.min.js"></script>
    <script src="assets/js/setting-demo.js"></script>
    <script src="assets/js/demo.js"></script>
    <script>
      $("#lineChart").sparkline([102, 109, 120, 99, 110, 105, 115], {
        type: "line",
        height: "70",
        width: "100%",
        lineWidth: "2",
        lineColor: "#177dff",
        fillColor: "rgba(23, 125, 255, 0.14)",
      });

      $("#lineChart2").sparkline([99, 125, 122, 105, 110, 124, 115], {
        type: "line",
        height: "70",
        width: "100%",
        lineWidth: "2",
        lineColor: "#f3545d",
        fillColor: "rgba(243, 84, 93, .14)",
      });

      $("#lineChart3").sparkline([105, 103, 123, 100, 95, 105, 115], {
        type: "line",
        height: "70",
        width: "100%",
        lineWidth: "2",
        lineColor: "#ffa534",
        fillColor: "rgba(255, 165, 52, .14)",
      });
    </script>
<script>
document.addEventListener('DOMContentLoaded', () => {
  
  const dashboardBtn = document.querySelector('[href="#dashboard"]'); 
  const incidentsBtn = document.getElementById('loadIncidents'); 
  const citizensBtn = document.getElementById('loadCitizens');
  const employeesBtn = document.getElementById('loadEmployees');
  const departmentsBtn = document.getElementById('loadDepartments');
  const employeHistoryBtn = document.getElementById('loadHistoryEmploye');
  const citizenHistoryBtn = document.getElementById('loadHistoryCitizen');
  const container = document.getElementById('dashboardContent');
  const navItems = document.querySelectorAll('.nav-item');

  if (!container) return;


  function setActive(item) {
    navItems.forEach(i => i.classList.remove('active'));
    if (item) item.closest('.nav-item').classList.add('active');
  }

  incidentsBtn?.addEventListener('click', (e) => {
    e.preventDefault();
    setActive(incidentsBtn);
    container.innerHTML = `
      <iframe src="forms/incidents.php" style="width:100%; height:100vh; border:none;"></iframe>
    `;
  });
  citizensBtn?.addEventListener('click', (e) => {
    e.preventDefault();
    setActive(citizensBtn);
    container.innerHTML = `
      <iframe src="forms/citizens.php" style="width:100%; height:100vh; border:none;"></iframe>
    `;
  });
 employeesBtn?.addEventListener('click', (e) => {
  e.preventDefault();
  setActive(employeesBtn);

  container.innerHTML = `
    <iframe src="forms/employees.php" style="width:100%; height:100%; min-height:800px; border:none;" class="full-scroll"></iframe>
  `;
});


  departmentsBtn?.addEventListener('click', (e) => {
    e.preventDefault();
    setActive(departmentsBtn);
    container.innerHTML = `
      <iframe src="forms/departments.php" style="width:100%; height:100vh; border:none;"></iframe>
    `;
  });
   employeHistoryBtn?.addEventListener('click', (e) => {
    e.preventDefault();
    setActive(employeHistoryBtn);
    container.innerHTML = `
      <iframe src="forms/employees_history.php" style="width:100%; height:100vh; border:none;"></iframe>
    `;
  });
  citizenHistoryBtn?.addEventListener('click', (e) => {
    e.preventDefault();
    setActive(citizenHistoryBtn);
    container.innerHTML = `
      <iframe src="forms/citizens_history.php" style="width:100%; height:100vh; border:none;"></iframe>
    `;
  });

  dashboardBtn?.addEventListener('click', (e) => {
    e.preventDefault();
    setActive(dashboardBtn);
    location.reload(); 
  });
});
</script>
<script>
$(document).ready(function() {
    console.log('✅ jQuery chargé:', typeof $ !== 'undefined');
    console.log('✅ Sidebar:', $('.sidebar').length);
    console.log('✅ Boutons toggle:', $('.toggle-sidebar').length);

    $('.toggle-sidebar').on('click', function(e) {
        e.preventDefault();
        e.stopPropagation();
        
        console.log('🔄 Toggle sidebar cliqué');
        
        const isMobile = $(window).width() < 992;
        
        if (isMobile) {
            $('body').toggleClass('sidebar-visible');
            console.log('📱 Mobile - Sidebar visible:', $('body').hasClass('sidebar-visible'));
        } else {
            $('body').toggleClass('sidebar-hidden');
            console.log('🖥️ Desktop - Sidebar cachée:', $('body').hasClass('sidebar-hidden'));
        }
    });
    $('.sidenav-toggler').on('click', function(e) {
        e.preventDefault();
        e.stopPropagation();
        
        console.log('🔄 Sidenav toggler cliqué');
        
        const isMobile = $(window).width() < 992;
        
        if (!isMobile) {
            $('body').toggleClass('sidebar_minimize');
            $('body').removeClass('sidebar-hidden');
            console.log('📏 Sidebar minimisée:', $('body').hasClass('sidebar_minimize'));
        }
    });
    $(document).on('click', function(event) {
        const isMobile = $(window).width() < 992;
        
        if (isMobile && $('body').hasClass('sidebar-visible')) {
            const isClickInSidebar = $(event.target).closest('.sidebar').length > 0;
            const isClickOnToggle = $(event.target).closest('.toggle-sidebar').length > 0;
            
            if (!isClickInSidebar && !isClickOnToggle) {
                $('body').removeClass('sidebar-visible');
                console.log('📱 Sidebar fermée (clic extérieur)');
            }
        }
    });

    let resizeTimer;
    $(window).on('resize', function() {
        clearTimeout(resizeTimer);
        resizeTimer = setTimeout(function() {
            const isMobile = $(window).width() < 992;
            
            if (isMobile) {
                $('body').removeClass('sidebar-hidden sidebar_minimize');
            } else {
                $('body').removeClass('sidebar-visible');
            }
        }, 250);
    });

    $('.nav-item a').on('click', function() {
        if ($(window).width() < 992) {
            $('body').removeClass('sidebar-visible');
        }
    });
document.addEventListener("keydown", function(e) {
  if (
    e.key === "F12" || 
    (e.ctrlKey && e.shiftKey && (e.key === "I" || e.key === "i")) || 
    (e.ctrlKey && e.shiftKey && (e.key === "J" || e.key === "j")) || 
    (e.ctrlKey && e.shiftKey && (e.key === "C" || e.key === "c")) || 
    (e.ctrlKey && (e.key === "U" || e.key === "u"))
  ) {
    e.preventDefault();
    return false;
  }
});

document.addEventListener("contextmenu", function(e) {
  e.preventDefault();
  return false;
});

(function() {
  const devtools = /./;
  devtools.toString = function() {
    this.opened = true;
  }
  
  setInterval(function() {
    console.clear();
    console.log(devtools);
    if (devtools.opened) {
      window.location.href = "about:blank"; 
    }
    devtools.opened = false;
  }, 1000);
})();

console.log = function() {};
console.warn = function() {};
console.error = function() {};
console.info = function() {};
});
</script>
  </body>
</html>
