<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
include '../../db.php';
include '../../shared/functionsinc.php';
include 'users_invitation.php';
include '../helper_functions/data_request.php';
include '../auth/auth_functions.php';

// function isNumberUnique($number, $currentId = null) {
//     $currentpropid = $_SESSION['property'];

//     try {

//         $phoneQuery = "
//             SELECT COUNT(*) AS count 
//             FROM property_users_data 
//             WHERE (mobile_number = :number OR home_number = :number) 
//             AND property_id = :propertyId
//             AND (id != :currentId OR :currentId IS NULL)
//         ";

//         $params = [
//             'number' => $number,
//             'propertyId' => $currentpropid,
//             'currentId' => $currentId
//         ];

//         if ($currentId === null) {
//             unset($params['currentId']);
//         }

//         $phoneCount = fetchSingleDataWithJoins($phoneQuery, $params)['count'];

//         return $phoneCount === 0;
//     } catch (Exception $e) {
//         error_log("Error checking number uniqueness: " . $e->getMessage());
//         return false;
//     }
// }
function isNumberUnique($number, $currentId = null) {

    try {
        $phoneQuery = "
            SELECT COUNT(*) AS count 
            FROM property_users_data 
            WHERE (mobile_number = :number OR home_number = :number) 
            AND NOT (id <=> :currentId)
            AND deleted_at IS NULL
        ";

        $phoneQuery1 = "
            SELECT COUNT(*) AS count 
            FROM multi_prop_users 
            WHERE (mobile_number = :number OR home_number = :number) 
            AND NOT (user_assoc <=> :currentId)
            AND deleted_at IS NULL
        ";
    
        $params = [
            'number' => $number,
            'currentId' => $currentId
        ];
    
        $phoneCount = fetchSingleDataWithJoins($phoneQuery, $params)['count'];
        $phoneCount1 = fetchSingleDataWithJoins($phoneQuery1, $params)['count'];
    
        return ($phoneCount + $phoneCount1) === 0;
    } catch (Exception $e) {
        error_log("Error checking number uniqueness: " . $e->getMessage());
        return false;
    }
}

function isEmailUnique($email, $currentId = null) {
    $currentpropid = $_SESSION['property'];

    try {

        $uemailQuery = "
            SELECT COUNT(*) AS count 
            FROM users 
            WHERE (email = :email)
            AND property_id = :propertyId
            AND (id != :currentId OR :currentId IS NULL)
            AND deleted_at IS NULL
        ";

        $puemailQuery = "
            SELECT COUNT(*) AS count 
            FROM property_users
            WHERE (email = :email)
            AND property_id = :propertyId
            AND (id != :currentId OR :currentId IS NULL)
            AND deleted_at IS NULL
        ";

        $params = [
            'email' => $email,
            'propertyId' => $currentpropid,
            'currentId' => $currentId
        ];

        if ($currentId === null) {
            unset($params['currentId']);
        }

        $uemailCount = fetchSingleDataWithJoins($uemailQuery, $params)['count'];
        $puemailCount = fetchSingleDataWithJoins($puemailQuery, $params)['count'];

        return $uemailCount + $puemailCount === 0;
    } catch (Exception $e) {
        error_log("Error checking email uniqueness: " . $e->getMessage());
        return false;
    }
}

