<?php
include('dbconnect.php');
include('header.php');
include('function.php');
?>

        <!-- ==================================================== -->
        <!-- Start right Content here -->
        <!-- ==================================================== -->

        <div class="page-content">

            <!-- Start Container Fluid -->
            <div class="container-fluid">

                <!-- ========== Page Title Start ========== -->
                <div class="row">
                    <div class="col-12">
                        <div class="page-title-box">
                            <h4 class="mb-0 fw-semibold">Users</h4>
                            <ol class="breadcrumb mb-0">
                                <li class="breadcrumb-item"><a href="javascript: void(0);">Users</a></li>
                                <li class="breadcrumb-item active">List</li>
                            </ol>
                        </div>
                    </div>
                </div>
                <!-- ========== Page Title End ========== -->
				
				<div class="row">
                         <div class="col-lg-12">
                              <div class="card">
                                   <div class="card-header border-0">
                                        <div class="row justify-content-between">
                                             <div class="col-lg-6">
                                                  <div class="row align-items-center">
                                                       <!--div class="col-lg-6">
                                                            <form class="app-search d-none d-md-block me-auto">
                                                                 <div class="position-relative">
                                                                      <input type="search" class="form-control" placeholder="Search Agent" autocomplete="off" value="">
                                                                      <iconify-icon icon="solar:magnifer-broken" class="search-widget-icon"></iconify-icon>
                                                                 </div>
                                                            </form>
                                                       </div-->
                                                       <!--div class="col-lg-4">
                                                            <h5 class="text-dark fw-medium mb-0">311 <span class="text-muted"> Agent</span></h5>
                                                       </div-->
                                                  </div>
                                             </div>
                                             <div class="col-lg-6">
                                                  <div class="text-md-end mt-3 mt-md-0">
                                                       <!--button type="button" class="btn btn-outline-primary me-1"><i class="ri-settings-2-line me-1"></i>More Setting</button-->
                                                       <button type="button" class="btn btn-outline-primary me-1"><i class="ri-filter-line me-1"></i> Filters</button>
                                                       <button type="button" class="btn btn-success me-1" data-bs-toggle="offcanvas" data-bs-target="#rightOffcanvas" aria-controls="rightOffcanvas"><i class="ri-add-line"></i> New Agent</button>
										
                                                  </div>
                                             </div><!-- end col-->
                                        </div>
                                   </div>
                              </div>
                         </div>
                    </div>
                    
                    <!-- Reset Password Offcanvas -->
                    <div class="offcanvas offcanvas-end" tabindex="-1" id="resetPasswordOffcanvas" aria-labelledby="resetPasswordOffcanvasLabel">
                        <div class="offcanvas-header">
                            <h4 class="offcanvas-title mt-0" id="resetPasswordOffcanvasLabel">Reset Password</h4>
                            <button type="button" class="btn-close text-reset" data-bs-dismiss="offcanvas" aria-label="Close"></button>
                        </div>
                        <div class="offcanvas-body">
                            <form name="resetPasswordForm" method="POST" action="#" onsubmit="return validateResetPasswordForm()">
                                <input type="hidden" name="reset_user_id" id="reset_user_id">
                                
                                <div class="mb-3">
                                    <label class="form-label">New Password</label>
                                    <input type="password" class="form-control" name="new_password" required>
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label">Confirm Password</label>
                                    <input type="password" class="form-control" name="confirm_password" required>
                                </div>
                    
                                <div class="d-flex justify-content-end">
                                    <button type="submit" class="btn btn-primary">Reset Password</button>
                                </div>
                            </form>
                        </div>
                    </div>

					
					<!-- right offcanvas -->
					<div class="offcanvas offcanvas-end" tabindex="-1" id="rightOffcanvas" aria-labelledby="rightOffcanvasLabel">
						<div class="offcanvas-header">
							<h4 class="offcanvas-title mt-0" id="rightOffcanvasLabel">Invite User</h4>
							<button type="button" class="btn-close text-reset" data-bs-dismiss="offcanvas" aria-label="Close"></button>
						</div>
						<div class="offcanvas-body">
							<form class="row g-3" name="userForm" action="#" method="POST" onsubmit="return validateForm()">
							    <input type="hidden" name="user_id" id="edit_user_id">
								<div class="col-md-12">
									<label for="validationDefault01" class="form-label">User name</label>
									<input type="text" class="form-control" name="user_name" id="validationDefault01" value="Enter User Name">
								</div>
								<div class="col-md-12">
									<label for="validationDefault02" class="form-label">Mobile No.</label>
									<input type="text" class="form-control" name="user_mobile" id="validationDefault02" value="" >
								</div>
								<div class="col-md-12">
									<label for="validationDefault02" class="form-label">Email</label>
									<input type="text" class="form-control" name="user_email" id="validationDefault02" value="" >
								</div>
								<div class="col-md-12">
								<label for="validationDefault02" class="form-label">Project Name</label>
									<select class="form-control" id="choices-multiple-remove-button" name="project_name[]" multiple>
                                        <option value="">Select Project</option>
                                        <?php
                                        $sql = mysqli_query($conn, "SELECT tbl_project_id, tbl_project_name FROM tbl_project WHERE tbl_project_flag = 0");
                                        while ($row = mysqli_fetch_array($sql)) {
                                            $projectId = $row['tbl_project_id'];
                                            $projectName = htmlspecialchars($row['tbl_project_name'], ENT_QUOTES);
                                            echo "<option value=\"$projectId\" data-name=\"$projectName\">$projectName</option>";
                                        }
                                        ?>
                                    </select>


								</div>
								<div class="col-md-12">
									<label for="validationDefault04" class="form-label">Role</label>
									<select class="form-select" name="user_role" id="validationDefault04">
										<option selected disabled value="">Choose...</option>
										<option value="ADMIN">ADMIN</option>
										<option value="STANDARD">STANDARD</option>
									</select>
								</div>
                                <div class="col-md-12 password-fields">
                                    <label for="validationDefault01" class="form-label">User Password</label>
                                    <input type="password" class="form-control" name="user_pass" value="" placeholder="Enter Password">
                                </div>
                                <div class="col-md-12 password-fields">
                                    <label for="validationDefault01" class="form-label">Confirm Password</label>
                                    <input type="password" class="form-control" name="user_cnf_pass" value="" placeholder="Enter Confirm Password">
                                </div>
								<br><br><br><br><br>
								<div class="col-md-6">
									<button type="button" class="btn btn-primary" data-bs-dismiss="offcanvas" >Cancel</button>
								</div>
								<div class="col-md-6">
									<button class="btn btn-primary" type="submit">Invite User</button>
								</div>
							</form>
						</div>
					</div>

                <div class="row">
                    <div class="col-xl-12">
                        <div class="card">
						
                            <div class="card-body">
                                <div>
                                    <div class="py-3">
                                        <div id="table-gridjs"></div>
                                    </div>
                                     

									 
                                    <div class="">
                                        <!--div class="highlight-toolbar border-top-0">
                                            <ul class="nav nav-pills">
                                                <li class="nav-item">
                                                    <a href="#gridjs-basic-html" data-bs-toggle="tab" aria-expanded="false" class="nav-link active">
                                                        <span class="fs-12 text-uppercase">html</span>
                                                    </a>
                                                </li>
                                                <li class="nav-item">
                                                    <a href="#gridjs-basic-javascript" data-bs-toggle="tab" aria-expanded="true" class="nav-link">
                                                        <span class="fs-12 text-uppercase">javascript</span>
                                                    </a>
                                                </li>
                                            </ul>
                                            <button class="btn btn-sm btn-outline-success btn-copy-clipboard" data-clipboard-action="copy">Copy</button>
                                        </div-->
                                        <div class="tab-content">
                                            <div class="tab-pane show active" id="gridjs-basic-html">
                                                <!--div class="code">
                                                    <pre class="language-html">
                                                        <code>
                                                            &lt;div id=&quot;table-gridjs&quot;&gt;&lt;/div&gt;
                                                        </code>
                                                    </pre>
                                                </div-->
                                            </div>
                                            <div class="tab-pane" id="gridjs-basic-javascript">
                                                <!--div class="code">
                                                    <pre class="language-javascript">
                                                    <code>
                                                        // Basic Table
                                                        if (document.getElementById("table-gridjs"))
                                                             new gridjs.Grid({
                                                                  columns: [{
                                                                       name: 'ID',
                                                                       formatter: (function (cell) {
                                                                            return gridjs.html('<span class="fw-semibold">' + cell + '</span>');
                                                                       })
                                                                  },
                                                                       "Name",
                                                                  {
                                                                       name: 'Email',
                                                                       formatter: (function (cell) {
                                                                            return gridjs.html('<a href="#">' + cell + '</a>');
                                                                       })
                                                                  },
                                                                       "Position", "Company", "Country",
                                                                  {
                                                                       name: 'Actions',
                                                                       width: '120px',
                                                                       formatter: (function (cell) {
                                                                            return gridjs.html("<a href='#' class='text-reset text-decoration-underline'>" + "Details" + "</a>");
                                                                       })
                                                                  },
                                                                  ],
                                                                  pagination: {
                                                                       limit: 5
                                                                  },
                                                                  sort: true,
                                                                  search: true,
                                                                  data: [
                                                                       ["11", "Alice", "alice@example.com", "Software Engineer", "ABC Company", "United States"],
                                                                       ["12", "Bob", "bob@example.com", "Product Manager", "XYZ Inc", "Canada"],
                                                                       ["13", "Charlie", "charlie@example.com", "Data Analyst", "123 Corp", "Australia"],
                                                                       ["14", "David", "david@example.com", "UI/UX Designer", "456 Ltd", "United Kingdom"],
                                                                       ["15", "Eve", "eve@example.com", "Marketing Specialist", "789 Enterprises", "France"],
                                                                       ["16", "Frank", "frank@example.com", "HR Manager", "ABC Company", "Germany"],
                                                                       ["17", "Grace", "grace@example.com", "Financial Analyst", "XYZ Inc", "Japan"],
                                                                       ["18", "Hannah", "hannah@example.com", "Sales Representative", "123 Corp", "Brazil"],
                                                                       ["19", "Ian", "ian@example.com", "Software Developer", "456 Ltd", "India"],
                                                                       ["20", "Jane", "jane@example.com", "Operations Manager", "789 Enterprises", "China"]
                                                                  ]
                                                             }).render(document.getElementById("table-gridjs"));
                                                    </code>
                                                </pre>
                                                </div-->
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>


                    </div> <!-- end card body -->

                   


                </div> <!-- end row -->

            </div>
            <!-- End Container Fluid -->
