<?php
include_once __DIR__ . '/functionsinc.php';
include_once __DIR__ . '/../include/auth/auth_functions.php';

if (session_status() === PHP_SESSION_NONE) session_start();
include_once __DIR__ .'/../include/helper_functions/data_request.php';
include_once __DIR__ .'/../db.php';

$iconClasses = [
    // Solid Style
    "fas fa-user-circle", "fas fa-user", "fas fa-smile", "fas fa-meh", "fas fa-grin",
    "fas fa-star", "fas fa-heart", "fas fa-bell", "fas fa-thumbs-up",
    "fas fa-face-grin", "fas fa-face-grin-beam", "fas fa-face-grin-beam-sweat",
    "fas fa-face-grin-hearts", "fas fa-face-grin-squint", "fas fa-face-grin-squint-tears",
    "fas fa-face-grin-stars", "fas fa-face-grin-tears", "fas fa-face-grin-tongue",
    "fas fa-face-grin-tongue-squint", "fas fa-face-grin-tongue-wink", "fas fa-face-grin-wide",
    "fas fa-face-grin-wink", "fas fa-face-kiss", "fas fa-face-kiss-beam", 
    "fas fa-face-kiss-wink-heart", "fas fa-face-laugh", "fas fa-face-laugh-beam",
    "fas fa-face-laugh-squint", "fas fa-face-laugh-wink", "fas fa-face-meh",
    "fas fa-face-meh-blank", "fas fa-face-rolling-eyes", "fas fa-face-sad-cry",
    "fas fa-face-sad-tear", "fas fa-face-smile", "fas fa-face-smile-beam",
    "fas fa-face-smile-wink", "fas fa-face-surprise", "fas fa-face-tired",
    "fas fa-chess-bishop", "fas fa-chess-board", "fas fa-chess-king", "fas fa-chess-knight",
    "fas fa-chess-pawn", "fas fa-chess-queen", "fas fa-chess-rook", "fas fa-dice", 
    "fas fa-dice-d20", "fas fa-dice-d6", "fas fa-dice-five", "fas fa-dice-four",
    "fas fa-dice-one", "fas fa-dice-six", "fas fa-dice-three", "fas fa-dice-two",
    "fas fa-gamepad", "fas fa-ghost", "fas fa-puzzle-piece", "fas fa-robot",
    "fas fa-rocket", "fas fa-space-shuttle", "fas fa-trophy", "fas fa-user-ninja",
    "fas fa-vr-cardboard", "fas fa-cat", "fas fa-crow", "fas fa-dog", "fas fa-dove",
    "fas fa-dragon", "fas fa-feather", "fas fa-feather-pointed", "fas fa-frog", "fas fa-hippo",
    "fas fa-horse", "fas fa-horse-head", "fas fa-kiwi-bird", "fas fa-otter", "fas fa-paw",
    "fas fa-spider", "fas fa-user-astronaut", "fas fa-user-ninja", "fas fa-id-card",
    "fas fa-paper-plane", "fas fa-motorcycle", "fas fa-plane", "fas fa-jet-fighter",
    "fas fa-helicopter", "fas fa-moon",

    // Regular Style
    "far fa-address-book", "far fa-address-card", "far fa-bell", "far fa-bell-slash",
    "far fa-bookmark", "far fa-building", "far fa-calendar", "far fa-calendar-check",
    "far fa-calendar-days", "far fa-calendar-minus", "far fa-calendar-plus", "far fa-calendar-xmark",
    "far fa-chart-bar", "far fa-circle", "far fa-circle-check", "far fa-circle-dot", "far fa-circle-down", 
    "far fa-circle-left", "far fa-circle-pause", "far fa-circle-play", "far fa-circle-question",
    "far fa-circle-right", "far fa-circle-stop", "far fa-circle-up", "far fa-circle-user", "far fa-circle-xmark",
    "far fa-clipboard", "far fa-clock", "far fa-clone", "far fa-closed-captioning", "far fa-comment", 
    "far fa-comment-dots", "far fa-comments", "far fa-compass", "far fa-copy", "far fa-copyright",
    "far fa-credit-card", "far fa-envelope", "far fa-envelope-open", "far fa-eye", "far fa-eye-slash",
    "far fa-face-angry", "far fa-face-dizzy", "far fa-face-flushed", "far fa-face-frown", "far fa-face-frown-open",
    "far fa-face-grimace", "far fa-face-grin", "far fa-face-grin-beam", "far fa-face-grin-beam-sweat",
    "far fa-face-grin-hearts", "far fa-face-grin-squint", "far fa-face-grin-squint-tears", "far fa-face-grin-stars",
    "far fa-face-grin-tears", "far fa-face-grin-tongue", "far fa-face-grin-tongue-squint", "far fa-face-grin-tongue-wink",
    "far fa-face-grin-wide", "far fa-face-grin-wink", "far fa-face-kiss", "far fa-face-kiss-beam",
    "far fa-face-kiss-wink-heart", "far fa-face-laugh", "far fa-face-laugh-beam", "far fa-face-laugh-squint",
    "far fa-face-laugh-wink", "far fa-face-meh", "far fa-face-meh-blank", "far fa-face-rolling-eyes",
    "far fa-face-sad-cry", "far fa-face-sad-tear", "far fa-face-smile", "far fa-face-smile-beam",
    "far fa-face-smile-wink", "far fa-face-surprise", "far fa-face-tired", "far fa-file", "far fa-file-audio",
    "far fa-file-code", "far fa-file-excel", "far fa-file-image", "far fa-file-lines", "far fa-file-pdf",
    "far fa-file-powerpoint", "far fa-file-video", "far fa-file-word", "far fa-file-zipper", "far fa-flag",
    "far fa-floppy-disk", "far fa-folder", "far fa-folder-open", "far fa-futbol", "far fa-gem", "far fa-hand",
    "far fa-hand-back-fist", "far fa-hand-lizard", "far fa-hand-peace", "far fa-hand-point-down", "far fa-hand-point-left",
    "far fa-hand-point-right", "far fa-hand-point-up", "far fa-hand-pointer", "far fa-hand-scissors", "far fa-hand-spock",
    "far fa-handshake", "far fa-hard-drive", "far fa-heart", "far fa-hospital", "far fa-hourglass", "far fa-hourglass-half",
    "far fa-id-badge", "far fa-id-card", "far fa-image", "far fa-images", "far fa-keyboard", "far fa-lemon",
    "far fa-life-ring", "far fa-lightbulb", "far fa-map", "far fa-message", "far fa-money-bill-1", "far fa-moon",
    "far fa-newspaper", "far fa-note-sticky", "far fa-object-group", "far fa-object-ungroup", "far fa-paper-plane",
    "far fa-pen-to-square", "far fa-rectangle-list", "far fa-rectangle-xmark", "far fa-registered", "far fa-share-from-square",
    "far fa-snowflake", "far fa-square", "far fa-square-caret-down", "far fa-square-caret-left", "far fa-square-caret-right",
    "far fa-square-caret-up", "far fa-square-check", "far fa-square-minus", "far fa-square-plus", "far fa-star",
    "far fa-star-half", "far fa-sun", "far fa-thumbs-down", "far fa-thumbs-up", "far fa-trash-can", "far fa-user",
    "far fa-window-maximize", "far fa-window-minimize", "far fa-window-restore" 
];

