"use strict";
exports.id = 7531;
exports.ids = [7531];
exports.modules = {

/***/ 7531:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  "SingleDbUserContext": () => (/* binding */ SingleDbUserContext),
  "default": () => (/* binding */ DatabaseSingleUserPage),
  "getServerSideProps": () => (/* binding */ getServerSideProps)
});

// EXTERNAL MODULE: external "react/jsx-runtime"
var jsx_runtime_ = __webpack_require__(997);
// EXTERNAL MODULE: external "react"
var external_react_ = __webpack_require__(6689);
var external_react_default = /*#__PURE__*/__webpack_require__.n(external_react_);
// EXTERNAL MODULE: ./layouts/AdminLayout.jsx + 2 modules
var AdminLayout = __webpack_require__(4858);
// EXTERNAL MODULE: ./functions/backend/userAuth.js
var userAuth = __webpack_require__(370);
var userAuth_default = /*#__PURE__*/__webpack_require__.n(userAuth);
// EXTERNAL MODULE: ./components/general/ExtraContentDatabase.jsx
var ExtraContentDatabase = __webpack_require__(4941);
// EXTERNAL MODULE: ./functions/backend/grabDelegatedUserFromCookie.js
var grabDelegatedUserFromCookie = __webpack_require__(5116);
var grabDelegatedUserFromCookie_default = /*#__PURE__*/__webpack_require__.n(grabDelegatedUserFromCookie);
// EXTERNAL MODULE: ./components/general/Breadcrumbs.jsx
var Breadcrumbs = __webpack_require__(424);
// EXTERNAL MODULE: ./components/general/BackButton.jsx
var BackButton = __webpack_require__(1781);
// EXTERNAL MODULE: ./functions/frontend/fetchApi.js
var fetchApi = __webpack_require__(6729);
// EXTERNAL MODULE: ./components/general/LoadingBlock.jsx
var LoadingBlock = __webpack_require__(5264);
// EXTERNAL MODULE: ./components/admin/users/UserImage.jsx
var UserImage = __webpack_require__(2733);
;// CONCATENATED MODULE: ./components/admin/users/SingleDbUserContent.jsx
// @ts-check
/**
 * ==============================================================================
 * Imports
 * ==============================================================================
 */ 







/** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /**
 * ==============================================================================
 * Main Component { Functional }
 * ==============================================================================
 * @param {Object} props - Server props
 */ function SingleDbUserContent(props) {
    /**
     * Get Contexts
     *
     * @abstract { React.useContext }
     */ const { singleUser , database , user  } = external_react_default().useContext(SingleDbUserContext);
    ////////////////////////////////////////
    ////////////////////////////////////////
    ////////////////////////////////////////
    /**
     * Javascript Variables
     *
     * @abstract Non hook variables and functions
     */ const userFields = Object.keys(singleUser).filter((key)=>!key.match(/^id$|^date_|^user_id$|^social_|^disk_usage|user_type/));
    ////////////////////////////////////////
    ////////////////////////////////////////
    ////////////////////////////////////////
    /**
     * React Hooks
     *
     * @abstract { useState, useEffect, useRef, etc ... }
     */ const [loading, setLoading] = external_react_default().useState(false);
    /** @type {[ userImage: any, setUserImage: React.Dispatch<React.SetStateAction<any>> ]} */ // @ts-ignore
    const [userImage, setUserImage] = external_react_default().useState(singleUser["image"]);
    ////////////////////////////////////////
    ////////////////////////////////////////
    ////////////////////////////////////////
    /**
     * Function Return
     *
     * @abstract Main Function Return
     */ return /*#__PURE__*/ (0,jsx_runtime_.jsxs)((external_react_default()).Fragment, {
        children: [
            /*#__PURE__*/ (0,jsx_runtime_.jsxs)("div", {
                className: "flex-col items-start gap-0 w-full",
                children: [
                    /*#__PURE__*/ (0,jsx_runtime_.jsxs)("div", {
                        className: "w-full justify-between flex-wrap",
                        children: [
                            /*#__PURE__*/ (0,jsx_runtime_.jsxs)("div", {
                                children: [
                                    /*#__PURE__*/ jsx_runtime_.jsx(BackButton/* default */.Z, {}),
                                    userImage && /*#__PURE__*/ jsx_runtime_.jsx("img", {
                                        src: userImage,
                                        alt: "",
                                        className: "avatar large outlined"
                                    }),
                                    /*#__PURE__*/ (0,jsx_runtime_.jsxs)("h1", {
                                        className: "text-3xl m-0",
                                        children: [
                                            singleUser.first_name,
                                            " ",
                                            singleUser.last_name
                                        ]
                                    })
                                ]
                            }),
                            /*#__PURE__*/ (0,jsx_runtime_.jsxs)("div", {
                                children: [
                                    /*#__PURE__*/ jsx_runtime_.jsx("a", {
                                        href: `/admin/${user?.id}/databases/${database.db_slug}/users/${singleUser.id}/change-password`,
                                        className: "button outlined gray",
                                        children: "Change Password"
                                    }),
                                    /*#__PURE__*/ jsx_runtime_.jsx("button", {
                                        className: "bg-red-500",
                                        onClick: (e)=>{
                                            setLoading(true);
                                            if (window.confirm("Delete this user?")) {
                                                (0,fetchApi/* default */.Z)("/api/deleteDbUser", {
                                                    method: "post",
                                                    body: {
                                                        userId: singleUser.id,
                                                        dbFullName: database.db_full_name
                                                    }
                                                }, true).then((res)=>{
                                                    if (res.success) window.location.pathname = `/admin/${user?.id}/databases/${database.db_slug}/users`;
                                                });
                                            }
                                        },
                                        children: "Delete User"
                                    })
                                ]
                            })
                        ]
                    }),
                    /*#__PURE__*/ jsx_runtime_.jsx(Breadcrumbs/* default */.Z, {
                        user: user
                    })
                ]
            }),
            /*#__PURE__*/ (0,jsx_runtime_.jsxs)("section", {
                className: "paper",
                children: [
                    loading && /*#__PURE__*/ jsx_runtime_.jsx(LoadingBlock/* default */.Z, {}),
                    /*#__PURE__*/ jsx_runtime_.jsx("div", {
                        className: "w-full flex-col items-stretch",
                        children: /*#__PURE__*/ (0,jsx_runtime_.jsxs)("form", {
                            className: "flex flex-col items-stretch gap-4",
                            onSubmit: (e)=>{
                                e.preventDefault();
                                setLoading(true);
                                /** @type {HTMLFormElement} */ // @ts-ignore
                                const form = e.target;
                                const formFields = Array.from(form);
                                /** @type {any} */ const formFieldsObject = {};
                                formFields.forEach((/** @type {any} */ field)=>{
                                    if (field?.nodeName?.match(/button/i)) return;
                                    if (!field?.name || !field?.value?.match(/./)) return;
                                    if (field?.name?.match(/username|email/)) return;
                                    formFieldsObject[field.name] = field.value;
                                });
                                const fetchObject = {
                                    dbFullName: database.db_full_name,
                                    payload: {
                                        ...formFieldsObject,
                                        id: singleUser["id"]
                                    }
                                };
                                (0,fetchApi/* default */.Z)("/api/updateDbUser", {
                                    method: "post",
                                    body: fetchObject
                                }, true).then((res)=>{
                                    if (userImage?.imageBase64) {
                                        userImage["imageName"] = `${database.db_slug}-user-${singleUser.id}`;
                                        userImage["mimeType"] = "jpeg";
                                        delete userImage["imageBase64Full"];
                                        (0,fetchApi/* default */.Z)("/api/addUserMedia", {
                                            method: "post",
                                            body: {
                                                media: [
                                                    userImage
                                                ],
                                                folder: database.db_slug.replace(/_/g, "-"),
                                                type: "image"
                                            }
                                        }, true).then((_res)=>{
                                            if (_res && _res.mediaData && _res.mediaData[0]?.media_url) {
                                                (0,fetchApi/* default */.Z)("/api/updateDbUser", {
                                                    method: "post",
                                                    body: {
                                                        dbFullName: database.db_full_name,
                                                        payload: {
                                                            id: singleUser.id,
                                                            image: _res.mediaData[0].media_url,
                                                            image_thumbnail: _res.mediaData[0].media_thumbnail_url
                                                        }
                                                    }
                                                }, true).then((__res)=>{
                                                    if (__res.success) window.location.reload();
                                                    setTimeout(()=>{
                                                        setLoading(false);
                                                    }, 500);
                                                });
                                            } else {
                                                window.location.reload();
                                            }
                                        });
                                    } else {
                                        window.location.reload();
                                    }
                                });
                            },
                            children: [
                                userFields.map((field, index)=>{
                                    if (field?.match(/password|^database|email|username/)) {
                                        return /*#__PURE__*/ (0,jsx_runtime_.jsxs)("div", {
                                            className: "flex-col items-start w-full gap-1",
                                            children: [
                                                /*#__PURE__*/ jsx_runtime_.jsx("label", {
                                                    htmlFor: field,
                                                    children: field
                                                }),
                                                /*#__PURE__*/ jsx_runtime_.jsx("input", {
                                                    type: "text",
                                                    name: field,
                                                    id: field,
                                                    // @ts-ignore
                                                    value: singleUser[field],
                                                    placeholder: field,
                                                    className: "opacity-40 pointer-events-none",
                                                    onChange: (e)=>{
                                                        e.preventDefault();
                                                    }
                                                }, index + 1)
                                            ]
                                        }, index + 1);
                                    }
                                    if (field?.match(/more_user_data/)) {
                                        return /*#__PURE__*/ (0,jsx_runtime_.jsxs)("div", {
                                            className: "flex-col items-start w-full gap-1",
                                            children: [
                                                /*#__PURE__*/ jsx_runtime_.jsx("label", {
                                                    htmlFor: field,
                                                    children: field
                                                }),
                                                /*#__PURE__*/ jsx_runtime_.jsx("textarea", {
                                                    name: field,
                                                    id: field,
                                                    defaultValue: // @ts-ignore
                                                    singleUser[field] ? singleUser[field] : undefined,
                                                    placeholder: field,
                                                    rows: 6
                                                }, index + 1)
                                            ]
                                        }, index + 1);
                                    }
                                    return /*#__PURE__*/ (0,jsx_runtime_.jsxs)("div", {
                                        className: "flex-col items-start w-full gap-1",
                                        children: [
                                            /*#__PURE__*/ jsx_runtime_.jsx("label", {
                                                htmlFor: field,
                                                children: field
                                            }),
                                            /*#__PURE__*/ jsx_runtime_.jsx("input", {
                                                type: "text",
                                                name: field,
                                                id: field,
                                                defaultValue: // @ts-ignore
                                                singleUser[field] ? singleUser[field] : undefined,
                                                placeholder: field
                                            }, index + 1)
                                        ]
                                    }, index + 1);
                                }),
                                /*#__PURE__*/ (0,jsx_runtime_.jsxs)("div", {
                                    className: "border border-slate-300 dark:border-slate-600 border-solid bg-slate-100 dark:bg-slate-700 rounded p-6 flex-col items-start w-full",
                                    children: [
                                        /*#__PURE__*/ jsx_runtime_.jsx("h3", {
                                            className: "m-0 text-lg font-semibold mb-1 text-slate-600",
                                            children: "Update Image"
                                        }),
                                        /*#__PURE__*/ jsx_runtime_.jsx(UserImage/* default */.Z, {
                                            userImage: userImage,
                                            setUserImage: setUserImage,
                                            className: "w-full"
                                        })
                                    ]
                                }),
                                /*#__PURE__*/ jsx_runtime_.jsx("button", {
                                    children: "Update User"
                                })
                            ]
                        })
                    })
                ]
            })
        ]
    });
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
} /** ****************************************************************************** */  /** ****************************************************************************** */  /** ****************************************************************************** */  /** ****************************************************************************** */  /** ****************************************************************************** */  /** ****************************************************************************** */ 

