"use strict";
(() => {
var exports = {};
exports.id = 5926;
exports.ids = [5926,8105];
exports.modules = {

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

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

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  "AddNewDbUserContext": () => (/* binding */ AddNewDbUserContext),
  "default": () => (/* binding */ AddUserPage),
  "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/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/DbCreateDbUserForm.jsx
var DbCreateDbUserForm = __webpack_require__(1926);
;// CONCATENATED MODULE: ./components/admin/users/DbAddNewUserContent.jsx
// @ts-check
/**
 * ==============================================================================
 * Imports
 * ==============================================================================
 */ 







/** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ let timeout;
/** ****************************************************************************** */ /**
 * ==============================================================================
 * Main Component { Functional }
 * ==============================================================================
 * @param {Object} props - Server props
 */ function DbAddNewUserContent(props) {
    /**
     * Get Contexts
     *
     * @abstract { React.useContext }
     */ const { user , database , table , query , confirmedDelegetedUser  } = external_react_default().useContext(AddNewDbUserContext);
    ////////////////////////////////////////
    ////////////////////////////////////////
    ////////////////////////////////////////
    /**
     * Javascript Variables
     *
     * @abstract Non hook variables and functions
     */ const userPriviledges = __webpack_require__(9169);
    ////////////////////////////////////////
    ////////////////////////////////////////
    ////////////////////////////////////////
    /**
     * React Hooks
     *
     * @abstract { useState, useEffect, useRef, etc ... }
     */ const [paradigm, setParadigm] = external_react_default().useState("invitation");
    const [loading, setLoading] = external_react_default().useState(false);
    const [allDbSelected, setAllDbSelected] = external_react_default().useState(false);
    const [priviledges, setPriviledges] = external_react_default().useState([
        "Edit"
    ]);
    /** @type {[ targetDb: string, setTargetDb: React.Dispatch<React.SetStateAction<string>> ]} */ // @ts-ignore
    const [targetDb, setTargetDb] = external_react_default().useState(database.db_slug);
    const [alert, setAlert] = external_react_default().useState(null);
    /** @type {[ userImage: any, setUserImage: React.Dispatch<React.SetStateAction<any>> ]} */ // @ts-ignore
    const [userImage, setUserImage] = external_react_default().useState(null);
    const [dbTables, setDbTables] = external_react_default().useState([]);
    const [selectedDbTables, setSlectedDbTables] = external_react_default().useState([]);
    ////////////////////////////////////////
    ////////////////////////////////////////
    ////////////////////////////////////////
    /**
     * 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__*/ jsx_runtime_.jsx("div", {
                        className: "w-full justify-between flex-wrap",
                        children: /*#__PURE__*/ (0,jsx_runtime_.jsxs)("div", {
                            children: [
                                /*#__PURE__*/ jsx_runtime_.jsx(BackButton/* default */.Z, {}),
                                /*#__PURE__*/ (0,jsx_runtime_.jsxs)("h1", {
                                    className: "text-3xl m-0",
                                    children: [
                                        "Add A New User to ",
                                        database.db_name
                                    ]
                                })
                            ]
                        })
                    }),
                    /*#__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__*/ (0,jsx_runtime_.jsxs)("form", {
                        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;
                                formFieldsObject[field.name] = field.value;
                            });
                            const fetchObject = {
                                payload: formFieldsObject,
                                dbFullName: database.db_full_name,
                                dbId: database.id
                            };
                            (0,fetchApi/* default */.Z)("/api/addDbUser", {
                                method: "post",
                                body: fetchObject
                            }, true).then((res)=>{
                                if (res.success) {
                                    if (userImage) {
                                        userImage["imageName"] = `${targetDb}-user-${res.newUserId}`;
                                        userImage["mimeType"] = "jpeg";
                                        delete userImage["imageBase64Full"];
                                        (0,fetchApi/* default */.Z)("/api/addUserMedia", {
                                            method: "post",
                                            body: {
                                                media: [
                                                    userImage
                                                ],
                                                folder: targetDb.replace(/_/g, "-"),
                                                type: "image"
                                            }
                                        }, true).then((_res)=>{
                                            (0,fetchApi/* default */.Z)("/api/updateDbUser", {
                                                method: "post",
                                                body: {
                                                    dbFullName: database.db_full_name,
                                                    payload: {
                                                        id: res.newUserId,
                                                        image: _res.mediaData[0].media_url,
                                                        image_thumbnail: _res.mediaData[0].media_thumbnail_url
                                                    }
                                                }
                                            }, true).then((__res)=>{
                                                if (__res.success) {
                                                    window.location.pathname = `/admin/${user?.id}/databases/${database.db_slug}/users`;
                                                }
                                                setTimeout(()=>{
                                                    setLoading(false);
                                                }, 500);
                                            });
                                        });
                                    } else {
                                        window.location.pathname = `/admin/${user?.id}/databases/${database.db_slug}/users`;
                                    }
                                } else {
                                    setTimeout(()=>{
                                        setLoading(false);
                                    }, 500);
                                }
                            });
                        },
                        className: "w-full flex flex-col items-stretch gap-4",
                        children: [
                            /*#__PURE__*/ jsx_runtime_.jsx(DbCreateDbUserForm/* default */.Z, {
                                user: user,
                                targetDb: database.db_full_name,
                                database: database,
                                userImage: userImage,
                                setUserImage: setUserImage
                            }),
                            /*#__PURE__*/ jsx_runtime_.jsx("button", {
                                children: "Add User"
                            })
                        ]
                    })
                ]
            })
        ]
    });
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
} /** ****************************************************************************** */  /** ****************************************************************************** */  /** ****************************************************************************** */  /** ****************************************************************************** */  /** ****************************************************************************** */  /** ****************************************************************************** */ 