$userId = $_SESSION['userid'];
$userLayer = $_SESSION['layer'];
$propDatas = getProperty($userId, $userLayer);
$propDataFull = array("current_site" => $_SESSION['property']);
$propDatas[] = $propDataFull;
$userMenu = getMenuByUser($pdo, $_SESSION["userid"]);
$already_set_preferences = fetchDataSingle('app_settings', ["property_id" => $_SESSION['property'], "userid" => $_SESSION["userid"]]);
$stream_url = fetchDataSingle("stream_url");

$properties = array_filter($propDatas, function($item) {
    return isset($item['id']) && isset($item['name']);
});
?>

<!-- Modals Start-->
<!-- Profile -->
<div class="modal fade" id="profilemodal" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalCenterTitle">Profile</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form action="include/users/profile.php" method="post" enctype="multipart/form-data">
                    <div class="current-avatar text-center">
                        <h4>Profile Avatar</h4>

                        <?php if (!empty($_SESSION['profile_image'])): ?>

                            <img src="/shared/serve_image.php?path=<?php echo urlencode($_SESSION['profile_image']); ?>&type=profile" 
                                alt="Profile Image" class="img-fluid rounded-circle" 
                                style="width: 100px; height: 100px; border: 2px solid #007bff;">
                            <br>
                            <button type="button" class="btn btn-danger mt-3" onclick="deleteProfileImage()">Delete Image</button>
                        <?php elseif (!empty($_SESSION['avatar_icon'])): ?>

                            <i class="<?php echo htmlspecialchars($_SESSION['avatar_icon']); ?> fa-4x"></i>
                        <?php else: ?>

                            <i class="fas fa-user-circle fa-4x"></i>
                        <?php endif; ?>
                        <br>
                        <button type="button" class="btn btn-primary mt-3" data-toggle="modal" data-target="#avatarModal">Change Avatar</button>
                        <br>
                        <br>
                    </div>
                    <div class="text-center mb-2">
                        <label for="profileImageInput" class="form-label"><small class="text-muted">(Max file size: 4MB)</small></label>
                    </div>
                    <input type="file" name="profile_image" accept="image/*" class="form-control mb-3">
                    <div class="input-group mb-3">
                        <input type="text" name="pfname" class="form-control" title="First Name" value="<?php echo $_SESSION['firstname']; ?>">
                        <input type="text" name="plname" class="form-control" title="Last Name" value="<?php echo $_SESSION['lastname']; ?>">
                        <div class="input-group-append">
                            <div class="input-group-text">
                                <span class="fa-solid fa-address-card" title="First & Last Name"></span>
                            </div>
                        </div>
                    </div>
                    <?php if ($_SESSION['layer'] === 'user' || $_SESSION['layer'] === 'property admin'): ?>
                        <div class="input-group mb-3">
                            <?php
                                $mobileNumber = $_SESSION['mobilenumber'];
                            ?>
                            <input type="tel" name="mphone" id="mphone" class="form-control" title="Mobile Number" readonly value="<?php echo $mobileNumber; ?>">

                            <div class="input-group-append">
                                <div class="input-group-text">
                                    <span class="fas fa-mobile-button fa-lg" title="Mobile Number"></span>
                                </div>
                            </div>
                        </div>
                        <div class="input-group mb-3">
                            <input type="tel" name="hphone" id="hphone" class="form-control" title="Home Number" oninput="formatPhoneNumber(this)" onpaste="handlePaste(event)" placeholder="Home Number Optional" value="<?php echo $_SESSION['homenumber']; ?>">
                            <div class="input-group-append">
                                <div class="input-group-text">
                                    <span class="fa-solid fa-phone" title="Home Number"></span>
                                </div>
                            </div>
                        </div>
                    <?php endif; ?>
                    <div class="input-group mb-3">
                        <input type="email" name="pemail" class="form-control" title="Email" disabled value="<?php echo $_SESSION['email']; ?>">
                        <div class="input-group-append">
                            <div class="input-group-text">
                                <span class="fas fa-envelope" title="Email"></span>
                            </div>
                        </div>
                    </div>

                    <div class="input-group mb-3">
                        <button type="button" class="btn btn-primary btn-block" data-toggle="modal" data-target="#changePasswordModal">Change Password</button>
                    </div>

                    <button type="submit" name="submit" class="btn btn-primary btn-block">Update</button>
                </form>

                <form id="deleteImageForm" action="include/users/profile.php" method="post">
                        <input type="hidden" name="delete_image" value="1">
                    </form>
            </div>
        </div>
    </div>
