<?php
session_start();
include ('../config/conn.php');
include ('../config/function.php');

if(isset($_POST['tambah'])){
    $nama_pengguna = $_POST['nama_pengguna'];
    $kata_sandi = password_hash($_POST['kata_sandi'],PASSWORD_DEFAULT);

    $cek = mysqli_query($con,"SELECT * FROM users WHERE nama_pengguna='$nama_pengguna'") or die(mysqli_error($con));
    if(mysqli_num_rows($cek)==0){
        $insert = mysqli_query($con,"INSERT INTO users (nama_pengguna, kata_sandi) VALUES ('$nama_pengguna','$kata_sandi')") or die (mysqli_error($con));
        if($insert){
            $success = 'Berhasil menambahkan data users';
        }else{
            $error = 'Gagal menambahkan data users';
        }
    }else{
        $error = 'nama_pengguna telah terdaftar !';
    }
    $_SESSION['success'] = $success;
    $_SESSION['error'] = $error;
    header('Location:../dashboard.php?pengguna');
}
if(isset($_POST['ubah'])){
    $nama_pengguna = $_POST['nama_pengguna'];
    $kata_sandi = $_POST['kata_sandi'];
    // $level = $_POST['level'];

    if($kata_sandi!=""){
        $update = mysqli_query($con,"UPDATE users SET nama_pengguna='$nama_pengguna', kata_sandi='".password_hash($kata_sandi,PASSWORD_DEFAULT)."' WHERE id_users='$id'") or die (mysqli_error($con));
    }else{
        $update = mysqli_query($con,"UPDATE users SET nama_pengguna='$nama_pengguna' WHERE id_users='$id'") or die (mysqli_error($con));
    }
    if($update){
        $success = 'Berhasil mengubah data users';
    }else{
        $error = 'Gagal mengubah data users';
    }
    $_SESSION['success'] = $success;
    $_SESSION['error'] = $error;
    header('Location:../dashboard.php?pengguna');
}

if(decrypt($_GET['act'])=='delete' && isset($_GET['id'])!=""){
    $id = decrypt($_GET['id']);
    $delete = mysqli_query($con, "DELETE FROM users WHERE id_users='$id'")or die(mysqli_error($con));
    if ($delete) {
        $success = "Data users berhasil dihapus";
    }else{
        $error = "Data users gagal dihapus";
    }
    $_SESSION['success'] = $success;
    header('Location:../dashboard.php?pengguna');
}

if(decrypt($_GET['act'])=='ganti_pass' && isset($_POST['ubah_pass'])){
    $id = $_POST['id'];
    $kata_sandi =password_hash($_POST['password'],PASSWORD_DEFAULT);

    $update = mysqli_query($con,"UPDATE users SET kata_sandi='$kata_sandi' WHERE id_users='$id'") or die (mysqli_error($con));
    $_SESSION['success'] = "Anda berhasil mengubah kata_sandi";
    echo '<script>window.history.back();</script>';
}

?>