<?php
// orig working
// session_start();

// if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
//     echo 'Invalid CSRF token';
//     exit;
// }

// $selectedProperty = filter_input(INPUT_POST, 'selectedProperty', FILTER_SANITIZE_FULL_SPECIAL_CHARS);

// if ($selectedProperty) {
//     $_SESSION['property'] = $selectedProperty;
//     echo 'Session variable set successfully';
// } else {
//     echo 'No value received or invalid input';
// }

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
    echo 'Invalid CSRF token';
    exit;
}

include '../auth/auth_functions.php';
include '../../shared/functionsinc.php';

$selectedProperty = filter_input(INPUT_POST, 'selectedProperty', FILTER_SANITIZE_FULL_SPECIAL_CHARS);

if ($selectedProperty) {

    $_SESSION['property'] = $selectedProperty;

    require_once '../../db.php';

    $userId = $_SESSION['userid'];
    $currentLayer = $_SESSION['layer'];

    if (in_array($currentLayer, ['organization admin', 'dealer', 'admin', 'super_admin'])) {

        echo 'Session variable for property updated successfully for admin-level user';
    } else {

        $stmt = $pdo->prepare("
            SELECT firstname, lastname, unit, street, mobile_number, home_number, role, role_type AS custom, photo_loc, 'user' AS layer
            FROM multi_prop_users
            WHERE user_assoc = :userId AND property_id = :propertyId AND status = 'Active'
        ");
        $stmt->execute(['userId' => $userId, 'propertyId' => $selectedProperty]);
        $multiPropData = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($multiPropData) {

            $_SESSION["firstname"] = $multiPropData["firstname"];
            $_SESSION["lastname"] = $multiPropData["lastname"];
            $_SESSION["name"] = $multiPropData["firstname"] . " " . $multiPropData["lastname"];
            $_SESSION["mobilenumber"] = formatPhoneNumber($multiPropData["mobile_number"]);
            $_SESSION["homenumber"] = formatPhoneNumber($multiPropData["home_number"]);
            $_SESSION["role"] = $multiPropData["role"];
            $_SESSION["custom"] = $multiPropData["custom"];
            $_SESSION["propertyUserRole"] = $multiPropData["role"];
            $_SESSION["isPropertyUser"] = false;
            $_SESSION["isMultiPropUser"] = true;
            $_SESSION["photo_loc"] = $multiPropData["photo_loc"];
            // var_dump($multiPropData["photo_loc"]);
            // exit();
            // Fetch avatar or profile image
            $photoLocId = $multiPropData["photo_loc"];
            $photoStmt = $pdo->prepare("SELECT location FROM profile_photo WHERE id = :photoLocId");
            $photoStmt->execute(['photoLocId' => $photoLocId]);
            $photoData = $photoStmt->fetch(PDO::FETCH_ASSOC);
            $_SESSION['user_type'] = $photoData['user_type'];

            if (!empty($photoData) && isset($photoData['location'])) {
                if (strpos($photoData['location'], 'fa') === 0) {
                    $_SESSION['avatar_icon'] = $photoData['location'];
                    unset($_SESSION['profile_image']);
                } else {
                    $_SESSION['profile_image'] = $photoData['location'];
                    unset($_SESSION['avatar_icon']);
                }
            } else {
                // Default values if no photo data is found
                $_SESSION['avatar_icon'] = "fas fa-user";
                unset($_SESSION['profile_image']);
            }
            // var_dump($_SESSION);
            // exit();
            if ($_SESSION["custom"] === 1) {
                $role = getCustomUserRoles($pdo, $_SESSION["role"]);
                $_SESSION["role_id"] = $role["id"];
                $_SESSION["layer"] = ($role["layer"] === "property") ? "property admin" : $role["layer"];
            } else {
                $role = getPropertyUserRoles($pdo, $_SESSION["role"]);
                $_SESSION["layer"] = $role["name"];
                $_SESSION["role_id"] = $role["id"];
            }
        } else {

            $stmt = $pdo->prepare("
                SELECT u.role, d.firstname, d.lastname, d.mobile_number, d.home_number, d.custom, d.photo_loc
                FROM property_users u
                JOIN property_users_data d ON u.id = d.property_user
                WHERE u.id = :userId AND u.property_id = :propertyId AND d.deleted_at IS NULL
            ");
            $stmt->execute(['userId' => $userId, 'propertyId' => $selectedProperty]);
            $userData = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($userData) {
                $_SESSION["firstname"] = $userData["firstname"];
                $_SESSION["lastname"] = $userData["lastname"];
                $_SESSION["name"] = $userData["firstname"] . " " . $userData["lastname"];
                $_SESSION["mobilenumber"] = formatPhoneNumber($userData["mobile_number"]);
                $_SESSION["homenumber"] = formatPhoneNumber($userData["home_number"]);
                $_SESSION["role"] = $userData["role"];
                $_SESSION["custom"] = $userData["custom"];
                $_SESSION["propertyUserRole"] = $userData["role"];
                $_SESSION["isPropertyUser"] = true;
                $_SESSION["isMultiPropUser"] = false;
                $_SESSION["photo_loc"] = $userData["photo_loc"];

                // Fetch avatar or profile image
                $photoLocId = $userData["photo_loc"];
                $photoStmt = $pdo->prepare("SELECT location FROM profile_photo WHERE id = :photoLocId");
                $photoStmt->execute(['photoLocId' => $photoLocId]);
                $photoData = $photoStmt->fetch(PDO::FETCH_ASSOC);
                $_SESSION['user_type'] = $photoData['user_type'];
                
                if ($photoData) {
                    if (strpos($photoData["location"], 'fa') === 0) {
                        $_SESSION["avatar_icon"] = $photoData["location"];
                        unset($_SESSION["profile_image"]);
                    } else {
                        $_SESSION["profile_image"] = $photoData["location"];
                        unset($_SESSION["avatar_icon"]);
                    }
                }
                // var_dump($_SESSION);
                // exit();
                if ($_SESSION["custom"] === 1) {
                    $role = getCustomUserRoles($pdo, $_SESSION["role"]);
                    $_SESSION["layer"] = $role["layer"];
                    $_SESSION["role_id"] = $role["id"];
                } else {
                    $role = getPropertyUserRoles($pdo, $_SESSION["role"]);
                    $_SESSION["layer"] = $role["name"];
                    $_SESSION["role_id"] = $role["id"];
                }
            }
        }

        // Regenerate session ID for security
        session_regenerate_id(true);

        // Generate a new CSRF token
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));

        // echo 'Session variables and CSRF token updated successfully for multi-property user';
    }
} else {
    echo 'No value received or invalid input';
}
?>