<?
switch ($_GET["action"]) {
    case 'edit':
        edit_contact();
        break;
    case 'delete':
        delete_contact($contact['id']);
        break;
    // case 'updateFromJSON':
    //     updateFromJSON();
    //     break;
    case 'new':
        require_once("edit_contact_cardform.inc.php");
        break;
    case 'save':
        save_contact();
        break;
    case 'report':
        report_new_emp();
        save_contact();
        break;
    case 'report_dismissal':
        report_emp_dismissal();
        save_contact();
        break;
    case 'hausausweis_request':
        hausausweis_request();
        save_contact();
        break;
    case 'delete_image':
        delete_contact_image();
        break;
    case 'open_card':
        open_card();
    default:
        require_once("edit_contact_listform.inc.php");
        break;
}

function open_card()
{ ?>
    <script type="text/javascript">
        openCardOnStart = true;
        openCardAction = 'new';
    </script>
<?php }

function edit_contact($_id = "", $messages = array())
{
    if ((int) $_id > 0) {
        $input_id = $_id;
    } else {
        $input_id = $_POST["input_id"];
    }

    if ($input_id <> '') {

        $pdoHost = getenv('MAIN_MYSQL_DB_HOST');
        $pdoPort = getenv('MAIN_MYSQL_DB_PORT');
        $pdoUser = getenv('MAIN_MYSQL_DB_USER');
        $pdoPass = getenv('MAIN_MYSQL_DB_PASS');
        $pdoSchema = getenv('MAIN_MYSQL_DB_SCHEMA');

        $pdo = new \DynCom\mysyde\common\classes\PDOQueryWrapper($pdoHost, $pdoPort, $pdoSchema, $pdoUser, $pdoPass);

        $prepStatement = "  SELECT * FROM main_contact WHERE id = :id LIMIT 1 ";
        $params = [
            [':id', $input_id, PDO::PARAM_STR],
        ];
        $pdo->setQuery($prepStatement);
        $pdo->prepareQuery();
        $pdo->bindParameters($params);
        $pdo->executePreparedStatement();
        $result = $pdo->getResultArray();

        if (count($result) == 1) {
            $input_contact = $result[0];
            $input_contact["password"] = "nochange";
            echo "<script>console.log('" . $input_id . "')</script>";
            require_once("edit_contact_cardform.inc.php");
        }
    } else {
        $input_contact = array();
        require_once("edit_contact_cardform.inc.php");
    }
}

function delete_contact($curr_contact_id)
{
    $translation = \DynCom\mysyde\common\classes\Registry::get("translation");
    if ($_POST["input_id"] <> '') {
        if ($_POST["input_id"] <> $curr_contact_id) {
            $query = "DELETE FROM main_contact WHERE id = '" . $_POST["input_id"] . "' LIMIT 1";
            @mysqli_query($GLOBALS['mysql_con'], $query);
            $deleteDepartment = @mysqli_query($GLOBALS["mysql_con"], "DELETE FROM main_contact_department WHERE main_contact_id=" . $_POST["input_id"]);
            $deletePermission = @mysqli_query($GLOBALS["mysql_con"], "DELETE FROM main_contact_permission WHERE main_contact_id=" . $_POST["input_id"]);
            $deleteProfileContent = @mysqli_query($GLOBALS["mysql_con"], "DELETE FROM main_contact_profile_content WHERE main_contact_id=" . $_POST["input_id"]);
            $deleteSkills = @mysqli_query($GLOBALS["mysql_con"], "DELETE FROM main_contact_skills WHERE main_contact_id=" . $_POST["input_id"]);
        } else {
            header('EDIT_ERROR: 1');
            $messages[] = "<div class=\"errorbox\">" . $translation->get("contact_error5") . "</div>";
            edit_contact($_POST["input_id"], $messages);
        }
    }
    require_once("edit_contact_listform.inc.php");
}


