<?php
$pdo = new PDO("mysql:host=".$GLOBALS['myservername'].";dbname=".$GLOBALS['mydb'].';charset=utf8', $GLOBALS['mylogin'], $GLOBALS['mypass']);
$GLOBALS["pdo_conn"] = $pdo;

$current_mandant = $GLOBALS['main_contact']['current_mandant_id'];
if(isset($_GET['mandant_id'])) {
	$current_mandant = $_GET['mandant_id'];
}



function all_mandant($current_mandant) {
	$statement_mandant = $GLOBALS['pdo_conn']->prepare("SELECT * FROM main_mandant");
	$statement_mandant->execute();
	$res_mandant = $statement_mandant->fetchall(PDO::FETCH_ASSOC);
	foreach($res_mandant as $key_mandant => $value_mandant) {
		if($value_mandant['id'] == $current_mandant) {
			echo "<a class='group_btn active' href='?mandant_id=".$value_mandant['id']."'>".$value_mandant['description']."</a>";
		}else {
			echo "<a class='group_btn' href='?mandant_id=".$value_mandant['id']."'>".$value_mandant['description']."</a>";
		}
	}
}

function current_mandant($current_mandant) {
	$statement_mandant = $GLOBALS['pdo_conn']->prepare("SELECT * FROM main_mandant WHERE id = :id");
	$statement_mandant->execute(array(':id' => $current_mandant));
	$res_mandant = $statement_mandant->fetch(PDO::FETCH_ASSOC);
	return $res_mandant;
}

function getDepartments($current_mandant) {
	$statement_departments = $GLOBALS["pdo_conn"]->prepare("SELECT DISTINCT main_department.* FROM main_department LEFT JOIN main_department_mandant_link ON main_department.id = main_department_mandant_link.main_department_id WHERE main_mandant_id = :main_mandant_id");
	$statement_departments->execute(array(':main_mandant_id' => $current_mandant));
	$res_departments = $statement_departments->fetchall(PDO::FETCH_ASSOC);
	echo "<div class='pop-up-button current'>Alle</div>";
	foreach ($res_departments as $key_departments => $value_departments) {
		echo "<div class='pop-up-button'>".$value_departments['description']."</div>";
	}
}

function getTeilen(){
    $current_department = isset($_GET['current_department']) ? $_GET['current_department'] : null;
	$statement_mandant = $GLOBALS['pdo_conn']->prepare("SELECT * FROM `main_department` ORDER BY description ASC");
    // $statement_mandant = $GLOBALS['pdo_conn']->prepare("SELECT * FROM `main_department`");
    $statement_mandant->execute();
    $res_mandant = $statement_mandant->fetchAll(PDO::FETCH_ASSOC);
    foreach($res_mandant as $key_mandant => $value_mandant) {
		$query = "SELECT * FROM main_contact_department WHERE main_department_id = ".$value_mandant['id'];
		// var_dump($query);
		$result = @mysqli_query($GLOBALS['mysql_con'], $query);

		// if (mysqli_num_rows($result) <= 0) {
		// 	continue;
		// }
		$isActive = ($current_department == $value_mandant['id']) ? 'active' : '';
		echo "<div class='department_container $isActive'>";
		echo "<a class='department_title' href='?current_department=".$value_mandant['id']."'>".$value_mandant['description']."</a>";
		// echo "<p class='department_details $isActive'>".$value_mandant["details"]."</p>";
		echo "</div>";

    }
}

function getTeilenDropdown() {
    $current_department = isset($_GET['current_department']) ? $_GET['current_department'] : null;
	$statement_mandant = $GLOBALS['pdo_conn']->prepare("SELECT * FROM `main_department` ORDER BY description ASC");
    $statement_mandant->execute();
    $res_mandant = $statement_mandant->fetchAll(PDO::FETCH_ASSOC);
    
    echo "<select class='department_dropdown' onchange='location = this.value;'>";
    // Erste Option, deaktiviert
    echo "<option value='/intranet/de/kontaktdaten/'selected>Abteilung auswählen</option>";
    foreach($res_mandant as $key_mandant => $value_mandant) {
		$query = "SELECT * FROM main_contact_department WHERE main_department_id = ".$value_mandant['id'];
		// var_dump($query);
		$result = @mysqli_query($GLOBALS['mysql_con'], $query);

		// if (mysqli_num_rows($result) <= 0) {
		// 	continue;
		// }
        $isActive = ($current_department == $value_mandant['id']) ? 'selected' : '';
        $url = "?current_department=".$value_mandant['id'];
        echo "<option value='$url' $isActive>".$value_mandant['description']."</option>";
    }
    echo "</select>";
}