if (isset($_POST['getUsers'])) {

    if (!currentUserHasAccess($pdo, 'users', 'read')) {
        echo json_encode(['error' => 'Access Denied']);
        exit();
    }

    $currentProperty = $_SESSION['property'];

    $propertyUsers = fetchData('property_users', ['property_id' => $currentProperty, 'deleted_at' => null]);

    $propertyUsersData = fetchData('property_users_data', ['property_id' => $currentProperty, 'deleted_at' => null]);

    $propertyUsersDataMapping = [];
    foreach ($propertyUsersData as $userData) {
        $propertyUsersDataMapping[$userData['property_user']] = $userData;
    }

    $mergedPropertyUsers = [];
    foreach ($propertyUsers as $user) {
        if (isset($propertyUsersDataMapping[$user['id']])) {
            $mergedPropertyUsers[] = array_merge($user, $propertyUsersDataMapping[$user['id']]);
        }
    }

    $multiPropUsers = fetchData('multi_prop_users', ['property_id' => $currentProperty, 'status' => 'Active', 'deleted_at' => null]);

    $allUsers = $mergedPropertyUsers; // Start with primary users
    foreach ($multiPropUsers as $multiUser) {
        $propertyUser = fetchData('property_users', ['id' => $multiUser['user_assoc'], 'deleted_at' => null]);

        $multiUserData = [
            'id' => $multiUser['user_assoc'],
            'email' => !empty($propertyUser) ? $propertyUser[0]['email'] : null,
            'role' => $multiUser['role'],
            'role_type' => $multiUser['role_type'],
            'property_id' => $multiUser['property_id'],
            'status' => $multiUser['status'],
            'firstname' => $multiUser['firstname'],
            'lastname' => $multiUser['lastname'],
            'unit' => $multiUser['unit'],
            'street' => $multiUser['street'],
            'mobile_number' => $multiUser['mobile_number'],
            'home_number' => $multiUser['home_number'],
            'home_extension' => $multiUser['home_extension'],
            'photo_loc' => $multiUser['photo_loc']
        ];

        $allUsers[] = $multiUserData;
    }

    $dataToPass = ['status', 'id', 'role', 'property_id', 'role_type', 'firstname', 'lastname', 'unit', 'street', 'mobile_number', 'home_number', 'home_extension', 'photo_loc', 'email'];

    $roles = fetchData('roles', []);
    $customRoles = fetchData('custom_roles', []);

    $rolesMapping = array_column($roles, 'name', 'id');

    $customRolesMapping = [];
    foreach ($customRoles as $customRole) {
        $layer = $customRole['layer'];
        switch ($layer) {
            case 'property':
                $roleName = 'property admin';
                break;
            case 'organization':
                $roleName = 'organization admin';
                break;
            case 'sub_dealer':
                $roleName = 'sub_dealer';
                break;
            case 'dealer':
                $roleName = 'dealer';
                break;
            case 'admin':
                $roleName = 'admin';
                break;
            case 'super_admin':
                $roleName = 'super_admin';
                break;
            default:
                $roleName = $layer;
        }
        $customRolesMapping[$customRole['id']] = $roleName;
    }

    $filteredResults = array_map(function ($row) use ($dataToPass, $rolesMapping, $customRolesMapping) {
        $filteredRow = array_intersect_key($row, array_flip($dataToPass));

        if ($filteredRow['role_type'] == 0) {
            $roleName = isset($rolesMapping[$filteredRow['role']]) ? $rolesMapping[$filteredRow['role']] : null;
        } else {
            $roleName = isset($customRolesMapping[$filteredRow['role']]) ? $customRolesMapping[$filteredRow['role']] : null;
        }

        if ($roleName && in_array($roleName, ['property admin', 'organization admin', 'sub_dealer', 'dealer', 'admin', 'super_admin'])) {
            return null;
        }

        $filteredRow['role_name'] = $roleName;
        return $filteredRow;
    }, $allUsers);

    $filteredResults = array_filter($filteredResults);

    $streetData = fetchData('property_groups', ['property_id' => $currentProperty]);
    $streetMapping = [];
    foreach ($streetData as $street) {
        $streetMapping[$street['id']] = $street['name'];
    }

    foreach ($filteredResults as &$result) {
        if (isset($result['street']) && isset($streetMapping[$result['street']])) {
            $result['street'] = $streetMapping[$result['street']];
        }

        if (isset($result['photo_loc'])) {
            $photoData = fetchData('profile_photo', ['id' => $result['photo_loc']]);
            $result['photo_loc'] = !empty($photoData) ? $photoData[0]['location'] : null;
        }
    }

    echo json_encode(array_values($filteredResults));
    exit();
}