// Hinweis:
// Da die Mandanten-Auswahl im Frontend aktuell deaktiviert ist (kein change_mandant möglich),
// wird der current_mandant_id beim Speichern eines Kontakts immer auf den master_mandant_id gesetzt.
// Hintergrund: Ohne sichtbaren Mandantenwechsel bleibt der alte current_mandant bestehen,
// was zu falscher Darstellung im Profil (z.B. falsche Rolle/Bereich) führt.
// Durch diese Anpassung wird sichergestellt, dass der Benutzer immer im korrekten Mandanten geladen wird.
//
// -> Fix implementiert von FA Ticket T26-1218 ∙ Fehlerhafte Darstellung Intranet
function save_contact()
{
    $messages = array();
    $error = FALSE;
    $input_id = "";
    $translation = \DynCom\mysyde\common\classes\Registry::get("translation");
    if ($_POST['input_password'] != "") {
        $password = md5($_POST['input_password']);
        $query = "UPDATE main_contact SET
            password = '" . $password . "'
            WHERE id = '" . $_POST['input_id'] . "' LIMIT 1";
        @mysqli_query($GLOBALS['mysql_con'], $query);
    }
    $birthday = new DateTime($_POST['input_birthday']);

    if ($_POST["input_id"] <> '') {
        $inserted = FALSE;
        $input_id = $_POST["input_id"];
        $query = "UPDATE main_contact
			SET name = '" . $_POST['input_name'] . "',
			email = '" . $_POST['input_email'] . "',
			shortcut = '" . $_POST['input_shortcut'] . "',
			address = '" . $_POST['input_address'] . "',  
			post_code = '" . $_POST['input_post_code'] . "',
			city = '" . $_POST['input_city'] . "',
			cost_center = '" . $_POST['input_cost_center'] . "',
			birthday = '" . $birthday->format('Y-m-d') . "',
			phone_no = '" . $_POST['input_phone_no'] . "',
			birthday_state = '" . $_POST['input_birthday_state'] . "',
            master_mandant_id = '" . $_POST['master_mandant_id'] . "',
            current_mandant_id = '" . $_POST['master_mandant_id'] . "'
			WHERE id = '" . $_POST["input_id"] . "' LIMIT 1";
    } else {
        $query = "INSERT INTO main_contact (id, name, email, shortcut, password, address, post_code, city, birthday, birthday_state, phone_no, cost_center, master_mandant_id, current_mandant_id, active) VALUES (
			NULL,
			'" . $_POST['input_name'] . "',
			'" . $_POST['input_email'] . "',
			'" . $_POST['input_shortcut'] . "',
			'" . $password . "',
			'" . $_POST['input_address'] . "',
			'" . $_POST['input_post_code'] . "',
			'" . $_POST['input_city'] . "',
			'" . $birthday->format('Y-m-d') . "',
            '" . $_POST['input_birthday_state'] . "', 
            '" . $_POST['input_phone_no'] . "',
            '" . $_POST['input_cost_center'] . "', 
            '" . $_POST['master_mandant_id'] . "',
            '" . $_POST['master_mandant_id'] . "',
            '1'
			)";
        $inserted = TRUE;
    }

    // $query_shortcut = "SELECT * FROM main_contact WHERE shortcut = '".$_POST['input_shortcut']."'";
    // $result_shortcut = @mysqli_query($GLOBALS['mysql_con'], $query_shortcut);
    // if(@mysqli_num_rows($result_shortcut) >= 1 && $inserted == TRUE){
    //     $messages[] = "<div class=\"errorbox\">" . $translation->get("user_error4") . "</div>\n";
    //     $error      = TRUE;
    // }

    if (!$error) {
        @mysqli_query($GLOBALS['mysql_con'], $query);
        if ($inserted == TRUE) {
            $input_id = mysqli_insert_id($GLOBALS['mysql_con']);
            $query2 = "INSERT INTO main_contact_profile_content (id, main_contact_id) VALUES (
                NULL,
                '" . $input_id . "'
                )";
            @mysqli_query($GLOBALS['mysql_con'], $query2);
            $messages[] = '<div class="successbox">' . $translation->get("contact_msg_success1") . '</div>';
        } else {
            $messages[] = '<div class="successbox">' . $translation->get("contact_msg_success2") . '</div>';
        }
        if (isset($_FILES) && $_FILES['input_image']['size'] != 0) {
            $fileName = saveImage('input_image', $input_id);
            $query = "UPDATE main_contact SET
                    image = '" . $fileName . "'
                    WHERE id = '" . $input_id . "' LIMIT 1";
            @mysqli_query($GLOBALS['mysql_con'], $query);
        }
        save_mandant_link($_POST, $input_id);
        save_permission($input_id);
        echo "<script>console.log('" . $input_id . "')</script>";
        edit_contact($input_id, $messages);
    } else {
        header('EDIT_ERROR: 1');
        $input_contact["id"] = $_POST["input_id"];
        $input_contact["name"] = $_POST["input_name"];
        $input_contact["email"] = $_POST["input_email"];
        $input_contact["login"] = $_POST["input_login"];
        require_once("edit_contact_cardform.inc.php");
    }
}