<script>

$(document).ready(function() {
    if (document.getElementById("table-gridjs")) {
        new gridjs.Grid({
            columns: [{
                name: "S.No.",
                formatter: function(e) {
                    return gridjs.html('<span class="fw-semibold">' + e + "</span>")
                }
            }, "Name", {
                name: "Email",
                formatter: function(e) {
                    return gridjs.html('<a href="">' + e + "</a>")
                }
            }, "Mobile No", "Role", "Modified Date","Projects","Password",
            {
              name: "Status",
              formatter: function(cell, row) {
                const isActive = cell === "Active";
                const color = isActive ? "bg-success-subtle text-success" : "bg-danger-subtle text-danger";
            
                return gridjs.html(`
                  <span 
                    class="badge ${color} py-1 px-2 fs-13 status-badge" 
                    style="cursor:pointer"
                    data-user-id="${row.cells[10].data}" 
                    data-current-status="${cell}"
                  >
                    ${cell}
                  </span>
                `);
              }
            },
            {
              name: "Lead Flag",
              formatter: function(cell, row) {
                const isLead = cell === "1";
                const displayText = isLead ? "On" : "Off";
                const color = isLead ? "bg-warning-subtle text-warning" : "bg-secondary-subtle text-muted";
            
                return gridjs.html(`
                  <span 
                    class="badge ${color} py-1 px-2 fs-13 lead-flag-badge" 
                    style="cursor:pointer"
                    data-user-id="${row.cells[10].data}" 
                    data-current-lead="${cell}"
                  >
                    ${displayText}
                  </span>
                `);
              }
            },
            {
                name: "Actions",
                width: "120px",
                formatter: function(e) {
                    return gridjs.html(`
                        <li class="list-inline-item fs-20 dropdown d-none d-md-flex">
                            <a href="javascript:void(0);" class="dropdown-toggle arrow-none text-dark" data-bs-toggle="dropdown">
                                <i class="ri-more-2-fill"></i>
                            </a>
                            <div class="dropdown-menu dropdown-menu-end">
                                <a class="dropdown-item edit-user" href="javascript:void(0);" data-user-id="${e}">Edit User</a>
                                <a class="dropdown-item reset-password" href="javascript:void(0);" data-user-id="${e}">Reset Password</a>
                            </div>
                        </li>
                    `);
                }
            }],
            pagination: {
                limit: 20
            },
            sort: true,
            search: true,
            server: {
                url: '<?php echo $base_url;?>user-fetch-data.php',  // The PHP script that fetches data
                then: data => data,     // Process the fetched data
                // You can handle any other server-side processing here if necessary
            }
        }).render(document.getElementById("table-gridjs"));
    }
});
</script>