if (isset($_POST['getDeleted'])) {

    if (!currentUserHasAccess($pdo, 'users', 'delete')) {
        echo json_encode(['error' => 'Access Denied']);
        exit();
    }
        
    $uUsersData = fetchData('property_users_data', ['property_id' => $_SESSION['property'], 'deleted_at' => ['IS NOT NULL']]);
    $uUsersF = fetchData('property_users', ['property_id' => $_SESSION['property'], 'deleted_at' => ['IS NOT NULL']]);
    $dataToPass = ['status', 'id', 'role', 'role_type'];

    $roles = fetchData('roles', []);
    $customRoles = fetchData('custom_roles', []);

    $rolesMapping = array_column($roles, 'name', 'id');

    $customRolesMapping = [];
    foreach ($customRoles as $customRole) {
        $layer = $customRole['layer'];

        switch ($layer) {
            case 'property':
                $roleName = 'property admin';
                break;
            case 'organization':
                $roleName = 'organization admin';
                break;
            case 'sub_dealer':
                $roleName = 'sub_dealer';
                break;
            case 'dealer':
                $roleName = 'dealer';
                break;
            case 'admin':
                $roleName = 'admin';
                break;
            case 'super_admin':
                $roleName = 'super_admin';
                break;
            default:
                $roleName = $layer;
        }
        $customRolesMapping[$customRole['id']] = $roleName;
    }

    $filteredResults = array_map(function($row) use ($dataToPass, $rolesMapping, $customRolesMapping) {

        $filteredRow = array_intersect_key($row, array_flip($dataToPass));

        if ($row['role_type'] == 0) {
            $roleName = isset($rolesMapping[$row['role']]) ? $rolesMapping[$row['role']] : null;
        } else {
            $roleName = isset($customRolesMapping[$row['role']]) ? $customRolesMapping[$row['role']] : null;
        }

        if ($roleName && in_array($roleName, ['property admin', 'organization admin', 'sub_dealer', 'dealer', 'admin', 'super_admin'])) {
            return null;
        }

        $filteredRow['role_name'] = $roleName;
        return $filteredRow;
    }, $uUsersF);

    $filteredResults = array_filter($filteredResults);

    $mergedResults = [];
    foreach ($uUsersData as $dataRow) {
        foreach ($filteredResults as $filteredRow) {
            if ($dataRow['property_user'] === $filteredRow['id']) {
                $mergedResults[] = array_merge($dataRow, $filteredRow);
            }
        }
    }

    $streetData = fetchData('property_groups', ['property_id' => $_SESSION['property']]);
    $streetMapping = [];
    foreach ($streetData as $street) {
        $streetMapping[$street['id']] = $street['name'];
    }

    foreach ($mergedResults as &$result) {
        if (isset($result['street']) && isset($streetMapping[$result['street']])) {
            $result['street'] = $streetMapping[$result['street']];
        }
    }

    echo json_encode($mergedResults);
    exit();
}

if (isset($_POST['getStreets'])) {

    if (!currentUserHasAccess($pdo, 'users', 'read')) {
        echo json_encode(['error' => 'Access Denied']);
        exit();
    }

   $streetData = fetchData('property_groups', ['property_id' => $_SESSION['property']]);
   echo json_encode($streetData);
   exit();
}

if (isset($_POST['deleteUser'])) {

    $userId = $_POST['userid'];
    $propertyId = $_POST['property'];

    if (!currentUserHasAccess($pdo, 'users', 'delete')) {
        echo "Access denied! Please wait while being Re-Directed.";
        echo '<meta http-equiv="refresh" content="2">';
        exit();
    }

    try {
        // Check if the user is a primary user for the current property
        $conditions = [
            'id' => $userId,
            'property_id' => $propertyId,
            'deleted_at' => null
        ];
    
        $primaryUser = fetchDataSingle('property_users', $conditions);

        if ($primaryUser) { 
            $a = handlePrimaryPropertyDeletion($userId, $propertyId, "property_user");
            deleteDataAdvanced('property_permissions', [
                'user_id' => $userId,
                'user_type' => 'property_user',
                'property_id' => $propertyId
            ]);

            deleteDataAdvanced('visitors', [
                'user_assoc' => $userId,
                'creator_type' => 'user'
            ]);

        } else {
            if (!softDeleteMultiPropertyUser($userId, $propertyId, "property_user")) {
                throw new Exception("Failed to soft delete the multi-property user.");
            }
            deleteDataAdvanced('property_permissions', [
                'user_id' => $userId,
                'user_type' => 'multi_prop',
                'property_id' => $propertyId
            ]);

            deleteDataAdvanced('visitors', [
                'user_assoc' => $userId,
                'creator_type' => 'multi'
            ]);
        }

        echo json_encode([
            "status" => "redirect",
            "location" => "../../dashboard.php?tab=users"
        ]);
        exit;

    } catch (Exception $e) {
        error_log("Error deleting user: " . $e->getMessage());
        echo 'An error occurred while deleting the user. Please try again later.';
        return;
    }
}

if (isset($_POST['recoverUsers'])) {
    if ($_SESSION['layer'] === 'super_admin' || $_SESSION['layer'] === 'admin') {
        restoreUser($_POST['userid'], $_POST['property']);
        echo 'Success';
        return;
    }else {
        echo 'Access Denied';
    }
}