function report_new_emp()
{

    $message = "Neuer Mitarbeiter wurde registriert!" .
        "<br> Name:" . $_POST['input_name'] .
        "<br> Email:" . $_POST['input_email'];

    if (
        mail_create(
            "Neuer Mitarbeiter", // titel
            $message,
            "intranet@awo-hamburg.de", // wer send
            "helpdesk@awo-hamburg.de", // wer kriegt
            "AWO Hamburg", // name des senders
            "AWO Hamburg IT", // name des empfängers
            FALSE,
            $file,
            "",
            "",
            0,
            "",
            $spid
        )
    ) {
        mail_send();
    }
}
function report_emp_dismissal()
{

    $message = "Der Mitarbeiter muss entlassen werden!" .
        "<br> Name:" . $_POST['input_name'] .
        "<br> Email:" . $_POST['input_email'];

    if (
        mail_create(
            "Mitarbeiter entlassen!", // titel
            $message,
            "intranet@awo-hamburg.de", // wer send
            "helpdesk@awo-hamburg.de", // wer kriegt
            "AWO Hamburg", // name des senders
            "AWO Hamburg IT", // name des empfängers
            FALSE,
            $file,
            "",
            "",
            0,
            "",
            $spid
        )
    ) {
        mail_send();
    }
}
function hausausweis_request()
{

    $message = "Der Mitarbeiter soll einen Hausausweis erhalten!" .
        "<br> Name:" . $_POST['input_name'] .
        "<br> Email:" . $_POST['input_email'];

    if (
        mail_create(
            "Der Mitarbeiter soll einen Hausausweis erhalten!", // titel
            $message,
            "intranet@awo-hamburg.de", // wer send
            "helpdesk@awo-hamburg.de", // wer kriegt
            "AWO Hamburg", // name des senders
            "AWO Hamburg IT", // name des empfängers
            FALSE,
            $file,
            "",
            "",
            0,
            "",
            $spid
        )
    ) {
        mail_send();
    }
}

function saveImage($filekey, $input_id)
{
    $erlaubte_endungen = array("jpg", "jpeg", "gif", "png");
    $filename = strtolower($_FILES[$filekey]['name']);
    $filename_expl = explode(".", $filename);
    if (!in_array($filename_expl[count($filename_expl) - 1], $erlaubte_endungen)) {
        $messages = "<div class='errorbox'>" . $translation->get("error_slideshow_line2") . "</div>\n";
        $error = TRUE;
    }

    $saveFilename = $input_id . "_" . time() . "_" . cleanFilename($_FILES[$filekey]['name']);

    require_once("intranet_config.inc.php");
    move_uploaded_file($_FILES[$filekey]['tmp_name'], PATH_CONTACT . $saveFilename);

    return $saveFilename;
}
function delete_contact_image()
{
    $contact_id = $_POST['input_id'];
    $query = "SELECT * FROM main_contact WHERE id =" . $contact_id . " LIMIT 1";
    $result = @mysqli_query($GLOBALS['mysql_con'], $query);
    $contact = @mysqli_fetch_array($result);

    if (!empty($contact)) {
        $filename = $contact['image'];
        require_once("intranet_config.inc.php");

        if (file_exists(PATH_CONTACT . $filename)) {
            unlink(PATH_CONTACT . $filename);
        }
        $query = "UPDATE main_contact SET
				image = ''
				WHERE id = '" . $contact_id . "' LIMIT 1";
        @mysqli_query($GLOBALS['mysql_con'], $query);
    }
    edit_contact();
}