</div>
<!-- End Profile -->

<!-- Start Password -->
<div class="modal fade" id="changePasswordModal" tabindex="-1" role="dialog" aria-labelledby="changePasswordModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="changePasswordModalLabel">Change Password</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form id="changePasswordForm" action="include/users/profile.php" method="post">
                    <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
                    <div class="form-group">
                        <label for="newPassword">New Password</label>
                        <div class="position-relative">
                            <input type="password" class="form-control" name="newPassword" id="newPassword" placeholder="Enter new password" required>
                            <i class="fas fa-eye position-absolute toggle-password" data-target="#newPassword" style="top: 50%; right: 10px; transform: translateY(-50%); cursor: pointer;"></i>
                        </div>
                        <small id="passwordHelp" class="form-text text-muted">Password must be at least 8 characters, include 1 uppercase letter, 1 number, and 1 special character.</small>
                        <progress id="passwordStrength" max="100" value="0" class="w-100"></progress>
                        </div>
                        <div class="form-group">
                        <label for="confirmPassword">Confirm Password</label>
                        <div class="position-relative">
                            <input type="password" class="form-control" name="confirmPassword" id="confirmPassword" placeholder="Confirm new password" required>
                            <i class="fas fa-eye position-absolute toggle-password" data-target="#confirmPassword" style="top: 50%; right: 10px; transform: translateY(-50%); cursor: pointer;"></i>
                        </div>
                    </div>
                    <button type="submit" name="changePasswordSubmit" class="btn btn-primary btn-block">Update Password</button>
                </form>
            </div>
        </div>
    </div>
