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

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

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

$user_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($user_id == 0) {
    header("Location: index.php?s=" . encrypt_url('mod=users&page=list_users'));
    exit;
}

// 2. FORM POST HANDLER
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $full_name = $db->escape($_POST['full_name']);
    $username  = $db->escape($_POST['username']);
    $status    = $db->escape($_POST['status']);
    $role_ids  = $_POST['role_ids'] ?? [];
    $updated_by = (int)$_SESSION['user_id'];

    // Check duplicate username (excluding current user)
    $check_sql = "SELECT USER_ID FROM TBL_USERS WHERE USERNAME = '$username' AND USER_ID != $user_id";
    if (mysqli_num_rows($db->query($check_sql)) > 0) {
        header("Location: index.php?s=" . encrypt_url("mod=users&page=edit_users&id=$user_id") . "&status=duplicate");
        exit;
    }

    // Base Update Query
    $sql = "UPDATE TBL_USERS 
            SET FULL_NAME = '$full_name', 
                USERNAME = '$username', 
                STATUS = '$status', 
                UPDATED_BY = $updated_by, 
                UPDATED_DATE = CURRENT_TIMESTAMP 
            WHERE USER_ID = $user_id";
            
    // Optional Password Update
    if (!empty($_POST['password'])) {
        $password = password_hash($_POST['password'], PASSWORD_BCRYPT);
        $sql = "UPDATE TBL_USERS 
                SET FULL_NAME = '$full_name', 
                    USERNAME = '$username', 
                    PASSWORD = '$password', 
                    STATUS = '$status', 
                    UPDATED_BY = $updated_by, 
                    UPDATED_DATE = CURRENT_TIMESTAMP 
                WHERE USER_ID = $user_id";
    }

    if ($db->query($sql)) {
        // Wipe old roles and insert new ones
        $db->query("DELETE FROM TBL_USER_ROLES WHERE USER_ID = $user_id");
        
        foreach ($role_ids as $r_id) {
            $r_id = (int)$r_id;
            $db->query("INSERT INTO TBL_USER_ROLES (USER_ID, ROLE_ID) VALUES ($user_id, $r_id)");
        }

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

// 3. FETCH EXISTING DATA
$user_sql = "SELECT * FROM TBL_USERS WHERE USER_ID = $user_id";
$user_res = $db->query($user_sql);
$data = mysqli_fetch_assoc($user_res);

// Fetch User's Current Roles into an Array
$current_roles = [];
$role_check_sql = $db->query("SELECT ROLE_ID FROM TBL_USER_ROLES WHERE USER_ID = $user_id");
while($row = mysqli_fetch_assoc($role_check_sql)){
    $current_roles[] = $row['ROLE_ID'];
}

// Fetch available roles for the dropdown (HRBAC Enforced)
$my_priority = $_SESSION['role_priority'] ?? 99;
$allowed_priority_clause = ($my_priority == 1) ? ">= 1" : "> $my_priority";
$roles_sql = "SELECT * FROM TBL_ROLES WHERE STATUS = 'ACTIVE' AND ROLE_PRIORITY $allowed_priority_clause ORDER BY ROLE_NAME ASC";
$roles_result = $db->query($roles_sql);
?>

<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>
    .select2-container--bootstrap4 .select2-selection--multiple .select2-selection__choice {
        background-color: #007bff !important;
        border-color: #007bff !important;
        color: white;
    }
</style>

<div class="p-3">
    <section class="content-header px-0">
        <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-edit mr-2"></i>Update 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 border">
                        <i class="fas fa-arrow-left mr-1"></i> Cancel Update
                    </a>
                </div>
            </div>
        </div>
    </section>

    <section class="content px-0">
        <div class="container-fluid">
            <form action="" method="POST">
                <div class="card card-outline card-primary shadow-sm" style="border-top: 4px solid #007bff;">
                    <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" value="<?php echo $data['FULL_NAME']; ?>" 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" value="<?php echo $data['USERNAME']; ?>" required autocomplete="off">
                            </div>
                            <div class="col-md-3 form-group">
                                <label class="text-secondary">Reset Password</label>
                                <input type="password" name="password" class="form-control" placeholder="Leave blank to keep current" autocomplete="new-password">
                            </div>
                        </div>

                        <hr>

                        <div class="row bg-light p-3 rounded border mt-3">
                            <div class="col-md-8 form-group mb-0">
                                <label class="text-dark">Assign Roles (Multiple Allowed) <span class="text-danger">*</span></label>
                                <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 in_array($r['ROLE_ID'], $current_roles) ? 'selected' : ''; ?>>
                                            <?php echo $r['ROLE_NAME']; ?>
                                        </option>
                                    <?php endwhile; ?>
                                </select>
                            </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" <?php echo ($data['STATUS'] == 'ACTIVE') ? 'selected' : ''; ?>>ACTIVE</option>
                                    <option value="SUSPENDED" <?php echo ($data['STATUS'] == 'SUSPENDED') ? 'selected' : ''; ?>>SUSPENDED</option>
                                </select>
                            </div>
                        </div>

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

<script src="assets/plugins/select2/js/select2.full.min.js"></script>
<script>
    $(function () {
        $('.select2').select2({ theme: 'bootstrap4' });
    });
</script>