function save_mandant_link($contacts, $contact_id)
{
    // $contact_id als Integer absichern
    $contact_id = intval($contact_id);

    // Vorherige Einträge löschen
    $deleteQuery = "DELETE FROM main_contact_department WHERE main_contact_id='" . $contact_id . "'";
    mysqli_query($GLOBALS["mysql_con"], $deleteQuery);

    // Array initialisieren
    $mandants = array();

    // Mandant-Werte aus $contacts extrahieren
    foreach ($contacts as $key => $value) {
        if (strpos($key, needle: 'input_mandant_') === 0 && $value != 0) {
            $mandants[] = $value;
        } elseif (strpos($key, needle: 'input_mandant_') === 1 && $value == 0) {
            $mandants[] = $value;
        }
    }

    // Falls $mandants nicht leer ist, Einträge einfügen
    for ($i = 0; $i < count($mandants); $i++) {
        // Wert absichern
        $mandantEscaped = mysqli_real_escape_string($GLOBALS['mysql_con'], $mandants[$i]);

        $query = "INSERT INTO main_contact_department
            (main_contact_id, main_mandant_id, sorting)
            VALUES (
                " . $contact_id . ",
                '" . $mandantEscaped . "',
                '" . ($i + 1) . "'
            )";

        mysqli_query($GLOBALS['mysql_con'], $query);
        // Falls du die eingefügte ID benötigst:
        $input_id = mysqli_insert_id($GLOBALS['mysql_con']);

     if ($i === 0) {
    $query2 = "UPDATE main_contact 
        SET master_mandant_id = " . $mandantEscaped . ",
            current_mandant_id = " . $mandantEscaped . "
        WHERE id = " . $contact_id;
    mysqli_query($GLOBALS['mysql_con'], $query2);
}
    }

    // Weitere Verarbeitung
    save_contact_department($contacts, $contact_id);
}

function save_contact_department($contacts, $contact_id)
{
    // Arrays initialisieren
    $mandants = [];
    $departments = [];
    $roles = [];
    $bereiches = [];
    $einrichtungs = [];
    $phone_numbers = [];
    $emails = [];

    // Durchlaufe alle Einträge in $contacts und fülle die jeweiligen Arrays
    foreach ($contacts as $key => $value) {
        if (strpos($key, 'input_mandant_') === 0) {
            if ($value != 0) {
                $mandants[] = $value;
            }
        } elseif (strpos($key, 'input_department_') === 0) {
            $departments[] = $value;
        } elseif (strpos($key, 'input_role_') === 0) {
            $roles[] = $value;
        } elseif (strpos($key, 'input_bereiche_') === 0) {
            $bereiches[] = $value;
        } elseif (strpos($key, 'input_einrichtung_') === 0) {
            $einrichtungs[] = $value;
        } elseif (strpos($key, 'input_phone_no_') === 0) {
            $phone_numbers[] = $value;
        } elseif (strpos($key, 'input_email_') === 0) {
            $emails[] = $value;
        }
    }

    // Nur fortfahren, wenn mindestens ein Mandant vorhanden ist
    if (count($mandants) > 0) {
        try {
            for ($i = 0; $i < count($mandants); $i++) {
                // Werte absichern
                $departmentEscaped = mysqli_real_escape_string($GLOBALS['mysql_con'], $departments[$i]);
                $roleEscaped = mysqli_real_escape_string($GLOBALS['mysql_con'], $roles[$i]);
                $bereichEscaped = mysqli_real_escape_string($GLOBALS['mysql_con'], $bereiches[$i]);
                $einrichtungEscaped = mysqli_real_escape_string($GLOBALS['mysql_con'], $einrichtungs[$i]);
                $phoneEscaped = mysqli_real_escape_string($GLOBALS['mysql_con'], $phone_numbers[$i]);
                $emailEscaped = mysqli_real_escape_string($GLOBALS['mysql_con'], $emails[$i]);

                // SQL-Abfrage zum Update
                $query = "UPDATE main_contact_department
                    SET 
                        main_department_id = '$departmentEscaped',
                        main_role_id       = '$roleEscaped',
                        main_bereich_id    = '$bereichEscaped',
                        main_einricht_id   = '$einrichtungEscaped',
                        phone_no           = '$phoneEscaped',
                        email              = '$emailEscaped'
                    WHERE 
                        main_contact_id = '" . intval($contact_id) . "' 
                        AND sorting = '" . ($i + 1) . "' 
                    LIMIT 1";

                mysqli_query($GLOBALS['mysql_con'], $query);
            }
        } catch (\Throwable $th) {
            // Bei einem Fehler wird die Fehlermeldung ausgegeben.
            echo $th->getMessage();
        }
    }
}