function get_person_role($current_mandant, $contact_id) {
    $conn = $GLOBALS['mysql_con'];

    $current_mandant = (int)$current_mandant;
    $contact_id = (int)$contact_id;

    $query = "SELECT main_role_id 
              FROM main_contact_department 
              WHERE main_mandant_id = $current_mandant 
                AND main_contact_id = $contact_id 
              LIMIT 1";

    $res = mysqli_query($conn, $query);

    if (!$res) {
        return ""; 
    }

    $row = mysqli_fetch_array($res, MYSQLI_ASSOC);

    if (!$row || empty($row['main_role_id'])) {
        return ""; 
    }

    $role_id = (int)$row['main_role_id'];
    $get_role = "SELECT description 
                 FROM main_role 
                 WHERE id = $role_id 
                 LIMIT 1";

    $role_res = mysqli_query($conn, $get_role);

    if (!$role_res) {
        return ""; 
    }

    $role_row = mysqli_fetch_array($role_res, MYSQLI_ASSOC);

    return $role_row['description'] ?? "";
}
function get_person_einricht($current_mandant, $contact_id) {
    $conn = $GLOBALS['mysql_con'];

    $current_mandant = (int)$current_mandant;
    $contact_id = (int)$contact_id;

    $query = "SELECT main_einricht_id 
              FROM main_contact_department 
              WHERE main_mandant_id = $current_mandant 
                AND main_contact_id = $contact_id 
              LIMIT 1";
    
    // var_dump($query);

    $res = mysqli_query($conn, $query);

    if (!$res) {
        return ""; 
    }

    $row = mysqli_fetch_array($res, MYSQLI_ASSOC);

    if (!$row || empty($row['main_einricht_id'])) {
        return ""; 
    }

    $role_id = (int)$row['main_einricht_id'];
    $get_role = "SELECT description 
                 FROM organigramm_einricht 
                 WHERE id = $role_id 
                 LIMIT 1";


    $role_res = mysqli_query($conn, $get_role);

    if (!$role_res) {
        return ""; 
    }

    $role_row = mysqli_fetch_array($role_res, MYSQLI_ASSOC);

    return $role_row['description'] ?? "";
}
function get_person_space($current_mandant, $contact_id) {
    $conn = $GLOBALS['mysql_con'];

    $current_mandant = (int)$current_mandant;
    $contact_id = (int)$contact_id;

    $query = "SELECT main_bereich_id 
              FROM main_contact_department 
              WHERE main_mandant_id = $current_mandant 
                AND main_contact_id = $contact_id 
              LIMIT 1";
    
    // var_dump($query);

    $res = mysqli_query($conn, $query);

    if (!$res) {
        return ""; 
    }

    $row = mysqli_fetch_array($res, MYSQLI_ASSOC);

    if (!$row || empty($row['main_bereich_id'])) {
        return ""; 
    }

    $role_id = (int)$row['main_bereich_id'];
    $get_role = "SELECT description 
                 FROM organogramm_space 
                 WHERE id = $role_id 
                 LIMIT 1";


    $role_res = mysqli_query($conn, $get_role);

    if (!$role_res) {
        return ""; 
    }

    $role_row = mysqli_fetch_array($role_res, MYSQLI_ASSOC);

    return $role_row['description'] ?? "";
}