if (isset($_POST['editUsers'])) {

    if (!currentUserHasAccess($pdo, 'users', 'write')) {
        echo json_encode(['error' => 'Access Denied']);
        exit();
    }

    $userId = $_POST['userid'];
    $currentProperty = $_SESSION['property'];

    $multiPropEntry = fetchData('multi_prop_users', ['user_assoc' => $userId, 'property_id' => $currentProperty, 'status' => 'Active']);

    if (!empty($multiPropEntry)) {

        $editUsersData = [
            'firstname' => $multiPropEntry[0]['firstname'],
            'lastname' => $multiPropEntry[0]['lastname'],
            'unit' => $multiPropEntry[0]['unit'],
            'street' => $multiPropEntry[0]['street'],
            'mobile_number' => $multiPropEntry[0]['mobile_number'],
            'home_number' => $multiPropEntry[0]['home_number'],
            'home_extension' => $multiPropEntry[0]['home_extension'],
            'photo_loc' => $multiPropEntry[0]['photo_loc'],
            'role' => $multiPropEntry[0]['role'],
            'role_type' => $multiPropEntry[0]['role_type'],
            'status' => $multiPropEntry[0]['status'],
            'user_assoc' => $userId
        ];
    } else {

        $editUsersData = fetchData('property_users_data', [
            'property_id' => $currentProperty,
            'property_user' => $userId,
            'deleted_at' => null
        ]);

        if (!empty($editUsersData)) {
            $editUsersData = [
                'firstname' => $editUsersData[0]['firstname'],
                'lastname' => $editUsersData[0]['lastname'],
                'unit' => $editUsersData[0]['unit'],
                'street' => $editUsersData[0]['street'],
                'mobile_number' => $editUsersData[0]['mobile_number'],
                'home_number' => $editUsersData[0]['home_number'],
                'home_extension' => $editUsersData[0]['home_extension'],
                'photo_loc' => $editUsersData[0]['photo_loc'],
                'role' => $editUsersData[0]['role'],
                'role_type' => $editUsersData[0]['custom'],
                'id' => $userId
            ];
        }
    }

    $editUserEmail = fetchData('property_users', ['id' => $userId]);

    if (!empty($editUserEmail)) {
        $editUsersData['email'] = $editUserEmail[0]['email'];
        $editUsersData['status'] = $editUserEmail[0]['status'];
    }

    echo json_encode($editUsersData);
    exit();
}