function load_mandant_list($contact)
{
    $translation = \DynCom\mysyde\common\classes\Registry::get("translation");

    $query = "SELECT * FROM main_mandant";
    $result = @mysqli_query($GLOBALS['mysql_con'], $query);
    while ($mandant = @mysqli_fetch_array($result)) {
        $mandant_id = $mandant['id'];

        $check_master_mandant = ($contact['master_mandant_id'] == $mandant_id) ? 'checked' : '';

        $query_contact = "SELECT * FROM main_contact_department WHERE main_contact_id = '" . $contact['id'] . "' AND main_mandant_id = '" . $mandant_id . "'";
        $result_contact = @mysqli_query($GLOBALS['mysql_con'], $query_contact);
        $contact_link = @mysqli_fetch_array($result_contact);

        $check_active = ($contact_link['active'] == 1) ? 'checked' : '';

        // $query_department = "SELECT DISTINCT main_department.id, main_department.description AS name FROM main_department LEFT JOIN main_department_mandant_link ON main_department.id = main_department_mandant_link.main_department_id WHERE main_mandant_id = ".$mandant_id;
        $query_department = "SELECT DISTINCT main_department.id, main_department.description AS name FROM main_department";
        $query_role = "SELECT id,description AS name FROM main_role";

        $query_bereich = "SELECT * FROM `organogramm_space`";
        $query_einricht = "SELECT * FROM `organigramm_einricht`";
        ?>
        <tr>
            <td><?= $mandant['description'] ?></td>
            <td><input class="checkbox_square" type="checkbox" name="active_<?= $mandant_id ?>" <?= $check_active ?>></td>
            <td><input class="checkbox_square" type="radio" name="master_mandant_id" value='<?= $mandant_id ?>'
                    <?= $check_master_mandant ?>></td>
            <td><?= input_select_from_sql("", "input_department_" . $mandant_id, $query_department, $contact_link['main_department_id'], FALSE, FALSE, "", TRUE); ?>
            </td>
            <td><?= input_select_from_sql_bereich("", "input_bereiche_" . $mandant_id, $query_bereich, $contact_link['main_bereich_id'], FALSE, FALSE, "", TRUE); ?>
            </td>
            <td><?= input_select_from_sql_ein("", "input_einrichtung_" . $mandant_id, $query_einricht, $contact_link['main_einricht_id'], FALSE, FALSE, "", TRUE); ?>
            </td>
            <td><?= input_select_from_sql("", "input_role_" . $mandant_id, $query_role, $contact_link['main_role_id'], FALSE, FALSE, "", TRUE); ?>
            </td>
            <td><?= input("", "input_phone_no_" . $mandant_id, "text", $contact_link["phone_no"], 100); ?></td>
            <td><?= input("", "input_email_" . $mandant_id, "text", $contact_link["email"], 100); ?></td>
            <!-- <?php if ($GLOBALS['admin_user']['control_permissions'] == 1) { ?>
                <td><button class="pop_up_button svg_button" title="Berechtigung ändern" data-popup-id="popup-mandant-<?= $mandant_id ?>" ><svg xmlns="http://www.w3.org/2000/svg" width="28.8" height="35.25" viewBox="0 0 28.8 35.25">
                    <path id="shield-security" d="M14.4.375l14.4,6.45v9.6a19.876,19.876,0,0,1-4.125,12.188A17.908,17.908,0,0,1,14.4,35.625,17.912,17.912,0,0,1,4.125,28.612,19.875,19.875,0,0,1,0,16.425v-9.6ZM14.4,18V3.9L3.225,8.85V18H14.4V32.325a15.292,15.292,0,0,0,7.5-5.4A17.845,17.845,0,0,0,25.575,18Z" transform="translate(0 -0.375)"/></svg>
                    </button>
                </td>
            <?php } ?> -->
        </tr>
    <?php }
    load_absence_contact($contact);
}



