<?php
$current_date = new DateTime();
$contact_id = $GLOBALS['main_contact']['id'];

if (isset($_GET['contact'])) {
    $contact_id = $_GET['contact'];
}

// Sanitize contact ID for safe use in SQL query
$contact_id = mysqli_real_escape_string($GLOBALS['mysql_con'], $contact_id);
$query = "SELECT *, main_contact.id as 'contact_id' FROM main_contact 
          LEFT JOIN main_contact_profile_content ON main_contact_profile_content.main_contact_id = main_contact.id 
          WHERE main_contact.id = '$contact_id'";

$result = mysqli_query($GLOBALS['mysql_con'], $query);
if (!$result) {
    die('Invalid query: ' . mysqli_error($GLOBALS['mysql_con']));
}
$contact = mysqli_fetch_array($result);

$contact_image = "platzhalter.png";
if (!empty($contact['image'])) {
    $contact_image = $contact['image'];
}

$contact_header_img = "contact_banner.jpg";
// if (!empty($contact['header_img'])) {
//     $contact_header_img = $contact['header_img'];
// }

$birthday = new DateTime($contact['birthday']);
$birthday_content = '';
if ($contact['birthday_state'] == 2) {
    $years = $birthday->diff($current_date);
    $birthday_content = $birthday->format("d.m.Y") . ", " . $years->y;
} elseif ($contact['birthday_state'] == 1) {
    $birthday_content = $birthday->format("d.m");
}

if (isset($_POST['input_submit'])) {
    $birthday = new DateTime($_POST['input_birthday']);

    if (!empty($_POST['input_password'])) {
        $password = password_hash($_POST['input_password'], PASSWORD_DEFAULT);
        $query = "UPDATE main_contact SET password = '" . mysqli_real_escape_string($GLOBALS['mysql_con'], $password) . "' 
                  WHERE id = '" . mysqli_real_escape_string($GLOBALS['mysql_con'], $contact['id']) . "' LIMIT 1";
        mysqli_query($GLOBALS['mysql_con'], $query);
    }

    $query = "UPDATE main_contact SET
                birthday = '" . mysqli_real_escape_string($GLOBALS['mysql_con'], $birthday->format('Y-m-d')) . "',
                birthday_state = '" . mysqli_real_escape_string($GLOBALS['mysql_con'], $_POST['input_birthday_state']) . "'
                WHERE id = '" . mysqli_real_escape_string($GLOBALS['mysql_con'], $contact_id) . "' LIMIT 1";
    mysqli_query($GLOBALS['mysql_con'], $query);

    if (isset($_FILES['input_image']) && $_FILES['input_image']['size'] != 0) {
    // Save uploaded image
    $fileName = saveImage('input_image', $contact_id);

    // Escape values
    $fileEsc      = mysqli_real_escape_string($GLOBALS['mysql_con'], $fileName);
    $contactIdEsc = mysqli_real_escape_string($GLOBALS['mysql_con'], $contact_id);

    // UPDATE: set image_new and image_state for moderation
    $query = "
        UPDATE main_contact SET
            image_new   = '{$fileEsc}',
            image_state = 'approve_required'
        WHERE id = '{$contactIdEsc}'
        LIMIT 1
    ";

    mysqli_query($GLOBALS['mysql_con'], $query);

    sendPhotoApproveMail((int)$contact_id);
    }

    if (isset($_FILES['input_header_image']) && $_FILES['input_header_image']['size'] != 0) {
        $fileName = saveImage('input_header_image', $contact_id);
    
        // Check if the record exists
        $check_query = "SELECT * FROM main_contact_profile_content 
                        WHERE main_contact_id = '" . mysqli_real_escape_string($GLOBALS['mysql_con'], $contact_id) . "'";
        $check_result = mysqli_query($GLOBALS['mysql_con'], $check_query);
    
        if (mysqli_num_rows($check_result) > 0) {
            // Record exists, perform an update
            $query_image = "UPDATE main_contact_profile_content SET
                            header_img = '" . mysqli_real_escape_string($GLOBALS['mysql_con'], $fileName) . "'
                            WHERE main_contact_id = '" . mysqli_real_escape_string($GLOBALS['mysql_con'], $contact_id) . "'";
            mysqli_query($GLOBALS['mysql_con'], $query_image);
        } else {
            // No record exists, perform an insert
            $query_image = "INSERT INTO main_contact_profile_content (main_contact_id, header_img)
                            VALUES (
                                '" . mysqli_real_escape_string($GLOBALS['mysql_con'], $contact_id) . "',
                                '" . mysqli_real_escape_string($GLOBALS['mysql_con'], $fileName) . "'
                            )";
            mysqli_query($GLOBALS['mysql_con'], $query_image);
        }
    
        // Optional: Check for errors
        if (mysqli_error($GLOBALS['mysql_con'])) {
            echo "Error: " . mysqli_error($GLOBALS['mysql_con']);
        }
    }

    $query_content = "UPDATE main_contact_profile_content SET
                        contact_description = '" . mysqli_real_escape_string($GLOBALS['mysql_con'], $_POST['input_contact_description']) . "'
                        WHERE main_contact_id = '" . mysqli_real_escape_string($GLOBALS['mysql_con'], $contact_id) . "' LIMIT 1";
    mysqli_query($GLOBALS['mysql_con'], $query_content);

    save_contact_department($contact['id']);

    $skills = rtrim($_POST['input_tags_hidden'], ',');
    $skillArray = explode(',', $skills);
    if (!empty($skillArray) && is_array($skillArray)) {
        mysqli_query($GLOBALS['mysql_con'], "DELETE FROM main_contact_skills WHERE main_contact_id='" . mysqli_real_escape_string($GLOBALS['mysql_con'], $contact['id']) . "'");
        foreach ($skillArray as $skill_value) {
            $query = "INSERT INTO main_contact_skills (main_contact_id, description)
                      VALUES ('" . mysqli_real_escape_string($GLOBALS['mysql_con'], $contact['id']) . "', '" . mysqli_real_escape_string($GLOBALS['mysql_con'], $skill_value) . "')";
            mysqli_query($GLOBALS['mysql_con'], $query);
        }
    }

    $host = $_SERVER['HTTP_HOST'];
    $uri = $_SERVER['REDIRECT_URL'];
    echo "<script type='text/javascript'>window.location.href = 'https://$host$uri';</script>";
}

