<?php
/**
 * modules/users/add_users.php
 */

// 1. STRICT SECURITY KICK-OUT
$p = $GLOBALS['my_privs'] ?? ['can_view' => 0, 'can_add' => 0, 'can_edit' => 0, 'can_del' => 0];
if (in_array(1, $_SESSION['all_role_ids'] ?? [])) {
    $p = ['can_view' => 1, 'can_add' => 1, 'can_edit' => 1, 'can_del' => 1];
}

if ($p['can_add'] == 0) {
    header("Location: index.php?s=" . encrypt_url('mod=users&page=list_users') . "&status=access_denied");
    exit;
}

// 2. FORM POST HANDLER
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $full_name = $db->escape($_POST['full_name']);
    $username  = $db->escape($_POST['username']);
    $password  = password_hash($_POST['password'], PASSWORD_BCRYPT); // Secure standard hashing
    $status    = $db->escape($_POST['status']);
    $role_ids  = $_POST['role_ids'] ?? []; // Array of selected roles
    $created_by = (int)$_SESSION['user_id'];

    // Check Duplicate Username
    $check_sql = "SELECT USER_ID FROM TBL_USERS WHERE USERNAME = '$username'";
    if (mysqli_num_rows($db->query($check_sql)) > 0) {
        header("Location: index.php?s=" . encrypt_url('mod=users&page=add_users') . "&status=duplicate");
        exit;
    }

    // Insert Base User
    $sql = "INSERT INTO TBL_USERS (USERNAME, PASSWORD, FULL_NAME, STATUS, CREATED_BY) 
            VALUES ('$username', '$password', '$full_name', '$status', $created_by)";
    
    if ($db->query($sql)) {
        // Grab the auto-generated ID of the user we just created
        $new_user_id = mysqli_insert_id($db->conn);

        // Loop through all selected roles and assign them in the Junction Table
        foreach ($role_ids as $r_id) {
            $r_id = (int)$r_id;
            $db->query("INSERT INTO TBL_USER_ROLES (USER_ID, ROLE_ID) VALUES ($new_user_id, $r_id)");
        }

        header("Location: index.php?s=" . encrypt_url('mod=users&page=list_users') . "&status=added");
        exit;
    }
}

// Fetch Active Roles for the Dropdown
$roles_sql = "SELECT * FROM TBL_ROLES WHERE STATUS = 'ACTIVE' ORDER BY ROLE_NAME ASC";
$roles_result = $db->query($roles_sql);
?>

<!-- Select2 CSS for Multi-Select -->
<link rel="stylesheet" href="assets/plugins/select2/css/select2.min.css">
<link rel="stylesheet" href="assets/plugins/select2-bootstrap4-theme/select2-bootstrap4.min.css">

<style>
    /* Styling to match WIMAS Orange Theme */
    .select2-container--bootstrap4 .select2-selection--multiple .select2-selection__choice {
        background-color: var(--slcmc-orange) !important;
        border-color: var(--slcmc-orange) !important;
        color: white;
    }
</style>

<section class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1 class="font-weight-bold text-primary"><i class="fas fa-user-plus mr-2"></i>Register New User</h1>
            </div>
            <div class="col-sm-6 text-right">
                <a href="index.php?s=<?php echo encrypt_url('mod=users&page=list_users'); ?>" class="btn btn-default shadow-sm">
                    <i class="fas fa-arrow-left mr-1"></i> Back to Users
                </a>
            </div>
        </div>
    </div>
</section>

<section class="content">
    <div class="container-fluid">
        <form action="" method="POST">
            <div class="card card-outline card-primary shadow-sm">
                <div class="card-header bg-white">
                    <h3 class="card-title font-weight-bold text-primary">Profile & Security Settings</h3>
                </div>
                <div class="card-body">
                    
                    <div class="row">
                        <div class="col-md-6 form-group">
                            <label class="text-secondary">Full Name <span class="text-danger">*</span></label>
                            <input type="text" name="full_name" class="form-control" placeholder="e.g. John Doe" required>
                        </div>
                        <div class="col-md-3 form-group">
                            <label class="text-secondary">Login Username <span class="text-danger">*</span></label>
                            <input type="text" name="username" class="form-control" placeholder="e.g. jdoe" required autocomplete="new-password">
                        </div>
                        <div class="col-md-3 form-group">
                            <label class="text-secondary">Initial Password <span class="text-danger">*</span></label>
                            <input type="password" name="password" class="form-control" placeholder="Create password" required autocomplete="new-password">
                        </div>
                    </div>

                    <hr>

                    <div class="row bg-light p-3 rounded border">
                        <div class="col-md-8 form-group mb-0">
                            <label class="text-dark">Assign Roles (Multiple Allowed) <span class="text-danger">*</span></label>
                            <!-- Notice the name="role_ids[]" array and multiple="multiple" -->
                            <select name="role_ids[]" class="form-control select2" multiple="multiple" data-placeholder="Select acting charges/roles" style="width: 100%;" required>
                                <?php while($r = mysqli_fetch_assoc($roles_result)): ?>
                                    <option value="<?php echo $r['ROLE_ID']; ?>"><?php echo $r['ROLE_NAME']; ?></option>
                                <?php endwhile; ?>
                            </select>
                            <small class="text-muted">You can select more than one role if the user holds an acting/additional charge.</small>
                        </div>
                        
                        <div class="col-md-4 form-group mb-0">
                            <label class="text-dark">Account Status</label>
                            <select name="status" class="form-control border-primary">
                                <option value="ACTIVE">ACTIVE</option>
                                <option value="SUSPENDED">SUSPENDED</option>
                            </select>
                        </div>
                    </div>

                </div>
                <div class="card-footer bg-white text-right">
                    <button type="submit" class="btn btn-primary px-5 font-weight-bold shadow-sm">
                        <i class="fas fa-save mr-2"></i> CREATE ACCOUNT
                    </button>
                </div>
            </div>
        </form>
    </div>
</section>

<!-- Select2 JS -->
<script src="assets/plugins/select2/js/select2.full.min.js"></script>
<script>
    $(function () {
        // Initialize Select2 Elements for multi-role tagging
        $('.select2').select2({
            theme: 'bootstrap4'
        });
    });
</script>