// EXTERNAL MODULE: ./package-shared/functions/backend/varDatabaseDbHandler.js
var varDatabaseDbHandler = __webpack_require__(1206);
var varDatabaseDbHandler_default = /*#__PURE__*/__webpack_require__.n(varDatabaseDbHandler);
// 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: ./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);
;// CONCATENATED MODULE: ./pages/admin/[user_id]/databases/[single]/users/add-user.jsx
// @ts-check
/**
 * ==============================================================================
 * Imports
 * ==============================================================================
 */ 
const fs = __webpack_require__(7147);

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







/** ****************************************************************************** */ /** @type {import("@/package-shared/types").AddUserUserContextType} */ // @ts-ignore
const init = {};
const AddNewDbUserContext = /*#__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 {any} props.query
 * @param {any} props.confirmedDelegetedUser
 */ function AddUserPage({ user , database , table , query , confirmedDelegetedUser ,  }) {
    /**
     * Get Contexts
     *
     * @abstract { React.useContext }
     */ ////////////////////////////////////////
    ////////////////////////////////////////
    ////////////////////////////////////////
    /**
     * Javascript Variables
     *
     * @abstract Non hook variables and functions
     */ const pageTitle = "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(AddNewDbUserContext.Provider, {
            value: {
                user,
                database,
                table,
                query,
                confirmedDelegetedUser
            },
            children: /*#__PURE__*/ jsx_runtime_.jsx(DbAddNewUserContent, {})
        })
    });
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
}
/** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /**
 * ==============================================================================
 * 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]) {
        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];
    /**
     * Page/Site Data Data Fetching
     *
     * @description Fetch data on the server before returning
     */ const users = await varDatabaseDbHandler_default()({
        database: database[0].db_full_name,
        queryString: `SELECT * FROM users LIMIT 20`,
        tableSchema: targetTable
    });
    ////////////////////////////////////////
    ////////////////////////////////////////
    ////////////////////////////////////////
    /**
     * Server props return
     *
     * @description Return data fetched on the server side
     */ return {
        props: {
            user: user,
            database: database[0],
            table: targetTable ? targetTable : {},
            query,
            confirmedDelegetedUser
        }
    };
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
}


/***/ }),

/***/ 4003:
/***/ ((module) => {

module.exports = require("@mui/icons-material/AdminPanelSettingsTwoTone");

/***/ }),