// EXTERNAL MODULE: ./package-shared/utils/backend/global-db/DB_HANDLER.js
var DB_HANDLER = __webpack_require__(9395);
var DB_HANDLER_default = /*#__PURE__*/__webpack_require__.n(DB_HANDLER);
// EXTERNAL MODULE: ./package-shared/functions/backend/varDatabaseDbHandler.js
var varDatabaseDbHandler = __webpack_require__(1206);
var varDatabaseDbHandler_default = /*#__PURE__*/__webpack_require__.n(varDatabaseDbHandler);
;// CONCATENATED MODULE: ./pages/admin/[user_id]/databases/[single]/users/[user]/index.jsx
// @ts-check
/**
 * ==============================================================================
 * Imports
 * ==============================================================================
 */ 
const fs = __webpack_require__(7147);

////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////







/** ****************************************************************************** */ /** @type {import("@/package-shared/types").DatabaseSingleUserContextType} */ // @ts-ignore
const init = {};
const SingleDbUserContext = /*#__PURE__*/ external_react_default().createContext(init);
/** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /**
 * ==============================================================================
 * Main Component { Functional }
 * ==============================================================================
 * @param {Object} props - Server props
 * @param {import("@/package-shared/types").UserType} props.user
 * @param {import("@/package-shared/types").DSQL_MYSQL_user_databases_Type} props.database
 * @param {import("@/package-shared/types").DSQL_TableSchemaType} props.table
 * @param {import("@/package-shared/types").DSQL_DatabaseSchemaType[]} props.dbSchemaData
 * @param {import("@/package-shared/types").MYSQL_user_users_table_def} props.singleUser
 * @param {any} props.query
 * @param {any} props.confirmedDelegetedUser
 */ function DatabaseSingleUserPage({ user , database , table , dbSchemaData , singleUser , query , confirmedDelegetedUser ,  }) {
    /**
     * Get Contexts
     *
     * @abstract { React.useContext }
     */ ////////////////////////////////////////
    ////////////////////////////////////////
    ////////////////////////////////////////
    /**
     * Javascript Variables
     *
     * @abstract Non hook variables and functions
     */ const pageTitle = `${singleUser.first_name} ${singleUser.last_name} Users | Datasquirel"`;
    const pageDescription = "Welcome to your data app";
    let head = /*#__PURE__*/ (0,jsx_runtime_.jsxs)(jsx_runtime_.Fragment, {
        children: [
            /*#__PURE__*/ jsx_runtime_.jsx("title", {
                children: pageTitle
            }),
            /*#__PURE__*/ jsx_runtime_.jsx("meta", {
                name: "description",
                content: pageDescription
            })
        ]
    });
    ////////////////////////////////////////
    ////////////////////////////////////////
    ////////////////////////////////////////
    /**
     * React Hooks
     *
     * @abstract { useState, useEffect, useRef, etc ... }
     */ ////////////////////////////////////////
    ////////////////////////////////////////
    ////////////////////////////////////////
    /**
     * Function Return
     *
     * @abstract Main Function Return
     */ return /*#__PURE__*/ jsx_runtime_.jsx(AdminLayout/* default */.Z, {
        head: head,
        user: user,
        extraHeaderContent: /*#__PURE__*/ jsx_runtime_.jsx(ExtraContentDatabase/* default */.Z, {
            database: database,
            query: query,
            confirmedDelegetedUser: confirmedDelegetedUser,
            user: user
        }),
        children: /*#__PURE__*/ jsx_runtime_.jsx(SingleDbUserContext.Provider, {
            value: {
                user,
                database,
                table,
                dbSchemaData,
                singleUser,
                query,
                confirmedDelegetedUser
            },
            children: /*#__PURE__*/ jsx_runtime_.jsx(SingleDbUserContent, {})
        })
    });
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
}
/** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /**
 * ==============================================================================
 * Server Side Props or Static Props
 * ==============================================================================
 * @type {import("next").GetServerSideProps}
 */ async function getServerSideProps({ req , res , query  }) {
    /**
     * User Auth
     *
     * @description User Auth
     */ const user = await userAuth_default()(req, res);
    if (!user?.logged_in_status) {
        return {
            redirect: {
                destination: "/logout",
                permanent: false
            }
        };
    }
    ////////////////////////////////////////
    ////////////////////////////////////////
    ////////////////////////////////////////
    /**
     * Page/Site Data Data Fetching
     *
     * @description Fetch data on the server before returning
     */ const dbUserData = await grabDelegatedUserFromCookie_default()({
        request: req,
        user: user,
        // @ts-ignore
        databaseSlug: query.single,
        query
    });
    const dbUserDataObj = dbUserData;
    if (!dbUserDataObj) {
        return {
            redirect: {
                destination: "/admin",
                permanent: false
            }
        };
    }
    const { dbUserId , rootUserId  } = dbUserDataObj;
    const database = await DB_HANDLER_default()(`SELECT * FROM user_databases WHERE user_id='${dbUserId}' AND db_slug='${query.single}'`);
    if (!database || !database[0]) {
        console.log("Database Not Found");
        return {
            redirect: {
                destination: `/admin/${user?.id}/databases`,
                permanent: false
            }
        };
    }
    ////////////////////////////////////////
    ////////////////////////////////////////
    ////////////////////////////////////////
    /**
     * Confirm delegated User
     *
     * @description Confirm delegated User
     */ let confirmedDelegetedUser = dbUserData;
    ////////////////////////////////////////
    ////////////////////////////////////////
    ////////////////////////////////////////
    /**
     * Page/Site Data Data Fetching
     *
     * @description Fetch data on the server before returning
     */ /** @type {import("@/package-shared/types").DSQL_DatabaseSchemaType[]} */ const dbSchemaData = JSON.parse(fs.readFileSync(`${process.env.DSQL_USER_DB_SCHEMA_PATH}/user-${dbUserId}/main.json`, "utf-8"));
    const tables = dbSchemaData.filter((db)=>db.dbFullName === database[0].db_full_name)[0]?.tables;
    const targetTable = tables.filter((table)=>table.tableName === "users")[0];
    const singleUser = await varDatabaseDbHandler_default()({
        database: database[0].db_full_name,
        queryString: `SELECT * FROM users WHERE id='${query.user}'`,
        tableSchema: targetTable
    });
    if (!singleUser?.[0]) {
        return {
            redirect: {
                destination: `/admin/${user?.id}/databases/${database[0].db_slug}/users`,
                permanent: false
            }
        };
    }
    /**
     * Server props return
     *
     * @description Return data fetched on the server side
     */ return {
        props: {
            user: user,
            database: database?.[0] || null,
            table: targetTable ? targetTable : {},
            dbSchemaData: dbSchemaData,
            singleUser: singleUser?.[0] || null,
            query,
            confirmedDelegetedUser
        }
    };
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
}


/***/ })

};
;