function load_mandant_list_new($contact)
{
    $translation = \DynCom\mysyde\common\classes\Registry::get("translation");
    $query_contact = "SELECT * FROM main_contact_department WHERE main_contact_id = '" . $contact['id'] . "'";
    $result_contact = @mysqli_query($GLOBALS['mysql_con'], $query_contact);
    $contacts = [];
    while ($contact_link = @mysqli_fetch_assoc($result_contact)) {
        $contacts[] = $contact_link;
    }
    for ($i = 1; $i < 10; $i++) {



        // $check_active = ($contact_link['active'] == 1) ? 'checked' : '';

        // $query_department = "SELECT DISTINCT main_department.id, main_department.description AS name FROM main_department LEFT JOIN main_department_mandant_link ON main_department.id = main_department_mandant_link.main_department_id WHERE main_mandant_id = ".$mandant_id;
        $query_department = "SELECT DISTINCT main_department.id, main_department.description AS name FROM main_department";
        $query_role = "SELECT id,description AS name FROM main_role";

        $query_bereich = "SELECT * FROM `organogramm_space`";
        $query_einricht = "SELECT * FROM `organigramm_einricht`";
        $query_mandant = "SELECT * FROM `main_mandant`";
        $found = false;
        $mandant = "0";
        $department = "0";
        $bereich = "0";
        $einricht = "0";
        $role = "0";
        $phone = "";
        $email = "";
        foreach ($contacts as $contact) {
            if (isset($contact["sorting"]) && $contact["sorting"] == $i) {
                $found = true;
                $mandant = $contact["main_mandant_id"];
                $department = $contact["main_department_id"];
                $bereich = $contact["main_bereich_id"];
                $einricht = $contact["main_einricht_id"];
                $role = $contact["main_role_id"];
                $phone = $contact["phone_no"];
                $email = $contact["email"];
                break;
            }
        }
        ?>
        <tr>
            <td><?= input_select_from_sql_mandant("", "input_mandant_" . $i, $query_mandant, $mandant, FALSE, FALSE, "", TRUE); ?>
            </td>
            <td><?= input_select_from_sql("", "input_department_" . $i, $query_department, $department, FALSE, FALSE, "", TRUE); ?>
            </td>
            <td><?= input_select_from_sql_bereich("", "input_bereiche_" . $i, $query_bereich, $bereich, FALSE, FALSE, "", TRUE); ?>
            </td>
            <td><?= input_select_from_sql_ein("", "input_einrichtung_" . $i, $query_einricht, $einricht, FALSE, FALSE, "", TRUE); ?>
            </td>
            <td><?= input_select_from_sql("", "input_role_" . $i, $query_role, $role, FALSE, FALSE, "", TRUE); ?></td>
            <td style="display: none;"><?= input("", "input_phone_no_" . $i, "text", $phone, 100); ?></td>
            <td style="display: none;"><?= input("", "input_email_" . $i, "text", $email, 100); ?></td>
            <?php if ($GLOBALS['admin_user']['control_permissions'] == 1) { ?>
                <td><button class="pop_up_button svg_button" title="Berechtigung ändern"
                        data-popup-id="popup-mandant-<?= $mandant ?>"><svg xmlns="http://www.w3.org/2000/svg" width="28.8"
                            height="35.25" viewBox="0 0 28.8 35.25">
                            <path id="shield-security"
                                d="M14.4.375l14.4,6.45v9.6a19.876,19.876,0,0,1-4.125,12.188A17.908,17.908,0,0,1,14.4,35.625,17.912,17.912,0,0,1,4.125,28.612,19.875,19.875,0,0,1,0,16.425v-9.6ZM14.4,18V3.9L3.225,8.85V18H14.4V32.325a15.292,15.292,0,0,0,7.5-5.4A17.845,17.845,0,0,0,25.575,18Z"
                                transform="translate(0 -0.375)" />
                        </svg>
                    </button>
                </td>
            <?php } ?>
        </tr>
    <?php
    }
}


function load_permission($contact)
{
    $translation = \DynCom\mysyde\common\classes\Registry::get("translation");

    $query_mandant = "SELECT * FROM main_mandant";
    $result_mandant = @mysqli_query($GLOBALS['mysql_con'], $query_mandant);
    while ($mandant = @mysqli_fetch_array($result_mandant)) {
        $mandant_id = $mandant['id'];
        ?>
        <div class='pop_up_element' id='popup-mandant-<?= $mandant_id ?>'>
            <table class="mandant_table">
                <thead>
                    <tr>
                        <th>Berechtigungen für: <span style="font-weight: bold;"><?= $mandant['description'] ?></span></th>
                        <th style="text-align: right;">Status</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    $query = "SELECT * FROM main_permission";
                    $result = @mysqli_query($GLOBALS['mysql_con'], $query);
                    while ($permission = @mysqli_fetch_array($result)) {
                        $check_permission = ($permission['default_active'] == 1) ? 'checked' : '';
                        if (!empty($contact['id'])) {
                            $query_contact = "SELECT * FROM main_contact_permission WHERE main_contact_id = " . intval($contact['id']) . " AND main_mandant_id = " . intval($mandant_id) . " AND main_permission_id = " . intval($permission['id']);
                            $result_contact = @mysqli_query($GLOBALS['mysql_con'], $query_contact);
                            $row = @mysqli_fetch_array($result_contact);
                        } else {
                            $result_contact = false;
                        }
                        if ($result_contact && @mysqli_num_rows($result_contact) == 1) {
                            $check_permission = ($row['active'] == 1) ? 'checked' : '';
                        }
                        ?>
                        <?php if ($permission['only_main_mandant'] == 1 && $mandant_id != $contact['master_mandant_id']) { ?>
                            <tr class='inactive' title='Dieses Berechtigung kann nur im Hauptmandanten geändert werden'>
                            <?php } else { ?>
                            <tr>
                            <?php } ?>
                            <td><?= $permission['description'] ?></td>
                            <td class="watch_state_td" style="text-align: right;"><input class="checkbox_square watch_state"
                                    type="checkbox" name="active_<?= $mandant_id ?>_<?= $permission['id'] ?>" <?= $check_permission ?>>
                            </td>
                        </tr>
                        <?php
                    }
                    ?>
                </tbody>
            </table>
        </div>
    <?php }
}