<script>
    let projectChoices;

$(document).ready(function () {
    const $selectElement = $('#choices-multiple-remove-button');

    // Initialize Choices.js only if not already initialized
    if (!$selectElement.data('choices')) {
        projectChoices = new Choices($selectElement[0], {
            removeItemButton: true
        });
        $selectElement.data('choices', projectChoices);
    }
});

$(document).ready(function () {
    // Initialize Choices.js only once
    // projectChoices = new Choices('#choices-multiple-remove-button', {
    //     removeItemButton: true
    // });

    let isEditMode = false;

    // On edit user click
    $(document).on("click", ".edit-user", function () {
        const userId = $(this).data("user-id");
    
        $.ajax({
            url: "<?php echo $base_url; ?>get-user.php",
            type: "POST",
            data: { id: userId },
            dataType: "json",
            success: function (user) {
                // Set form fields
                $("input[name='user_name']").val(user.name);
                $("input[name='user_mobile']").val(user.mobile_no);
                $("input[name='user_email']").val(user.email);
                $("select[name='user_role']").val(user.role);
                $("#edit_user_id").val(user.id);
    
                // Preselect projects
                // const projectIds = user.project_ids.map(id => String(id)); // Ensure values are strings
                // projectChoices.setValue(projectIds);
                
                setTimeout(() => {
                    projectChoices.removeActiveItems();
                
                    const allChoices = projectChoices._store.choices; // Get all choices from the Choices.js instance
                
                    const selectedValues = user.project_ids.map(id => {
                        const match = allChoices.find(choice => choice.value === id);
                        return {
                            value: id,
                            label: match ? match.label : `Project ${id}`,
                            selected: true
                        };
                    });
                
                    projectChoices.setValue(selectedValues);
                    console.log('Choices store:', projectChoices._store.choices);
                }, 300); // Delay slightly to wait for DOM
    
                // Hide password fields
                $(".password-fields").hide();
    
                // Update UI elements
                $("#rightOffcanvasLabel").text("Update User");
                $("button[type='submit']").text("Update User");
    
                // Show offcanvas
                const offcanvas = new bootstrap.Offcanvas('#rightOffcanvas');
                offcanvas.show();
            },
            error: function () {
                alert("Failed to load user data.");
            }
        });
    });


    // Add User button reset logic
    $("#addUserBtn").on("click", function () {
        isEditMode = false;
        $(".password-fields").show();
        $("#rightOffcanvasLabel").text("Invite User");
        $("button[type='submit']").text("Invite User");
        document.forms["userForm"].reset();
        $("#edit_user_id").val("");

        // Clear Choices.js selections
        projectChoices.removeActiveItems();

        const offcanvas = new bootstrap.Offcanvas('#rightOffcanvas');
        offcanvas.show();
    });
    
    $(document).on("click", ".reset-password", function () {
        const userId = $(this).data("user-id");
    
        // Set the hidden input with user ID
        $("#reset_user_id").val(userId);
    
        // Optionally reset the form fields
        $("form[name='resetPasswordForm']")[0].reset();
    
        // Open the offcanvas
        const offcanvas = new bootstrap.Offcanvas('#resetPasswordOffcanvas');
        offcanvas.show();
    });
    
    document.addEventListener("click", function(e) {
      if (e.target && e.target.classList.contains("status-badge")) {
        const userId = e.target.getAttribute("data-user-id");
        const currentStatus = e.target.getAttribute("data-current-status");
        const newStatus = currentStatus === "Active" ? "Inactive" : "Active";
    
        Swal.fire({
          title: `Are you sure?`,
          text: `You are about to set the user as ${newStatus}.`,
          icon: 'warning',
          showCancelButton: true,
          confirmButtonText: `Yes, ${newStatus}!`
        }).then((result) => {
          if (result.isConfirmed) {
            // Send to PHP backend
            fetch("update-status.php", {
              method: "POST",
              headers: { "Content-Type": "application/x-www-form-urlencoded" },
              body: `user_id=${userId}&status=${newStatus}`
            })
            .then(res => res.text())
            .then(response => {
              Swal.fire("Success!", `User status changed to ${newStatus}.`, "success")
                .then(() => window.location.reload()); // reload to reflect change
            })
            .catch(() => {
              Swal.fire("Error!", "Something went wrong.", "error");
            });
          }
        });
      }
    });
    
    document.addEventListener("click", function(e) {
      if (e.target && e.target.classList.contains("lead-flag-badge")) {
        const userId = e.target.getAttribute("data-user-id");
        const currentFlag = e.target.getAttribute("data-current-lead");
        const newFlag = currentFlag === "1" ? "Off" : "On";
    
        Swal.fire({
          title: `Are you sure?`,
          text: `You are about to turn the Lead Flag ${newFlag}.`,
          icon: 'warning',
          showCancelButton: true,
          confirmButtonText: `Yes, turn ${newFlag}`
        }).then((result) => {
          if (result.isConfirmed) {
            fetch("update-lead-flag.php", {
              method: "POST",
              headers: { "Content-Type": "application/x-www-form-urlencoded" },
              body: `user_id=${userId}&lead_flag=${newFlag}`
            })
            .then(res => res.text())
            .then(response => {
              Swal.fire("Success!", `Lead Flag changed to ${newFlag}.`, "success")
                .then(() => window.location.reload());
            })
            .catch(() => {
              Swal.fire("Error!", "Something went wrong.", "error");
            });
          }
        });
      }
    });

    
});