function sendPhotoApproveMail(int $contactId) {
    if (empty($GLOBALS['mysql_con'])) {
        return;
    }

    $sql = "SELECT name, email FROM main_contact WHERE id = {$contactId} LIMIT 1";
    $res = mysqli_query($GLOBALS['mysql_con'], $sql);
    $u = mysqli_fetch_assoc($res);

    $username  = $u['name']  ?? 'Unbekannt';
    $userEmail = $u['email'] ?? '';

    $to = "help-intranet@awo-hamburg.de"; 

    $subject = "Neue Foto-Anfrage zur Freigabe von {$username}";

    $message =
        "Hallo,\n\n" .
        "Der Benutzer '{$username}' hat ein neues Profilfoto hochgeladen.\n" .
        "Bitte prüfen und freigeben oder ablehnen:\n" .
        "Benutzer Email: {$userEmail}\n" .
        "Viele Grüße\n" .
        "Intranet System";

    // Headers
    $headers  = "From: intranet@awo-hamburg.de\r\n"; 
    $headers .= "Content-Type: text/plain; charset=utf-8\r\n";

    @mail($to, $subject, $message, $headers);
}

function saveImage($filekey, $input_id) {
    $translation = \DynCom\mysyde\common\classes\Registry::get("translation");

    $allowed_extensions = ['jpg', 'jpeg', 'gif', 'png'];
    $filename = strtolower($_FILES[$filekey]['name']);
    $filename_expl = pathinfo($filename);
    
    if (!in_array($filename_expl['extension'], $allowed_extensions)) {
        echo "<div class='errorbox'>" . $translation->get("error_slideshow_line2") . "</div>\n";
        return false;
    }

    // Generate a unique filename
    $saveFilename = $input_id . "_" . time() . "_" . cleanFilename($_FILES[$filekey]['name']);

    // Get image dimensions
    list($width, $height) = getimagesize($_FILES[$filekey]['tmp_name']);

    // Calculate new dimensions
    $max_size = 1000;
    if ($width > $max_size || $height > $max_size) {
        $ratio = $width / $height;
        if ($ratio > 1) {
            $new_width = $max_size;
            $new_height = $max_size / $ratio;
        } else {
            $new_width = $max_size * $ratio;
            $new_height = $max_size;
        }
    } else {
        $new_width = $width;
        $new_height = $height;
    }

    // Create a new image resource
    $src_image = null;
    switch ($filename_expl['extension']) {
        case 'jpg':
        case 'jpeg':
            $src_image = imagecreatefromjpeg($_FILES[$filekey]['tmp_name']);
            break;
        case 'png':
            $src_image = imagecreatefrompng($_FILES[$filekey]['tmp_name']);
            break;
        case 'gif':
            $src_image = imagecreatefromgif($_FILES[$filekey]['tmp_name']);
            break;
    }

    // Create a blank canvas for the resized image
    $dst_image = imagecreatetruecolor($new_width, $new_height);

    // Preserve transparency for PNG and GIF
    if ($filename_expl['extension'] == 'png' || $filename_expl['extension'] == 'gif') {
        imagealphablending($dst_image, false);
        imagesavealpha($dst_image, true);
        $transparent = imagecolorallocatealpha($dst_image, 255, 255, 255, 127);
        imagefilledrectangle($dst_image, 0, 0, $new_width, $new_height, $transparent);
    }

    // Resize the image
    imagecopyresampled($dst_image, $src_image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

    // Save the resized image
    require_once("../../mysyde/intranet/admin/intranet_config.inc.php");
    if ($filename_expl['extension'] == 'jpg' || $filename_expl['extension'] == 'jpeg') {
        imagejpeg($dst_image, PATH_CONTACT . $saveFilename);
    } elseif ($filename_expl['extension'] == 'png') {
        imagepng($dst_image, PATH_CONTACT . $saveFilename);
    } elseif ($filename_expl['extension'] == 'gif') {
        imagegif($dst_image, PATH_CONTACT . $saveFilename);
    }

    // Free up memory
    imagedestroy($src_image);
    imagedestroy($dst_image);

    return $saveFilename;
}

function save_contact_department($contact_id) {
    $contact_id = mysqli_real_escape_string($GLOBALS['mysql_con'], $contact_id);

    $query = "SELECT * FROM main_contact_department 
              LEFT JOIN main_mandant ON main_contact_department.main_mandant_id = main_mandant.id 
              WHERE main_contact_id = '$contact_id' 
              AND main_contact_department.active = 1";
    
    $result = mysqli_query($GLOBALS['mysql_con'], $query);
    
    while ($contact = mysqli_fetch_array($result)) {
        $mandant_id = $contact['main_mandant_id'];

        $phone_no = mysqli_real_escape_string($GLOBALS['mysql_con'], $_POST['input_phone_no_' . $mandant_id]);
        $email = mysqli_real_escape_string($GLOBALS['mysql_con'], $_POST['input_email_' . $mandant_id]);

        $query_department = "UPDATE main_contact_department SET
                             phone_no = '$phone_no',
                             email = '$email'
                             WHERE main_contact_id = '$contact_id' AND main_mandant_id = '$mandant_id' LIMIT 1";
        
        mysqli_query($GLOBALS['mysql_con'], $query_department);
    }
}

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'] ?? "";
}