function save_permission($contact_id)
{
    $deleteLink = @mysqli_query($GLOBALS["mysql_con"], "DELETE FROM main_contact_permission WHERE main_contact_id=" . $contact_id);

    $query_mandant = "SELECT * FROM main_mandant";
    $result_mandant = @mysqli_query($GLOBALS['mysql_con'], $query_mandant);
    while ($mandant = @mysqli_fetch_array($result_mandant)) {
        $query = "SELECT * FROM main_permission";
        $result = @mysqli_query($GLOBALS['mysql_con'], $query);
        while ($permission = @mysqli_fetch_array($result)) {
            $active = ($_POST["active_" . $mandant['id'] . "_" . $permission['id']] == "on") ? '1' : '0';
            $query = "INSERT INTO main_contact_permission
            (main_contact_id, main_mandant_id, main_permission_id, active)
            VALUES (
                " . $contact_id . ",
                '" . $mandant['id'] . "',
                '" . $permission['id'] . "',
                '" . $active . "'
            )";
            @mysqli_query($GLOBALS['mysql_con'], $query);
        }
    }
}
?>

<script>
    $(document).ready(function () {
        // Funktion zur Aktualisierung des Status für eine einzelne Checkbox
        function updateStatus(checkbox) {
            if (checkbox.is(':checked')) {
                // Wenn die Checkbox ausgewählt ist, entfernen Sie das vorherige "inactive" span und fügen Sie ein "active" span hinzu
                checkbox.siblings('.inactive').remove();
                checkbox.after('<span class="active_span">Aktiv</span>');
            } else {
                // Wenn die Checkbox nicht ausgewählt ist, entfernen Sie das vorherige "active" span und fügen Sie ein "inactive" span hinzu
                checkbox.siblings('.active_span').remove();
                checkbox.after('<span class="inactive">Inaktiv</span>');
            }
        }

        // Überwachen Sie Änderungen am Status der Checkbox
        $('.watch_state').change(function () {
            // Rufen Sie die Funktion auf, um den Status nur für die angeklickte Checkbox zu aktualisieren
            updateStatus($(this));
        });

        // Rufen Sie die Funktion zum ersten Mal auf, um den Anfangszustand festzulegen
        $('.watch_state').each(function () {
            updateStatus($(this));
        });
    });

</script>

<?php
function load_absence_contact($main_contact)
{
    $query = "SELECT * FROM main_contact";
    $result_contact = @mysqli_query($GLOBALS['mysql_con'], $query);

    $preselect = array();

    $contact_array = explode(",", $main_contact['absence_contact']);

    foreach ($contact_array as $contact) {
        array_push($preselect, $contact);
    }
    ?>
    <!-- <div class="label">Ansprechpartner Krankmeldung</div>
    <div class="contacts bc-select-ui ui fluid multiple search selection dropdown" style="clear:both;display:inline-block;">
        <input type="hidden" name="absence_contact">
        <i class="dropdown icon"></i>
        <div class="default text">Ansprechpartner Krankmeldung</div>
        <div class="menu">
            <?
            while ($contacts = @mysqli_fetch_array($result_contact)) {
                echo "<div class=\"item\" data-value=\"{$contacts['id']}\">" . $contacts["name"] . "</div>";
            }
            ?>
        </div>
    </div> -->
    <script type="text/javascript" src="/plugins/jquery/jquery-3.5.1.min.js"></script>
    <script type="text/javascript" src="/plugins/Semantic-UI-master/semantic.min.js"></script>
    <link rel="stylesheet" type="text/css"
        href="/plugins/Semantic-UI-master/bc-semantic.css?time=<?= filemtime($_SERVER['DOCUMENT_ROOT'] . '/plugins/Semantic-UI-master/bc-semantic.css') ?>">
    <script>
        var $y = jQuery.noConflict();
        $y(document).ready(function () {
            $y('.contacts.ui.fluid.multiple.dropdown').dropdown('set selected', <?= json_encode($preselect) ?>);
        });
    </script>
    <?php
}