function waitForProjectOptions(user) {
    const interval = setInterval(() => {
        const optionCount = $("#choices-multiple-remove-button option").length;
        
        if (optionCount > 1) { // means options are loaded
            clearInterval(interval);

            // Now bind projects
            projectChoices.removeActiveItems();

            user.project_ids.forEach(id => {
                const $option = $(`#choices-multiple-remove-button option[value="${id}"]`);
                if ($option.length > 0) {
                    $option.prop("selected", true);
                } else {
                    console.warn(`Option with value "${id}" not found`);
                }
            });

            // Trigger change event so Choices.js updates UI
            document.getElementById('choices-multiple-remove-button').dispatchEvent(new Event('change', { bubbles: true }));
        }
    }, 100); // check every 100ms
}


</script>

<script>
        // JavaScript Validation Function
        function validateForm() {
            var name = document.forms["userForm"]["user_name"].value;
            var email = document.forms["userForm"]["user_email"].value;
            var mobile = document.forms["userForm"]["user_mobile"].value;
            var role = document.forms["userForm"]["user_role"].value;
            var pass = document.forms["userForm"]["user_pass"].value;
            var confPass = document.forms["userForm"]["user_cnf_pass"].value;
            var errorMessage = "";
        
            if (name == "") {
                errorMessage += "Name is required.\n";
            }
        
            var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
            if (email == "") {
                errorMessage += "Email is required.\n";
            } else if (!emailPattern.test(email)) {
                errorMessage += "Invalid email format.\n";
            }
        
            if (mobile == "") {
                errorMessage += "Mobile No. is required.\n";
            }
        
            if (role == "") {
                errorMessage += "Role is required.\n";
            }
        
            // Only validate password if NOT in edit mode
            if (!isEditMode) {
                if (pass == "") {
                    errorMessage += "Password is required.\n";
                }
                if (pass != confPass) {
                    errorMessage += "Password and confirm password is mismatched.\n";
                }
            }
        
            if (errorMessage != "") {
                alert(errorMessage);
                return false;
            }
            return true;
        }


        
        function validateResetPasswordForm() {
            const pass = document.forms["resetPasswordForm"]["new_password"].value;
            const confirm = document.forms["resetPasswordForm"]["confirm_password"].value;
        
            if (pass !== confirm) {
                alert("Passwords do not match!");
                return false;
            }
        
            return true;
        }

        
    </script>
	