?>

<div class="profil_container">

        <div class='profil_header'>
            <div class="profil_bg_group">
            <img class="profil_bg" src='/userdata/intranet/contact/<?= $contact_header_img  ?>'>
            </div>

            <img class="profil_img" src='/userdata/intranet/contact/<?= $contact_image?>'>
            <h2><?= $contact['name'] ?></h2>
            
            <p class="profil_role" style="font-size: 14px;"><?= get_person_space($GLOBALS['main_contact']['current_mandant_id'], $contact['contact_id']) ?></p>
            <p class="profil_role"><?= get_person_einricht($GLOBALS['main_contact']['current_mandant_id'], $contact['contact_id']) ?> - <?= get_person_role($GLOBALS['main_contact']['current_mandant_id'], $contact['contact_id']) ?></p>
            <?php if (!empty($contact['email'])): ?>
                <a class="profil_info_link" href="mailto:<?= $contact['email'] ?>"><?= $contact['email'] ?></a>
            <?php endif; ?>  
            <?php if (!empty($contact['phone_no'])): ?>
                <a class="profil_info_link" href="tel:<?= $contact['phone_no'] ?>"><?= $contact['phone_no'] ?></a>
            <?php endif; ?>  
            <?php if (!empty($contact['cost_center'])): ?>
                <p class="profil_cost_center">Kostenstelle: <?= $contact['cost_center'] ?></p>
            <?php endif; ?>  
            <?php if (!empty($birthday_content)): ?>
                <p class="profil_birthday">Geburtstag: <?= $birthday_content ?></p>
            <?php endif; ?>      
                <p class="profil_info_link"><?= $contact['address'] ?>, <?= $contact['post_code'] ?> <?= $contact['city'] ?></p>
            <p class="profil_desc">
                <svg xmlns="https://www.w3.org/2000/svg" width="20.356" height="19" viewBox="0 0 20.356 19">
                    <g id="network-4" transform="translate(-2.25 -2.25)">
                        <path id="Pfad_74" data-name="Pfad 74" d="M24.089,28.357A1.357,1.357,0,1,1,22.732,27,1.357,1.357,0,0,1,24.089,28.357Z" transform="translate(-7.589 -9.821)"/>
                        <path id="Pfad_75" data-name="Pfad 75" d="M24.089,5.857A1.357,1.357,0,1,1,22.732,4.5,1.357,1.357,0,0,1,24.089,5.857Z" transform="translate(-7.589 -0.893)"/>
                        <path id="Pfad_76" data-name="Pfad 76" d="M4.964,17.107A1.357,1.357,0,1,1,3.607,15.75,1.357,1.357,0,0,1,4.964,17.107Z" transform="translate(0 -5.357)"/>
                        <path id="Pfad_77" data-name="Pfad 77" d="M20.786,9.036a2.711,2.711,0,0,0-2.618,2.036H15.261a2.691,2.691,0,0,0-3.726-1.793L9.38,6.584a2.716,2.716,0,1,0-1.057.852l2.155,2.694a2.663,2.663,0,0,0,0,3.24L8.323,16.063a2.687,2.687,0,0,0-1.109-.242,2.742,2.742,0,1,0,2.165,1.095l2.155-2.694a2.691,2.691,0,0,0,3.726-1.794h2.907a2.709,2.709,0,1,0,2.618-3.393ZM5.857,4.964A1.357,1.357,0,1,1,7.214,6.321,1.357,1.357,0,0,1,5.857,4.964ZM7.214,19.893a1.357,1.357,0,1,1,1.357-1.357A1.357,1.357,0,0,1,7.214,19.893Zm5.429-6.786A1.357,1.357,0,1,1,14,11.75a1.357,1.357,0,0,1-1.357,1.357Zm8.143,0a1.357,1.357,0,1,1,1.357-1.357,1.357,1.357,0,0,1-1.357,1.357Z" transform="translate(-0.893)"/>
                    </g>
                </svg>

                <?= $contact['contact_description']?>
            </p>


            <?php if(!isset($_GET['contact'])){ ?>
                <button class="profil_settings" onclick='open_cardform()'>Kontoeinstellungen</button>
                <div class='cardform_profil' style='display: none'>
                    <?php require_once('profile_cardform.inc.php')?>
                </div>
            <?php } ?>
        </div>
</div>

<style>
    .profil_cost_center {
        font-size: 14px;
        position: absolute;
        top: 180px;
        right: 20px;
    }
</style>

<script>
    function open_cardform(){
        $('.cardform_profil').show();
        $(".cardform_profil").prependTo("body");
    }

    function close_cardform(){
        $('.cardform_profil').hide();
    }

    $(document).keyup(function(e) {
     if (e.key === "Escape") { 
        close_cardform();
    }
    });


</script>