<?php 
// error_reporting(E_ALL);
// ini_set('display_errors', 1);

function get_all_knowledgebase_articles($period = "") {

    
    if ($period == "") {
        $query = "SELECT * FROM `main_collection` WHERE main_collection_setup_id = 3 AND (is_archived = 0 OR is_archived IS NULL) AND description != '' ORDER BY creation_date DESC LIMIT 30";
    } else {
        // Zeitraum in Tagen in Timestamp umwandeln
        $timestamp = time() - ($period * 24 * 60 * 60);
        $query = "SELECT * FROM `main_collection` WHERE main_collection_setup_id = 3 AND (is_archived = 0 OR is_archived IS NULL) AND creation_date >= $timestamp AND description != '' ORDER BY creation_date DESC";
    }

    $result = mysqli_query($GLOBALS['mysql_con'], $query);
    $articles = [];
    while ($row = mysqli_fetch_assoc($result)) {
        $articles[] = $row;
    }
    return $articles;
};

function get_select_permisions($collection_id, $type) {
    $query = "SELECT * FROM main_collection_".$type."_link WHERE main_collection_id = ".$collection_id;
    $result = @mysqli_query($GLOBALS['mysql_con'], $query);

    $permissions = [];

    while($row = @mysqli_fetch_array($result)){
        array_push($permissions,$row['main_'.$type.'_id']);
    }
    return $permissions;
}

function has_access($user_id, $mandant, $department, $role, $fachbereich, $einricht) {

    $con = $GLOBALS['mysql_con'];


    $query = "
        SELECT * FROM main_contact_department
        WHERE main_contact_id = " . (int)$user_id;
    $result = mysqli_query($con, $query);

    if (!$result) {
        return false;
    }

    while ($row = mysqli_fetch_assoc($result)) {
        if (
            in_array($row['main_mandant_id'], $mandant) &&
            in_array($row['main_department_id'], $department) &&
            in_array($row['main_role_id'], $role) &&
            in_array($row['main_bereich_id'], $fachbereich) &&
            in_array($row['main_einricht_id'], $einricht)
        ) {
            return true; 
        }
    }

    return false;
}

// Artikel der letzten 40 Tage für die Zählung der neuen Artikel abrufen
$new_articles_period = get_all_knowledgebase_articles(15);

// Alle Artikel für die Anzeige der letzten verfügbaren Artikel abrufen
$all_articles = get_all_knowledgebase_articles();

// Neue Artikel (für den Zeitraum) nach Benutzerzugriff filtern
$new_articles_with_access = [];
foreach ($new_articles_period as $article) {
    $collection_id = $article['id'];

    $mandant = get_select_permisions($collection_id, 'mandant');
    $department = get_select_permisions($collection_id, 'department');
    $role = get_select_permisions($collection_id, 'role');
    $fachbereich = get_select_permisions($collection_id, 'fachbereich');
    $einricht = get_select_permisions($collection_id, 'einricht');

    if (has_access($GLOBALS['main_contact']["id"], $mandant, $department, $role, $fachbereich, $einricht)) {
        $new_articles_with_access[] = $article;
    }
}

// Alle Artikel nach Benutzerzugriff filtern, um die letzten 3 anzuzeigen
$accessible_articles = [];
foreach ($all_articles as $article) {
    $collection_id = $article['id'];

    $mandant = get_select_permisions($collection_id, 'mandant');
    $department = get_select_permisions($collection_id, 'department');
    $role = get_select_permisions($collection_id, 'role');
    $fachbereich = get_select_permisions($collection_id, 'fachbereich');
    $einricht = get_select_permisions($collection_id, 'einricht');

    if (has_access($GLOBALS['main_contact']["id"], $mandant, $department, $role, $fachbereich, $einricht)) {
        $accessible_articles[] = $article;
    }
}

// Nur die letzten 3 verfügbaren Artikel nehmen
$last_3_articles = array_slice($accessible_articles, 0, 3);

// Ergebnis anzeigen
if (count($last_3_articles) > 0) {
    echo '<div class="qm_container">';
    echo '<div class="mb-3">';
    $count = count($new_articles_with_access);
    $text = ($count == 1) ? 'neuer Artikel' : 'neue Artikel';
    echo '<span class="badge badge-info">' . $count . ' ' . $text . ' in den letzten 15 Tagen</span>';
    echo '</div>';
    echo '<h2>Neueste Artikel aus dem QM</h2>';
    echo '<div class="list-group">';
    
    foreach ($last_3_articles as $article) {
        $title = htmlspecialchars($article['description']);
        $link = '/awo/de/knowledgecenter-post/-' . $article['id'] . "/";
        $creation_date = date('d.m.Y', $article['creation_date']);
        
        // Prüfen, ob der Artikel neu ist (in den letzten 40 Tagen)
        $is_new = in_array($article['id'], array_column($new_articles_with_access, 'id'));
        $new_badge = $is_new ? '<span class="badge badge-success ml-2">Neu</span>' : '';
        
        echo '<a href="' . $link . '" class="list-group-item list-group-item-action">';
        echo "<img src='/userdata/03_Module/01_Firmenwiki/18_1709134644_qmhandbuch.jpg'>";
        echo '<div class="block_right">';
        echo '<h5 class="mb-1">' . $title . $new_badge . '</h5>';
        echo '<small>' . $creation_date . '</small>';
        echo '</div>';
        echo '</a>';
    }
    
    echo '</div>';
    echo '</div>';
}

?>

<style>
    .qm_container {
        width: 100%;
        padding: 20px;
        .badge-info {
            font-size: 14px;
        }
        h2 {
            font-size: var(--fs-700);
        }
        a {
            display: flex;
            align-items: center;
            text-decoration: none;
            color: inherit;
            margin-bottom: 10px;
            .block_right {
                margin-left: 15px;
            }
            img {
                max-width: 150px;
                border-radius: 7px;
            }
            h5 {
                font-size: 18px !important;
                margin-bottom: 5px;
            }
        }
    }
</style>