<?php
include('footer.php');
?>

<?php

// First: Handle RESET PASSWORD
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['reset_user_id'])) {
    $user_id = $_POST['reset_user_id'];
    $new_password = $_POST['new_password'];
    $confirm_password = $_POST['confirm_password'];

    if ($new_password !== $confirm_password) {
        echo "<script>
            Swal.fire({ icon: 'error', title: 'Passwords do not match!' });
        </script>";
        exit;
    }

    $hashed_password = md5($new_password);

    $sql = "UPDATE tbl_invite_user SET 
                password = '$new_password', 
                encrypt_password = '$hashed_password', 
                edate = '" . date('Y-m-d H:i:s') . "',
                euser = 'ADMIN' 
            WHERE id = '$user_id'";

    $result = mysqli_query($conn, $sql);

    if ($result) {
        echo "<script>
            Swal.fire({
                title: 'Password Reset!',
                text: 'The password has been successfully updated.',
                icon: 'success'
            }).then(() => {
                window.location.href = 'users-list.php';
            });
        </script>";
    } else {
        echo "<script>
            Swal.fire({
                title: 'Error!',
                text: 'Something went wrong.',
                icon: 'error'
            });
        </script>";
    }
    exit; // Stop further execution
}

// Second: Handle ADD / UPDATE USER
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $user_id = $_POST['user_id'] ?? '';
    $hashed_password = md5($_POST['user_pass']);

    if (!empty($user_id)) {
        // UPDATE
        $sql = "UPDATE tbl_invite_user SET 
                    name = '" . $_POST['user_name'] . "', 
                    email = '" . $_POST['user_email'] . "',
                    mobile_no = '" . $_POST['user_mobile'] . "',
                    role = '" . $_POST['user_role'] . "',
                    edate = '" . date('Y-m-d h:i:s') . "',
                    euser = 'ADMIN'
                WHERE id = '$user_id'";
        $result = mysqli_query($conn, $sql);
    } else {
        // INSERT
        $sql = "INSERT INTO tbl_invite_user SET 
                    name = '" . $_POST['user_name'] . "',
                    email = '" . $_POST['user_email'] . "',
                    mobile_no = '" . $_POST['user_mobile'] . "',
                    role = '" . $_POST['user_role'] . "',
                    cdate = '" . date('Y-m-d h:i:s') . "',
                    flag = 0,
                    cuser = 'ADMIN',
                    deleted_flag = 0,
                    status = 'ACTIVE',
                    password = '" . $_POST['user_pass'] . "',
                    encrypt_password = '" . $hashed_password . "'";
        $result = mysqli_query($conn, $sql);
        $user_id = $conn->insert_id;
    }

    // Common: Insert project access
    if ($result) {
        if (isset($_POST['project_name']) && is_array($_POST['project_name'])) {
            // First delete existing project assignments for this user
            $delete_sql = "DELETE FROM tbl_lead_user_access_projects WHERE tbl_lead_user_access_projects_user_id = '$user_id'";
            mysqli_query($conn, $delete_sql);
            
            // Then insert new project assignments
            foreach ($_POST['project_name'] as $project_id) {
                $sql = "INSERT INTO tbl_lead_user_access_projects(tbl_lead_user_access_projects_user_id, tbl_lead_user_access_projects_project_id)
                        VALUES ('$user_id', '$project_id')";
                mysqli_query($conn, $sql);
            }
        }

        echo "<script>
            Swal.fire({
                title: 'Success!',
                text: 'Your request has been completed.',
                icon: 'success'
            }).then(() => {
                window.location.href = 'users-list.php';
            });
        </script>";
    } else {
        echo "<script>
            Swal.fire({
                title: 'Oops...!',
                text: 'Request Incomplete. Please Try Again!',
                icon: 'error'
            });
        </script>";
    }
    exit;
}

// Added PHP endpoint to get user projects
if (isset($_GET['action']) && $_GET['action'] == 'getUserProjects') {
    $user_id = $_GET['user_id'] ?? 0;
    $query = "SELECT tbl_lead_user_access_projects_project_id as project_id FROM tbl_lead_user_access_projects WHERE tbl_lead_user_access_projects_user_id = ?";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $projects = [];
    while ($row = $result->fetch_assoc()) {
        $projects[] = $row['project_id'];
    }
    echo json_encode($projects);
    exit;
}
?>