/***/ 3257:
/***/ ((module) => {

module.exports = require("@mui/icons-material/ArrowBackIosRounded");

/***/ }),

/***/ 69:
/***/ ((module) => {

module.exports = require("@mui/icons-material/CloudOffTwoTone");

/***/ }),

/***/ 4008:
/***/ ((module) => {

module.exports = require("@mui/icons-material/CloudQueueRounded");

/***/ }),

/***/ 3849:
/***/ ((module) => {

module.exports = require("@mui/icons-material/CodeRounded");

/***/ }),

/***/ 7306:
/***/ ((module) => {

module.exports = require("@mui/icons-material/CollectionsTwoTone");

/***/ }),

/***/ 5050:
/***/ ((module) => {

module.exports = require("@mui/icons-material/CopyAllTwoTone");

/***/ }),

/***/ 386:
/***/ ((module) => {

module.exports = require("@mui/icons-material/CottageTwoTone");

/***/ }),

/***/ 8979:
/***/ ((module) => {

module.exports = require("@mui/icons-material/DynamicFormTwoTone");

/***/ }),

/***/ 300:
/***/ ((module) => {

module.exports = require("@mui/icons-material/LanguageOutlined");

/***/ }),

/***/ 2814:
/***/ ((module) => {

module.exports = require("@mui/icons-material/LockTwoTone");

/***/ }),

/***/ 5557:
/***/ ((module) => {

module.exports = require("@mui/icons-material/MenuBookTwoTone");

/***/ }),

/***/ 9806:
/***/ ((module) => {

module.exports = require("@mui/icons-material/PeopleOutlineTwoTone");

/***/ }),

/***/ 36:
/***/ ((module) => {

module.exports = require("@mui/icons-material/RefreshRounded");

/***/ }),

/***/ 1799:
/***/ ((module) => {

module.exports = require("@mui/icons-material/SchemaTwoTone");

/***/ }),

/***/ 6500:
/***/ ((module) => {

module.exports = require("@mui/icons-material/SendToMobileTwoTone");

/***/ }),

/***/ 7428:
/***/ ((module) => {

module.exports = require("@mui/icons-material/SummarizeTwoTone");

/***/ }),

/***/ 507:
/***/ ((module) => {

module.exports = require("@mui/icons-material/TipsAndUpdatesTwoTone");

/***/ }),

/***/ 2423:
/***/ ((module) => {

module.exports = require("lucide-react");

/***/ }),

/***/ 968:
/***/ ((module) => {

module.exports = require("next/head");

/***/ }),

/***/ 6689:
/***/ ((module) => {

module.exports = require("react");

/***/ }),

/***/ 997:
/***/ ((module) => {

module.exports = require("react/jsx-runtime");

/***/ }),

/***/ 2261:
/***/ ((module) => {

module.exports = require("serverless-mysql");

/***/ }),

/***/ 4300:
/***/ ((module) => {

module.exports = require("buffer");

/***/ }),

/***/ 6113:
/***/ ((module) => {

module.exports = require("crypto");

/***/ }),

/***/ 7147:
/***/ ((module) => {

module.exports = require("fs");

/***/ }),

/***/ 3685:
/***/ ((module) => {

module.exports = require("http");

/***/ }),

/***/ 1017:
/***/ ((module) => {

module.exports = require("path");

/***/ }),

/***/ 9169:
/***/ ((module) => {

module.exports = JSON.parse('["Edit Tables","Update Entries","Create Table","Delete Entries","Delete Tables"]');

/***/ })

};
;

// load runtime
var __webpack_require__ = require("../../../../../../webpack-runtime.js");
__webpack_require__.C(exports);
var __webpack_exec__ = (moduleId) => (__webpack_require__(__webpack_require__.s = moduleId))
var __webpack_exports__ = __webpack_require__.X(0, [4017,8313,5264,6729,5449,913,4480,370,424,4858,5472,1781,4941,7023,7901,8682,1206,5116,6718,7037,2733,1926], () => (__webpack_exec__(4437)));
module.exports = __webpack_exports__;

})();