</div>
<!-- End Password --> 
 
<!-- Preferences -->

<div class="modal fade" id="prefmodal" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalCenterTitle">Preferences</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form class="form-horizontal w-100" id="preferencesForm">
                    <input type="hidden" name="preferencesId" id="preferencesId" value="">

                    <div class="input-group mb-3">
                        <select class="form-control custom-select" name="themeMode" id="themeMode">
                            <option value="" selected disabled>Select theme mode</option>
                            <option value="dark">Dark mode</option>
                            <option value="light">Light mode </option>
                        </select>
                        <select class="form-control custom-select" name="timeFormat" id="timeFormat">
                            <option value="" selected disabled>Select time format</option>
                            <option value="12h">12 hours</option>
                            <option value="24h">24 hours</option>
                        </select>
                        <div class="input-group-append">
                            <div class="input-group-text">
                                <i class="fa-solid fa-hourglass-start"></i>
                            </div>
                        </div>
                    </div>

                    <div class="input-group mb-3">
                        <select class="form-control custom-select" name="autoLogoutTime" id="autoLogoutTime">
                            <option value="" selected disabled>Select auto logout time</option>
                        </select>
                        <select class="form-control custom-select" name="startPage" id="startPage">
                            <option value="" selected disabled>Select starting page</option>
                            <?php
                            foreach ($userMenu as $page) {
                                if (!empty($page['slug']) && !empty($page['name'])) {
                                    echo '<option value="' . htmlspecialchars($page['slug']) . '">' . htmlspecialchars($page['name']) . '</option>';
                                }
                            }
                            ?>
                        </select>
                        <!-- <select class="form-control custom-select" name="startPage" id="startPage">
                            <option value="" selected disabled>Select starting page</option>
                        </select> -->
                        <div class="input-group-append">
                            <div class="input-group-text">
                                <i class="fa-solid fa-address-card"></i>
                            </div>
                        </div>
                    </div>

                    <!-- <div class="input-group mb-3">
                        <select class="form-control custom-select" name="startProperty" id="startProperty">
                            <option value="" selected disabled>Select one</option>
                        </select>
                        <div class="input-group-append">
                            <div class="input-group-text">
                                <i class="fa-solid fa-city"></i>
                            </div>
                        </div>
                    </div> -->

                    <div class="input-group mb-3">
                        <select class="form-control custom-select" name="startProperty" id="startProperty">
                            <option value="" selected disabled>Select one</option>

                            <?php
                            foreach ($properties as $property) {
                                if (isset($property['id']) && isset($property['name'])) {
                                    echo '<option value="' . htmlspecialchars($property['id']) . '">' . htmlspecialchars($property['name']) . '</option>';
                                }
                            }
                            ?>
                        </select>
                        <div class="input-group-append">
                            <div class="input-group-text">
                                <i class="fa-solid fa-city"></i>
                            </div>
                        </div>
                    </div>
                    <div class="input-group mb-3">
                        <select class="form-control custom-select" name="isCardView" id="isCardView">
                            <option value="" selected disabled>Select one</option>
                            <option value="1">Card view</option>
                            <option value="0">Table view</option>
                        </select>
                    </div>

                </form>

            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <button type="button" onclick="submitPreferencesValues()" class="btn btn-primary">Submit</button>
            </div>
        </div>
    </div>
</div>
<!-- End Preferences -->
 <!-- Avatar Selection Modal -->