// function updateFromJSON() {
//    // Alle Einträge aus main_contact abfragen
//    $query = "SELECT * FROM main_contact";
//    $result = @mysqli_query($GLOBALS['mysql_con'], $query);

//    if ($result) {
//        while ($row = mysqli_fetch_assoc($result)) {
//            $contact_id = $row['id'];
//            $email = $row['email'];

//            // Überprüfen, ob ein Eintrag in main_contact_department existiert
//            $checkQuery = "SELECT * FROM main_contact_department WHERE main_contact_id = '$contact_id'";
//            $checkResult = @mysqli_query($GLOBALS['mysql_con'], $checkQuery);

//            if ($checkResult->num_rows == 0) {
//                // Eintrag existiert nicht, neuen Eintrag erstellen
//                $insertQuery = "INSERT INTO main_contact_department 
//                                (main_contact_id, main_mandant_id, main_department_id, main_role_id, main_bereich_id, main_einricht_id, phone_no, email, active) 
//                                VALUES 
//                                ('$contact_id', 1, 13, 13, 3, 1, '', '$email', 1)";

//                if (@mysqli_query($GLOBALS['mysql_con'], $insertQuery)) {
//                    echo "Eintrag für Kontakt-ID $contact_id in main_contact_department erstellt.<br>";
//                } else {
//                    echo "Fehler beim Erstellen des Eintrags für Kontakt-ID $contact_id: " . mysqli_error($GLOBALS['mysql_con']) . "<br>";
//                }
//            }
//        }
//    } else {
//        echo "Fehler beim Abrufen der Kontakte: " . mysqli_error($GLOBALS['mysql_con']) . "<br>";
//    }
// }
// function updateFromJSON() {
//     // JSON-Daten laden
//     $json_file_path = "https://awo-hamburg.breadcrumb-online.de/mysyde/intranet/admin/awo_hamburg_benutzer.json";
//     $json_data = file_get_contents($json_file_path);

//     // Überprüfen, ob die Daten erfolgreich geladen wurden
//     if ($json_data === false) {
//         die("Fehler beim Laden der JSON-Datei.");
//     }

//     // JSON-Daten parsen
//     $data = json_decode($json_data, true);

//     // Überprüfen, ob das Parsen erfolgreich war
//     if ($data === null) {
//         die("Fehler beim Parsen der JSON-Daten: " . json_last_error_msg());
//     }

//     $new_entries_count = 0;

//     // Überprüfen, ob der 'users'-Schlüssel vorhanden ist
//     if (!isset($data['users']) || !is_array($data['users'])) {
//         die("Keine Benutzerdaten gefunden.");
//     }

//     // Durchlaufen der Benutzerdaten
//     foreach ($data['users'] as $user) {

//         $displayName = mysqli_real_escape_string($GLOBALS['mysql_con'], $user['displayName']);
//         $mail = mysqli_real_escape_string($GLOBALS['mysql_con'], $user['mail']);
//         $surname = mysqli_real_escape_string($GLOBALS['mysql_con'], $user['surname']);
//         $telephoneNumber = mysqli_real_escape_string($GLOBALS['mysql_con'], $user['telephoneNumber']);
//         $azureId = mysqli_real_escape_string($GLOBALS['mysql_con'], $user['id']); // Azure ID aus der JSON

//         // Abfrage, ob der Eintrag bereits existiert
//         $query = "SELECT * FROM main_contact WHERE azure_id = '$azureId'";
//         $result = @mysqli_query($GLOBALS['mysql_con'], $query);

//         if ($result->num_rows > 0) {
//             // Eintrag existiert bereits
//             //echo "Eintrag für $displayName existiert bereits. Keine Aktion erforderlich.<br>";
//         } else {
//             // Eintrag existiert nicht, neuen Eintrag erstellen
//             $query = "INSERT INTO main_contact (name, email, shortcut, phone_no, master_mandant_id, current_mandant_id, active, azure_id) 
//                       VALUES ('$displayName', '$mail', '$surname', '$telephoneNumber', 12, 12, 1, '$azureId')";

//             if (@mysqli_query($GLOBALS['mysql_con'], $query)) {
//                 $new_entries_count++;
//             }
//         }
//     }

//     // Gesamtmeldung
//     if ($new_entries_count > 0) {
//         echo "Es wurden $new_entries_count neue Einträge erfolgreich hinzugefügt.";
//     } else {
//         echo "Keine neuen Einträge hinzugefügt.";
//     }
// }