if (isset($_POST['updateUserBtn'])) {

    if (!currentUserHasAccess($pdo, 'users', 'write')) {
        echo json_encode(['error' => 'Access Denied']);
        exit();
    }

    $cuserId = $_POST['euidstore'];
    $cfirstname = $_POST['firstname'];
    $clastname = $_POST['lastname'];
    $cunit = $_POST['unit'];
    $cstreet = $_POST['streetList'];
    $mobile_number = preg_replace('/\D/', '', $_POST['mobile']);
    $home_number = preg_replace('/\D/', '', $_POST['home']);
    $home_extension = $_POST['home_extension'];
    $cemail = $_POST['uemail'];
    $uRole = $_POST['uroleList'];
    $currentProperty = $_SESSION['property'];

    $multiPropEntry = fetchData('multi_prop_users', ['user_assoc' => $cuserId, 'property_id' => $currentProperty, 'status' => 'Active']);
    $isMultiPropUser = !empty($multiPropEntry);
    $currentuserD = fetchData('property_users', ['id' => $cuserId]);
    $currentEmail = $currentuserD[0]['email'];

    // if (!isNumberUnique($mobile_number, $cuserId)) {
    //     $_SESSION['alert']['message'] = "The Phone Number is already in use.";
    //     $_SESSION['alert']['type'] = "danger";
    //     header("Location: ../../dashboard.php?tab=users");
    //     exit();
    // }

    // if (!isNumberUnique($home_number, $cuserId)) {
    //     $_SESSION['alert']['message'] = "The Phone Number is already in use.";
    //     $_SESSION['alert']['type'] = "danger";
    //     header("Location: ../../dashboard.php?tab=users");
    //     exit();
    // }

    if (!isEmailUnique($cemail, $cuserId)) {
        $_SESSION['alert']['message'] = "The Email Address is already in use.";
        $_SESSION['alert']['type'] = "danger";
        header("Location: ../../dashboard.php?tab=users");
        exit();
    }

    if (substr($uRole, 0, 1) === 'C') {
        $uCustom = 1;
        $uRole = substr($uRole, 1);
    } else {
        $uCustom = 0;
    }

    // try {

        $updateData = [
            'firstname' => $cfirstname,
            'lastname' => $clastname,
            'unit' => $cunit,
            'mobile_number' => $mobile_number,
            'home_number' => $home_number,
            'home_extension' => $home_extension,
            'role' => $uRole,
            'street' => $cstreet,
            ($isMultiPropUser ? 'role_type' : 'custom') => $uCustom
        ];

        if ($isMultiPropUser) {
           
            $table_name = "multi_prop_users";
            $user_data = fetchDataSingle('multi_prop_users', ['user_assoc' => $cuserId, 'property_id', $currentProperty]);
            $whereClause = 'user_assoc = :user_assoc AND property_id = :property_id';
            $whereParams = ['user_assoc' => $cuserId, 'property_id' => $currentProperty];
            updateTable('multi_prop_users', $updateData, $whereClause, $whereParams);
            $email_data_user = fetchDataSingle('property_users', ['id' => $cuserId]);
        } else {

            $table_name = "property_users";
            $user_data = fetchDataSingle('property_users_data', ['property_user' => $cuserId]);
            $whereClause = 'property_user = :property_user';
            $whereParams = ['property_user' => $cuserId];
            updateTable('property_users_data', $updateData, $whereClause, $whereParams);
            $email_data_user = fetchDataSingle('property_users', ['id' => $cuserId]);
            if ($currentEmail !== $cemail) {
                $emailData = ['email' => $cemail];
                updateTable('property_users', $emailData, 'id = :id', ['id' => $cuserId]);
            }

            if ($currentuserD[0]['role'] !== $uRole || $currentuserD[0]['role_type'] !== $uCustom) {
                $roleData = ['role' => $uRole, 'role_type' => $uCustom];
                updateTable('property_users', $roleData, 'id = :id', ['id' => $cuserId]);
            }
        }

        if(isset($email_data_user['id']) && !empty($email_data_user['id'])){
            if($email_data_user['email'] != $cemail){
                createAuditLog($_SESSION["userid"], "Udated user email", "property_users", $oId, $_SESSION["email"]??null, $_SESSION['property'], $email_data_user['email'], $cemail, "Udated user email", "medium", "property_users");
            }
        }

        if(isset($user_data['id']) && !empty($user_data['id'])){
           
            if($user_data['firstname'] != $cfirstname){
               
                createAuditLog($_SESSION["userid"], "Updated Property User First Name", $table_name, $cuserId, $_SESSION["email"]??null, $_SESSION['property'], $user_data['firstname'], $cfirstname, "Updated property user first name", "medium", $table_name);
            }
        
            if($user_data['lastname'] != $clastname){
                
                createAuditLog($_SESSION["userid"], "Updated Property User Last Name", $table_name, $cuserId, $_SESSION["email"]??null, $_SESSION['property'], $user_data['lastname'], $lastname, "Updated property user last name", "medium", $table_name);
            }
            
            if($user_data['unit'] != $cunit){
                createAuditLog($_SESSION["userid"], "Updated Property User Unit", $table_name, $cuserId, $_SESSION["email"]??null, $_SESSION['property'], $user_data['unit'], $cunit, "Updated property user unit", "medium", $table_name);
            }
           
            if($user_data['mobile_number'] != $mobile_number){
                createAuditLog($_SESSION["userid"], "Updated Property User Mobile Number", $table_name, $cuserId, $_SESSION["email"]??null, $_SESSION['property'], $user_data['mobile_number'], $mobile_number, "Updated property user mobile number", "medium", $table_name);
            }

            if($user_data['home_number'] != $home_number){
                createAuditLog($_SESSION["userid"], "Updated Property User Alternate Number", $table_name, $cuserId, $_SESSION["email"]??null, $_SESSION['property'], $user_data['home_number'], $home_number, "Updated property user Alternate number", "medium", $table_name);
            }

            if($user_data['home_extension'] != $home_extension){
                createAuditLog($_SESSION["userid"], "Updated Property User Alternate Number Extension", $table_name, $cuserId, $_SESSION["email"]??null, $_SESSION['property'], $user_data['home_number'], $home_number, "Updated property user Alternate number extension", "medium", $table_name);
            }

            if($user_data['street'] != $cstreet){
                createAuditLog($_SESSION["userid"], "Updated Property User Street", $table_name, $cuserId, $_SESSION["email"]??null, $_SESSION['property'], $user_data['street'], $cstreet, "Updated property user Street", "medium", $table_name);
            }

        }

        $_SESSION['alert'] = [
            "message" => "User updated successfully!",
            "type" => "success"
        ];

        header("Location: ../../dashboard.php?tab=users");
        exit();

    // } catch (Exception $e) {
    //     error_log("Error updating User: " . $e->getMessage());
    //     $_SESSION['alert'] = [
    //         "message" => "Failed to update user. Please try again.",
    //         "type" => "danger"
    //     ];
    //     header("Location: ../../dashboard.php?tab=users");
    //     exit();
    // }
}

