<?php
require_once('config.php');



$roles = mysqli_query($db, "SELECT * FROM roles");
while($role = mysqli_fetch_assoc($roles)){

    $json = [];
    $parent = mysqli_query($db, "SELECT * FROM emp_files WHERE `status`=1 and parent=0 and find_in_set('$role[id]', default_access_role)");
    while($row = mysqli_fetch_assoc($parent)){
        $sub = mysqli_query($db, "SELECT * FROM emp_files WHERE `status`=1 and parent='$row[id]' and find_in_set('$role[id]', default_access_role)");
        // echo "SELECT * FROM emp_files WHERE parent='$row[id]' and find_in_set('$user[role]', default_access_role)\n";
        $sub_json = [];
        while($r = mysqli_fetch_assoc($sub)){
            array_push($sub_json, $r['id']);
        }
        $json += [$row['id']=>$sub_json];
    }

    $j = json_encode($json);

    if(mysqli_query($db, "UPDATE roles SET default_files_access='$j' WHERE id='$role[id]'")){
        echo "role updated \n";
    }else{
        echo mysqli_error($db);
    }
    
}



$users = mysqli_query($db, "SELECT t1.* FROM users t1 LEFT join files_permission t2 ON t1.id=t2.user_id WHERE t2.permission IS NULL");
while($user = mysqli_fetch_assoc($users)){
    
    $role = mysqli_fetch_assoc(mysqli_query($db, "SELECT * FROM roles WHERE id='$user[role]'"));

    if(mysqli_query($db, "INSERT INTO files_permission (user_id, permission) VALUES('$user[id]','$role[default_files_access]')")){
        echo "file permission updated \n";
    }else{
        echo mysqli_error($db);
    }

}