<div class="modal fade" id="avatarModal" tabindex="-1" role="dialog" aria-labelledby="avatarModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-xl" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="avatarModalLabel">Select a New Avatar</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form id="avatarForm" action="../include/users/profile.php" method="post">
                    <div class="avatar-selection d-flex flex-wrap justify-content-center" style="height: 400px !important;overflow: auto;">
                        <?php 
                        foreach ($iconClasses as $icon): ?>
                            <label class="avatar-option text-center" style="margin: 10px;">
                                <i class="<?php echo $icon; ?> fa-3x" style="cursor: pointer; margin: 10px;"
                                data-icon-class="<?php echo $icon; ?>"
                                onclick="selectAvatar(this)"></i>
                            </label>
                        <?php endforeach; ?>
                    </div>
                    <input type="hidden" name="avatarIcon" id="selectedAvatarIcon">

                    <button type="submit" name="submit" class="btn btn-primary btn-block mt-3">Save Changes</button>
                </form>
            </div>
        </div>
    </div>
</div>
<!-- End Avatar Selection Modal -->
<!-- End Modals -->



<!-- Image preview -->
<div class="modal fade" id="show_image_modal" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle">
    <div class="modal-dialog image-modal-size" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span >&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div id="show_image_in_modal">
                    
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Test Alert Modal -->
<div class="modal fade" id="reusableAlertModal" tabindex="-1" role="dialog" aria-labelledby="reusableAlertModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="reusableAlertModalLabel">Alert</h5>
      </div>
      <div class="modal-body">
        <!-- Text will be injected here -->
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-primary" data-dismiss="modal">OK</button>
      </div>
    </div>
  </div>
</div>
<!-- End Test Alert Modal -->

<!-- Reusable Confirm Modal -->
<div class="modal fade" id="reusableConfirmModal" tabindex="-1" role="dialog" aria-labelledby="reusableConfirmModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="reusableConfirmModalLabel">Confirm Your Action</h5>
        <!-- <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button> -->
      </div>
      <div class="modal-body">
        <!-- Text will be injected here -->
        Are you sure you want to proceed?
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
        <button type="button" class="btn btn-danger" id="reusableConfirmButton">Confirm</button>
      </div>
    </div>
  </div>
</div>
<!-- End Test Confirm Modal -->


<div class="toast-container position-fixed p-3" id="headerToastMessage" style="display:none;z-index: 99999; top: 20px; right: 0px;width:300px">
    <div id="myToast" class="toast bg-danger text-white" role="alert" aria-live="assertive" aria-atomic="true">
        <div class="toast-header d-flex justify-content-between  ">
            <strong class="me-auto">Error</strong>
            <button onclick="closeHeaderToastMessage()" type="button" class="close " data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
        <div class="toast-body" id="headerToastMessageErrorMessage">
            An error occurred! Please check the details and try again.
        </div>
    </div>
</div>


<div class="toast-container position-fixed p-3" id="globalSuccessToastMessage" style="display:none;z-index: 99999; top: 20px; right: 0px;width:300px">
    <div id="global_success_Toast" class="toast bg-success text-white" role="alert" aria-live="assertive" aria-atomic="true">
        <div class="toast-header d-flex justify-content-between  ">
            <strong class="me-auto">Success</strong>
        </div>
        <div class="toast-body" id="globalSuccessMessage">
        </div>
    </div>
</div>


<div class="toast-container position-fixed p-3" id="globalErrorToastMessage" style="display:none;z-index: 99999; top: 20px; right: 0px;width:300px">
    <div id="global_error_Toast" class="toast bg-danger text-white" role="alert" aria-live="assertive" aria-atomic="true">
        <div class="toast-header d-flex justify-content-between  ">
            <strong class="me-auto">Error</strong>
        </div>
        <div class="toast-body" id="globalErrorMessage">
            An error occurred! Please check the details and try again.
        </div>
    </div>
</div>

<div class="modal fade" id="select_property_id_modal" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalCenterTitle">Select property id</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div class="input-group d-flex align-items-center">
                    <meta name="csrf-token" content="<?php echo $_SESSION['csrf_token']; ?>">
                    <label class="custom-label mr-2">Property</label> <!--also have css to remove if not used -->
                    <select id="selectPropertyInModal" onchange="handleChangePropertyInModal()" class="form-control" style="font-size: 1rem;" name="selectPropertyInModal" required></select>

                </div>
            </div>
        </div>
    </div>
</div>