if (isset($_POST['resendInvite'])) {
    if (!currentUserHasAccess($pdo, 'users', 'read')) {
        echo json_encode(['error' => 'Access Denied']);
        exit();
    }

    $email = $_POST['email'] ?? '';
    if (empty($email)) {
        echo json_encode(['error' => 'Missing email']);
        exit();
    }

    // Determine user type
    $isPropertyUser = fetchDataSingle('property_invitations', ['email' => $email]);
    $isDealerAdmin = !$isPropertyUser ? fetchDataSingle('dealer_invitations', ['email' => $email]) : null;

    if (!$isPropertyUser && !$isDealerAdmin) {
        echo json_encode(['error' => 'User not found']);
        exit();
    }

    $sendinvite = resendInvitation($email);

    // Log audit for property_users
    if ($isPropertyUser) {
        $user_data = fetchDataSingle('property_invitations', ['email' => $email]);
        if (isset($user_data['id']) && !empty($user_data['id'])) {
            createAuditLog(
                $_SESSION["userid"],
                "Resend Property User Invitation",
                "property_invitations",
                $user_data['id'],
                $email ?? null,
                $_SESSION['property'],
                null,
                null,
                "resend property user invitation",
                "medium",
                "property_invitations"
            );
        }
    }

    // Log audit for dealer_admins
    if ($isDealerAdmin) {
        $dealer_data = fetchDataSingle('dealer_invitations', ['email' => $email]);
        if (isset($dealer_data['id']) && !empty($dealer_data['id'])) {
            createAuditLog(
                $_SESSION["userid"],
                "Resend Dealer Admin Invitation",
                "dealer_invitations",
                $dealer_data['id'],
                $email ?? null,
                null,
                null,
                null,
                "resend dealer admin invitation",
                "medium",
                "dealer_invitations"
            );
        }
    }

    echo $sendinvite;
    exit();
}