function getList($current_mandant) {
    $join = "";
    $where = "WHERE main_contact.active = 1";
    $join .= " LEFT JOIN main_contact_department ON main_contact.id = main_contact_department.main_contact_id";
    $join .= " LEFT JOIN main_department ON main_contact_department.main_department_id = main_department.id";
    
    if ($_GET['current_department']) {
        $where .= " AND main_contact_department.main_mandant_id = " . $current_mandant . " AND main_contact_department.main_department_id IN ( SELECT md.id FROM main_department md WHERE md.id = " . $_GET['current_department'] . ")";
    }
    if ($_GET['tag']) {
        $join .= " LEFT JOIN main_contact_tags_link ON main_contact.id = main_contact_tags_link.main_contact_id";
        $where .= " AND main_contact_tags_link.main_contact_tags_id = " . $_GET['tag'];
    }

    $query = "SELECT main_contact.*, GROUP_CONCAT(DISTINCT main_department.description SEPARATOR ', ') AS department_list
    FROM main_contact 
    $join 
    $where 
    GROUP BY main_contact.id
    ORDER BY main_contact.name";
    $result = @mysqli_query($GLOBALS['mysql_con'], $query);

    // Beginne die Tabelle
    echo '<table class="contact_table">';
    echo '<thead>';
    echo '<tr>';
    echo '<th>Bild</th>';
    echo '<th>Name</th>';
    echo '<th>Telefon</th>';
    echo '<th>Email</th>';
    echo '</tr>';
    echo '</thead>';
    echo '<tbody>';

    while ($value_users = @mysqli_fetch_array($result)) {
        $role_class = "";
        if ($value_users['main_role_id'] == 5) {
            $role_class = "observer";
        } else if ($value_users['main_role_id'] == 3) {
            $role_class = "teamleader";
        } else if ($value_users['main_role_id'] == 4) {
            $role_class = "ceo";
        }
        $link = get_link_to_navigation(10) . "?contact=" . $value_users['id'];

        // Zeile für jeden Kontakt
        echo '<tr class="contact_row">';
        echo '<td class="contact_img_new">';
        if ($value_users['image'] == "") {
            echo "<img class='img-fluid' src='/userdata/intranet/contact/platzhalter.png'>";
        } else {
            echo "<a data-fslightbox=" . $value_users['id'] . " href='/userdata/intranet/contact/" . $value_users['image'] . "'><img class='img-fluid' src='/userdata/intranet/contact/" . $value_users['image'] . "'></a>";
        }
        echo '</td>';
        echo '<td><a class="contact_link_new" href="' . $link . '">' . $value_users['name'] . '</a></td>';

        $phoneNumber = $value_users['phone_no'];
        echo '<td>' . (!empty($phoneNumber) ? "<a href='tel:" . $phoneNumber . "'>" . $phoneNumber . "</a>" : "") . '</td>';
        echo '<td><a href="mailto:' . $value_users['email'] . '">' . $value_users['email'] . '</a></td>';
        echo '<td>
            <div style="cursor:pointer; width:16px; height:16px;" 
                onclick="open_modal_visitcard(\'' . 
                ($value_users['image'] != "" ? $value_users['image'] : "platzhalter.png") . '\', \'' . 
                $value_users['name'] . '\', \'' . 
                $value_users['email'] . '\', \'' . 
                $value_users['cost_center'] . '\', \'' . 
                $value_users['address'] . '\', \'' . 
                $value_users['post_code'] . '\', \'' . 
                $value_users['city'] . '\', \'' . 
                get_person_role($current_mandant, $value_users['id']) . '\', \'' . 
                get_person_einricht($current_mandant, $value_users['id']) . '\', \'' . 
                get_person_space($current_mandant, $value_users['id']) . '\', \'' . 
                $phoneNumber . '\')">
                <img src="/userdata/intranet/contact/visitcard.svg">
            </div>
        </td>';
        echo '</tr>';
    }

    echo '</tbody>';
    echo '</table>';
}

?>
<div class="cont_container">
	<div class='kontaktdaten_list'>
		<div class='kontaktdaten_content'>
			<div class='col-sm-12 col-md-12 col-lg-8'>
				<div class="contact_list">
						<?php getList($current_mandant);?>
				</div>
			</div>
			<div class="col-xs-12 col-sm-12 col-md-12 col-lg-4">
				<div class="department_list">
					<div class="widget_header">
						<div class="widget_title"><h2>Fachbereiche</h2></div>
						<a href="/intranet/de/kontaktdaten/">Alle Kollegen anzeigen</a>
					</div>
					<?php getTeilen(); ?>
				</div>
			</div>
		</div>
	</div>
</div>

