<?php include "check_login.php"; ?>
<?php 
include 'dbcon.php';
$projects = mysqli_query($conn,"
    SELECT id, company_name, project_location
    FROM projects
    WHERE user_id IS NULL
    ORDER BY id DESC
");

?>
<!DOCTYPE html>
<html lang="zxx">
<head>
    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
  
    <title>Create User</title>
  
    <link rel="shortcut icon" type="image/x-icon" href="assets/images/favicon.ico">
  
    <link rel="stylesheet" type="text/css" href="assets/css/bootstrap.min.css">
 
    <link rel="stylesheet" type="text/css" href="assets/vendors/css/vendors.min.css">
    <link rel="stylesheet" type="text/css" href="assets/vendors/css/select2.min.css">
    <link rel="stylesheet" type="text/css" href="assets/vendors/css/select2-theme.min.css">
    <link rel="stylesheet" type="text/css" href="assets/vendors/css/datepicker.min.html">
    
    <link rel="stylesheet" type="text/css" href="assets/css/theme.min.css">
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

</head>

<body>
<?php include("sidebar.php"); ?>
<?php include("header.php"); ?>   

    <main class="nxl-container">
        <div class="nxl-content">
            <!-- [ page-header ] start -->
            <div class="page-header">
                <div class="page-header-left d-flex align-items-center">
                    <div class="page-header-title">
                        <h5 class="m-b-10">Customers</h5>
                    </div>
                    <ul class="breadcrumb">
                        <li class="breadcrumb-item"><a href="index.html">Home</a></li>
                        <li class="breadcrumb-item">Create</li>
                    </ul>
                </div>
          
            </div>
            <!-- [ page-header ] end -->
            <!-- [ Main Content ] start -->
            <div class="main-content">
                <div class="row">
                    <div class="col-lg-12">
                        <div class="card border-top-0">
                        
                         <div class="card-body personal-info">
                                        <div class="mb-4 d-flex align-items-center justify-content-between">
                                            <h5 class="fw-bold mb-0 me-4">
                                                <span class="d-block mb-2">Personal Information:</span>
                                           
                                            </h5>
                                           
                                        </div>
                                     <form method="POST" action="">

                                           <div class="row mb-4 align-items-center">
                                            <div class="col-lg-2">
                                                <label for="fullnameInput" class="fw-semibold">Assing Project: </label>
                                            </div>
                                            <div class="col-lg-10">
                                                <div class="input-group">
                                                    <div class="input-group-text"><i class="feather-file"></i></div>
                                                        <select name="project_id" id="projectSelect" class="form-select" required>
                                                        <option value="">-- Select Project --</option>

                                                     <?php while($p = mysqli_fetch_assoc($projects)){ ?>
                                                            <option value="<?= $p['id'] ?>">
                                                                <?= htmlspecialchars($p['company_name']) ?> - <?= htmlspecialchars($p['project_location']) ?>
                                                            </option>
                                                        <?php } ?>

                                                    </select>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="row mb-4 align-items-center">
                                            <div class="col-lg-2">
                                                <label for="fullnameInput" class="fw-semibold">Name: </label>
                                            </div>
                                            <div class="col-lg-10">
                                                <div class="input-group">
                                                    <div class="input-group-text"><i class="feather-user"></i></div>
                                                    <input type="text" name="name" id="userName" class="form-control" id="fullnameInput" placeholder="Name">
                                                </div>
                                            </div>
                                        </div>
                                        <div class="row mb-4 align-items-center">
                                            <div class="col-lg-2">
                                                <label for="mailInput" class="fw-semibold">Email: </label>
                                            </div>
                                            <div class="col-lg-10">
                                                <div class="input-group">
                                                    <div class="input-group-text"><i class="feather-mail"></i></div>
                                                    <input type="text" name="email" id="userEmail" class="form-control" id="mailInput" placeholder="Email">
                                                </div>
                                            </div>
                                        </div>
                                        <div class="row mb-4 align-items-center">
                                            <div class="col-lg-2">
                                                <label for="usernameInput" class="fw-semibold">Username: </label>
                                            </div>
                                            <div class="col-lg-10">
                                                <div class="input-group">
                                                    <div class="input-group-text"><i class="feather-users"></i></div>
                                                   
                                                    <input type="text" name="username" class="form-control" id="usernameInput" placeholder="Username">
                                                </div>
                                            </div>
                                        </div>
                                        <div class="row mb-4 align-items-center">
                                            <div class="col-lg-2">
                                                <label for="phoneInput" class="fw-semibold">Phone: </label>
                                            </div>
                                            <div class="col-lg-10">
                                                <div class="input-group">
                                                    <div class="input-group-text"><i class="feather-phone"></i></div>
                                                    <input type="number" name="mobile" id="userPhone" class="form-control" id="phoneInput" placeholder="Phone">
                                                </div>
                                            </div>
                                        </div>
                                    <div class="row mb-4 align-items-center">
                                            <div class="col-lg-2">
                                                <label for="Input" class="fw-semibold">Password: </label>
                                            </div>
                                            <div class="col-lg-10">
                                                <div class="input-group">
                                                    <div class="input-group-text"><i class="feather-key"></i></div>
                                                    <input type="text" name="password" class="form-control" id="Input" placeholder="Password">
                                                </div>
                                            </div>
                                        </div>

                                    </div>
                                    <hr class="my-0">
                                     <div class="mt-5">
                                <button type="submit" name="submit" class="btn btn-lg btn-primary w-100">Add User</button>
                            </div>
                                </form>
                          
                        </div>
                    </div>
                </div>
            </div>
            <!-- [ Main Content ] end -->
        </div>
        <!-- [ Footer ] start -->
<?php include("footer.php"); ?>
        <!-- [ Footer ] end -->
    </main>

    <!--! BEGIN: Vendors JS !-->
    <script src="assets/vendors/js/vendors.min.js"></script>
    <!-- vendors.min.js {always must need to be top} -->
    <script src="assets/vendors/js/select2.min.js"></script>
    <script src="assets/vendors/js/select2-active.min.js"></script>
    <script src="assets/vendors/js/datepicker.min.html"></script>
    <script src="assets/vendors/js/lslstrength.min.html"></script>
    <!--! END: Vendors JS !-->
    <!--! BEGIN: Apps Init  !-->
    <script src="assets/js/common-init.min.js"></script>
    <script src="assets/js/customers-create-init.min.js"></script>
    <!--! END: Apps Init !-->
    <!--! BEGIN: Theme Customizer  !-->
    <script src="assets/js/theme-customizer-init.min.js"></script>
    <!--! END: Theme Customizer !-->
<script>
document.getElementById('projectSelect').addEventListener('change', function(){

    const projectId = this.value;

    if(projectId === ''){
        document.getElementById('userName').value  = '';
        document.getElementById('userEmail').value = '';
        document.getElementById('userPhone').value = '';
        return;
    }

    fetch('ajax_project_details_user.php?project_id=' + projectId)
    .then(res => res.json())
    .then(data => {

        if(data.error){
            alert('Unable to fetch project details');
            return;
        }

        document.getElementById('userName').value  = data.name || '';
        document.getElementById('userEmail').value = data.email || '';
        document.getElementById('userPhone').value = data.phone || '';
    })
    .catch(err => {
        console.error(err);
        alert('AJAX error');
    });
});
</script>

</html>
<?php
include 'dbcon.php';

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

    $project_id = (int)$_POST['project_id'];
    $name       = $_POST['name'];
    $email      = $_POST['email'];
    $mobile     = $_POST['mobile'];
    $username   = $_POST['username'];
    $password   = $_POST['password'];

    $hash = password_hash($password, PASSWORD_DEFAULT);

    $stmt = $conn->prepare(
        "INSERT INTO users (username, name, mobile, email, password)
         VALUES (?, ?, ?, ?, ?)"
    );

    if ($stmt) {
        $stmt->bind_param("sssss", $username, $name, $mobile, $email, $hash);

        if ($stmt->execute()) {

            /* ✅ 1️⃣ LAST INSERT ID */
            $user_id = $conn->insert_id;

            /* ✅ 2️⃣ PROJECT → USER ASSIGN */
            $upd = $conn->prepare(
                "UPDATE projects
                 SET user_id = ?
                 WHERE id = ? AND user_id IS NULL"
            );
            $upd->bind_param("ii", $user_id, $project_id);
            $upd->execute();
            $upd->close();
            ?>

            <script>
            Swal.fire({
                icon: 'success',
                title: 'Registered',
                text: 'User created and project assigned successfully',
                confirmButtonColor: '#28a745'
            }).then(() => {
                window.location.href = 'create_user.php';
            });
            </script>

            <?php
        } else {

            // DUPLICATE USERNAME
            if ($conn->errno == 1062) {
                ?>
                <script>
                Swal.fire({
                    icon: 'warning',
                    title: 'Username Exists',
                    text: 'This username is already taken. Try another one.'
                });
                </script>
                <?php
            } else {
                ?>
                <script>
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: 'Something went wrong. Please try again.'
                });
                </script>
                <?php
            }
        }

        $stmt->close();
    }

    $conn->close();
}
?>