// Add Users
if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    if (!currentUserHasAccess($pdo, 'users', 'write')) {
        echo json_encode(['error' => 'Access Denied']);
        exit();
    }
   
    if (isset($_POST['form_id'])) {
        
        $form_id = $_POST['form_id'];
        switch ($form_id) {
            case 'form1':

                $uPhoto = '';// $_POST['photo'];
                $uFName = $_POST['firstname'];
                $uLName = $_POST['lastname'];
                $uUnit = $_POST['unit'];
                // $uStreet = 1;
                $uStreet = $_POST['streetList'];
                $uEmail = $_POST['uemail'];
                $uMobile = preg_replace('/\D/', '', $_POST['mobile']);
                $uHome = preg_replace('/\D/', '', $_POST['home']);
                $home_extension = $_POST['home_extension'];
                $uRole = $_POST['roleList'];
                // $uCustom = $_POST['custom'];
                $uStatus = 2; // not registered
                break;
            
            case 'form2':

                $uPhoto = '';
                $uFName = 'Staff';
                $uLName = 'Staff';
                $uUnit = '1';
                $uStreet = '1';
                $uEmail = $_POST['opemail'];
                $uMobile = preg_replace('/\D/', '', $_POST['opmobile']);;
                $uHome = '';
                $home_extension = NULL;
                $uRole = $_POST['opRoleList'];
                // $uCustom = $_POST['custom'];
                $uStatus = 2; // not registered

                break;

            default:
                echo "Invalid request method.";
                exit();     
        }
    }

    if (!isNumberUnique($uMobile)) {
        $_SESSION['alert'] = [
            "message" => "Mobile Number already exists.",
            "type" => "danger"
        ];
        header("location: ../../dashboard.php?tab=users");
        exit();
    }
    
    $uProperty = $_SESSION['property'];
    
    $uCreated = $_SESSION['userid'];

    if ($_SESSION['layer'] === 'super_admin' || $_SESSION['layer'] === 'admin' || $_SESSION['layer'] === 'dealer') {
        $creator_type = 'users';
    }else if ($_SESSION['layer'] === 'sub_dealer' || $_SESSION['layer'] === 'organization admin') {
        $creator_type = 'dealer_admins';
    }else {
        $creator_type = 'property_users';
    }

    if (substr($uRole, 0, 1) === 'C') {
        $uCustom = 1;
        $uRole = substr($uRole, 1);
    }else {
        $uCustom = 0;
    }
    
    $exists = emailExists($pdo, $uEmail);

    $dealerAdminCheck = fetchData('dealer_admins', ['email' => $uEmail, 'deleted_at' => NULL]);

    if($dealerAdminCheck) {
        $_SESSION['alert'] = [
            "message" => "Email already exists.",
            "type" => "danger"
        ];
        header("location: ../../dashboard.php?tab=users");
        exit();
    }
    
    if ($exists) {
        $existpropid = $exists["property_id"];
        $existid = $exists["id"];
        $user_type = 'multi_property_user';
    
        // Check both primary and multi-property entries for existing active users
        $primaryCheck = $existpropid == $uProperty && is_null($exists['deleted_at']);
        $multiPropCheck = fetchData('multi_prop_users', [
            'user_assoc' => $existid, 
            'property_id' => $uProperty, 
            'deleted_at' => null
        ]);
    
        if ($primaryCheck || $multiPropCheck) {
            $_SESSION['alert'] = [
                "message" => "Email already exists.",
                "type" => "danger"
            ];
            header("location: ../../dashboard.php?tab=users");
            exit();
        }
    

        try {
            $photoData = [
                'user_id' => $existid,
                'user_type' => $user_type,
                'property_id' => $uProperty,
                'location' => $uPhoto,
                'created_by' => $uCreated,
                'creator_type' => $creator_type
            ];
            $photoInsertResult = insertData('profile_photo', $photoData);
            $ulastPhotoInsertId = $photoInsertResult['id'];

            $newpropData = [
                'role' => $uRole,
                'role_type' => $uCustom,
                'property_id' => $uProperty,
                'status' => 'Active',
                'user_assoc' => $existid,
                'firstname' => $uFName,
                'lastname' => $uLName,
                'unit' => $uUnit,
                'street' => $uStreet,
                'mobile_number' => $uMobile,
                'home_number' => $uHome,
                'home_extension' => $home_extension,
                'photo_loc' => $photoInsertResult['id'],
                'created_by' => $uCreated,
                'creator_type' => $creator_type
            ];

            if (insertData('multi_prop_users', $newpropData)) {
                $user_id = getLastInsertId();
                $propName = fetchData('properties', ['id' => $uProperty]);
    
                multipropInvitation($uEmail, $propName[0]['name']);

                $default = fetchDataSingle('property_default_permissions', ['property_id' => $uProperty]);

                if ($default) {
                    $doors = fetchData('hardwares_settings', ['property_id' => $uProperty]);
                    foreach ($doors as $door) {
                        $data = [
                            'property_id' => htmlspecialchars($uProperty, ENT_QUOTES, 'UTF-8'),
                            'user_id' => $user_id,
                            'door_id' => htmlspecialchars($door['id'], ENT_QUOTES, 'UTF-8'),
                            'actions_to_perform' => $default['actions_to_perform'],
                            'is_keep_open_to' => htmlspecialchars($default['is_keep_open_to'], ENT_QUOTES, 'UTF-8'),
                            'is_individual' => htmlspecialchars(0, ENT_QUOTES, 'UTF-8'),
                            'created_by' => htmlspecialchars($_SESSION['userid'], ENT_QUOTES, 'UTF-8'),
                            'user_type' => "multi_prop"
                        ];
                        $stmt = $pdo->prepare("
                            INSERT INTO property_permissions 
                            (property_id, user_id, door_id, :user_type, actions_to_perform, is_keep_open_to, is_individual, created_by, user_type) 
                            VALUES (:property_id, :user_id, :door_id, :user_type, :actions_to_perform, :is_keep_open_to, :is_individual, :created_by)
                        ");

                        $stmt->execute($data);
                    }
                }
                
                createAuditLog($_SESSION["userid"], "Added New User", "multi_prop_users", $user_id, $_SESSION["email"]??null, $_SESSION['property'], null, $uFName . " " . $uLName, "Added new user", "high", "multi_prop_users");
                $_SESSION['alert'] = [
                    "message" => "User has been added successfully!",
                    "type" => "success"
                ];
                header("location: ../../dashboard.php?tab=users");
                exit();
            }
    
            throw new Exception("Failed to add User to Property.");
    
        } catch (Exception $e) {
            $_SESSION['alert'] = [
                "message" => "Failed to add User to Property. Please try again.",
                "type" => "danger"
            ];
    
            header("location: ../../dashboard.php?tab=users");
            exit();
        }
    }
    
    $user_type = 'users';
    $type = 'users';
    $inviteToken = sendInvitation($pdo, $uEmail, $uRole, $uCustom, $uCreated, $creator_type, $type, $uFName, $uProperty);
    
    if (!$inviteToken) {
        $_SESSION['alert'] = [
                "message" => "An Invitation is already present for this Email Address. Please try again.",
                "type" => "danger"
            ];
        header("location: ../../dashboard.php?tab=users");
        exit();
    }

    try {
        $pdo->beginTransaction();

        $userData = [
            'email' => $uEmail,
            'password' => $inviteToken,
            'role' => $uRole,
            'role_type' => $uCustom,
            'status' => $uStatus,
            'property_id' => $uProperty,
            'created_by' => $uCreated,
            'creator_type' => $creator_type
        ];
        $userInsertResult = insertData('property_users', $userData);

        $ulastInsertId = $userInsertResult['id'];
        $u_type = "user";
        if($uRole == 6){
            $u_type = "property admin";
        }

        createAuditLog($_SESSION["userid"], "Added new " . $u_type, "property_users", $ulastInsertId, $_SESSION["email"]??null, $_SESSION['property'], null, $uFName . " " . $uLName, "Added new user", "high", "property_users");
        
        $photoData = [
            'user_id' => $ulastInsertId,
            'user_type' => $user_type,
            'location' => $uPhoto,
            'property_id' => $uProperty,
            'created_by' => $uCreated,
            'creator_type' => $creator_type
        ];
        $photoInsertResult = insertData('profile_photo', $photoData);
        $ulastPhotoInsertId = $photoInsertResult['id'];
    
        $userDataDetails = [
            'property_user' => $ulastInsertId,
            'firstname' => $uFName,
            'lastname' => $uLName,
            'unit' => $uUnit,
            'street' => $uStreet,
            'mobile_number' => $uMobile,
            'home_number' => $uHome,
            'home_extension' => $home_extension,
            'role' => $uRole,
            'custom' => $uCustom,
            'created_by' => $uCreated,
            'creator_type' => $creator_type,
            'property_id' => $uProperty,
            'photo_loc' => $ulastPhotoInsertId
        ];
        insertData('property_users_data', $userDataDetails);

        $default = fetchDataSingle('property_default_permissions', ['property_id' => $uProperty]);

        if ($default) {
            $doors = fetchData('hardwares_settings', ['property_id' => $uProperty]);
            foreach ($doors as $door) {
                $data = [
                    'property_id' => htmlspecialchars($uProperty, ENT_QUOTES, 'UTF-8'),
                    'user_id' => $ulastInsertId,
                    'door_id' => htmlspecialchars($door['id'], ENT_QUOTES, 'UTF-8'),
                    'actions_to_perform' => $default['actions_to_perform'],
                    'is_keep_open_to' => htmlspecialchars($default['is_keep_open_to'], ENT_QUOTES, 'UTF-8'),
                    'is_individual' => htmlspecialchars(0, ENT_QUOTES, 'UTF-8'),
                    'created_by' => htmlspecialchars($_SESSION['userid'], ENT_QUOTES, 'UTF-8'),
                    'user_type' => "property_user"
                ];
                $stmt = $pdo->prepare("
                    INSERT INTO property_permissions 
                    (property_id, user_id, door_id, user_type, actions_to_perform, is_keep_open_to, is_individual, created_by) 
                    VALUES (:property_id, :user_id, :door_id, :user_type, :actions_to_perform, :is_keep_open_to, :is_individual, :created_by)
                ");

                $stmt->execute($data);
            }
        }

        $pdo->commit();
        
        $_SESSION['alert'] = [
            "message" => "User has been added successfully!",
            "type" => "success"
        ];
    
        header("location: ../../dashboard.php?tab=users");
        exit();
    } catch (Exception $e) {
        $pdo->rollBack();
        error_log("Error updating User: " . $e->getMessage());
        $_SESSION['alert'] = [
            "message" => "Failed to add New User. Please try again.",
            "type" => "danger"
        ];
    }
    
} else {
    echo "Invalid request method.";
}