<style>
    #modal_visitcard {
        display: block; /* Show the modal */
        position: fixed; /* Stay in place */
        z-index: 1000; /* Sit on top */
        left: 0;
        top: 0;
        width: 100%; /* Full width */
        height: 100%; /* Full height */
        overflow: auto; /* Enable scroll if needed */
        background-color: rgb(0,0,0); /* Fallback color */
        background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
    }
    #modal_visitcard .modal-content {
        background-color: #fefefe;
        margin: 15% auto; /* 15% from the top and centered */
        /* padding: 20px; */
        border: 1px solid #888;
        width: 80%; /* Could be more or less, depending on screen size */
        max-width: 600px;
        position: relative;
        border-radius: 10px;
        overflow: hidden;
        .profil_bg {
            max-height: 100px;
            position: static;
        }
        .close {
            color: #fff;
            float: right;
            font-size: 28px;
            font-weight: bold;
            position: absolute;
            top: 10px;
            right: 10px;
            z-index: 1001;
        }

        .img-fluid {
            width: 70px;
            height: 70px;
            max-width: 60px;
            max-height: 60px;
            border-radius: 50%;
            object-fit: cover;
            top: 70px;
            left: 40px;
            position: absolute;
        }
        .user_name {
            font-size: 20px;
            font-weight: bold;
            margin-top: 40px;
            margin-left: 30px;
        }
        .user_email {
            font-size: 16px;
            margin-top: 5px;
            margin-left: 30px;
        }
        .user_adress {
            font-size: 16px;
            /* margin-top: 5px; */
            margin-left: 30px;
        }
        .user_phone {
            font-size: 16px;
            /* margin-top: 5px; */
            margin-bottom: 20px;
            margin-left: 30px;
        }
        .user_role {
            font-size: 14px;
            /* margin-top: 5px; */
            margin-left: 30px;
        }
        .user_cost_center {
            position: absolute;
            top: 110px;
            right: 10px;
            font-size: 12px;
        }
    }
    .contact_table {
        font-size: 16px;
    }
</style>

<script>

function open_modal_visitcard(img_src, user_name, user_email, user_cost_center, address, postCode, city, role, einricht, space, user_phone ) {

    user_cost_center = user_cost_center ? `<p class="user_cost_center">Kostenstelle: ${user_cost_center}</p>` : "";

    document.querySelector("body#body").insertAdjacentHTML('beforeend', `
        <div id="modal_visitcard" class="modal">
            <div class="modal-content">
                <span class="close" onclick="close_modal_visitcard()">&times;</span>
                <img class="profil_bg" src="/userdata/intranet/contact/contact_banner.jpg">
                <img class='img-fluid' src='/userdata/intranet/contact/${img_src}'>
                <p class="user_name">${user_name}</p>
                ${user_cost_center}
                <p class="user_role" style="font-size: 10px;">${space}</p>
                <p class="user_role">${einricht} - ${role}</p>
                <p class="user_email"><a href="mailto:${user_email}">${user_email}</a></p>
                <p class="user_adress">${address}, ${postCode} ${city}</p>
                <p class="user_phone"><a href="tel:${user_phone}">${user_phone}</a></p>
            </div>
        </div>
    `);
};

function close_modal_visitcard() {
    var modal = document.getElementById("modal_visitcard");
    if (modal) {
        modal.remove();
    }
}

$(document).ready(function() {
    function setFirstOption(selectId, defaultText) {
        var $select = $('#' + selectId);

        // Check if the first option is not already the default option
        if ($select.find('option').first().text() !== defaultText) {
            // Remove any existing default option if necessary
            $select.find('option[value=""]').remove();

            // Prepend the default option and mark it as selected
            var $defaultOption = $('<option>', {
                value: '',
                text: defaultText,
                selected: 'selected'  // Set selected attribute
            });
            $select.prepend($defaultOption);
        }
    }

    // Usage of the function for the select element with the ID 'main_contact_tags'
    setFirstOption('main_contact_tags', 'Zuständigkeit auswählen');

    $('#main_contact_tags').on('change', function() {
        var selectedValue = $(this).val();
        var currentUrl = window.location.href;
        var newUrl;

        // Create a URL object for easier manipulation
        var url = new URL(currentUrl);

        // Set the 'tag' parameter
        url.searchParams.set('tag', selectedValue);

        // Remove any duplicate 'tag' or 'id' parameters
        var searchParams = new URLSearchParams(url.search);
        var keysToRemove = [];
        searchParams.forEach((value, key) => {
            if (key === 'tag' && value !== selectedValue) {
                keysToRemove.push(key);
            }
            if (key === 'id' && value !== url.searchParams.get('id')) {
                keysToRemove.push(key);
            }
        });
        keysToRemove.forEach(key => searchParams.delete(key));

        newUrl = url.origin + url.pathname + '?' + searchParams.toString();

        // Reload the page with the new URL
        window.location.href = newUrl;
    });
});



</script>