<?php
session_start();
require_once '../../config.php';
load('middleware', 'user');
$date = date('Y-m-d H:i:s');
if ($_SESSION['user']['level'] !== "Admin") {
    header('location:' . base_url('id'));

}

if (isset($_POST['edit_user'])) {
    $ppid =  $db->real_escape_string(e(@$_POST['id']));
    $saldo =  $db->real_escape_string(e(@$_POST['saldoo']));
    $level =  $db->real_escape_string(e(@$_POST['level']));
	    if(isset($saldo)){
	        
	        $db->query("UPDATE users SET saldo = '$saldo', level='$level' WHERE id = '$ppid'");
	        $_SESSION['alert'] = ['success', 'Success!', 'User successfully change.'];
	        exit(header("Location: ".base_url('/admin/user/')));

		}else{
		    $_SESSION['alert'] = ['danger', 'Failed!', 'User Failed change.'];
		    exit(header("Location: ".base_url('/admin/user/')));
	        
		}
	} 
	
if (isset($_POST['add_user'])) {
	$username =  $db->real_escape_string(e(@$_POST['username']));
	$password =  $db->real_escape_string(e(@$_POST['password']));
	$level =  $db->real_escape_string(e(@$_POST['level']));
	$phone =  $db->real_escape_string(e(@$_POST['phone']));
	$email =  $db->real_escape_string(e(@$_POST['email']));
	$name =  $db->real_escape_string(e(@$_POST['name']));
	$date = date('Y-m-d H:i:s');
	$exp = date('Y-m-d H:i:s', strtotime('+30 days'));
	
	if (!$username || !$password || !$level || !$phone || !$email || !$name) {
	    $_SESSION['alert'] = ['danger', 'Failed!', 'Masih ada form kosong.'];
	    exit(header("Location: ".base_url('/admin/user/')));
	} else {
	       $api_key = random(64);
	       $api_id = random(12);
	       $pass = password_hash($password, PASSWORD_DEFAULT);
	       $insert_srvc = $db->query("INSERT INTO users VALUES('','$name', '$email','$phone','$username', '$pass', '0', '0','$level','active','YES','$api_key','$api_id','0','0','$date','$exp')");
			if ($insert_srvc === true) {
				$_SESSION['alert'] = ['success', 'Success!', 'User successfully add.'];
				exit(header("Location: ".base_url('/admin/user/')));
		
			} else {
				$_SESSION['alert'] = ['danger', 'Failed!', 'System is busy, please try again later.'];
				exit(header("Location: ".base_url('/admin/user/')));
		
			}
		}
	}

if (isset($_POST['delete_user'])) {
	$pid =  $db->real_escape_string(e(@$_POST['iid']));
        $delete_srvc = $db->query("DELETE FROM users WHERE id = '$pid'");
                if ($delete_srvc === true) {
                    $_SESSION['alert'] = ['success', 'Success!', 'User successfully delete.'];
                    exit(header("Location: ".base_url('/admin/user/')));
                } else {
                    $_SESSION['alert'] = ['danger', 'Failed!', 'System is busy, please try again later.'];
                    exit(header("Location: ".base_url('/admin/user/')));
                }
           }
require '../../layouts/header-admin.php';?>
<div class="row">
        <div class="col-12">
            <div class="card bg-dark shadow">
                <div class="card-header">
                    <h4 class="card-title float-left">Kelola User</h4>
                    <button class="btn btn-success float-right" onclick="modal('Tambah User','<?= base_url('admin/user/service_user/add_user'); ?>');">Add</button>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        	<table class="table table-striped table-dark table-bordered table-hover dataTable no-footer" id="datatabl3s">
                            <thead>
                                <tr>
                                    <th>Username</th>
                                    <th>Email</th>
                                    <th>Phone</th>
                                    <th>Act.</th>
                                </tr>
                            </thead>
                            <tbody>
                            <td colspan="4" class="text-center">Loading data from server...</td>
                            </tbody>		
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
<?php include_once '../../layouts/footer-admin.php';?>
<script type="text/javascript">
$(document).ready(function() {
    $('#datatabl3s').DataTable({
        "order": [[0, 'desc']],
        "processing": false,
        "serverSide": true,
        "paging": true,
        "pagingType": "simple_numbers",
        "ajax": "<?= base_url('admin/user/users.php'); ?>",
        columnDefs : [
        {
        "searhable" : false,
        "orderable" : false,
        "targets" : 3,
        "render" : function(data, type, row) {
            var btn = "<button class=\"btn btn-warning btn-sm\" onclick=\"modal('Edit User','<?= base_url(); ?>admin/user/service_user/edit_user?id="+data+"')\"><i class=\"fas fa-edit\"></i> Edit</button> <button class=\"btn btn-danger btn-sm\" href = \"javascript:;\" onclick=\"modal('Delete Users','<?= base_url(); ?>admin/user/service_user/delete_user?id="+data+"')\"><i class=\"fa fa-trash\"></i> Delete</button>"
            return btn;
        }
        } 
                     ]
        
    });
});
</script>
<script type="text/javascript">
    function modal(name, link, size) {
        var sizes = '';
        if (size == 'smaller' || size == 'xs') sizes = 'modal-xs';
        if (size == 'small' || size == 'sm') sizes = 'modal-sm';
        if (size == 'large' || size == 'lg') sizes = 'modal-lg';
        if (size == 'larger' || size == 'xl') sizes = 'modal-xl';

        $.ajax({
            type: "GET",
            url: link,
            beforeSend: function() {
                $('#SModal-body').html('Loading...');
            },
            success: function(result) {
                $('#SModal-body').html(result);
            },
            error: function() {
                $('#SModal-body').html('Failed to get contents...');
            }
        });

        $('#SModal-title').html(name);
        $('#SModal-size').removeClass('modal-xs');
        $('#SModal-size').removeClass('modal-sm');
        $('#SModal-size').removeClass('modal-lg');
        $('#SModal-size').removeClass('modal-xl');
        $('#SModal-size').addClass(sizes);
        $('#SModal').modal('show');
    }
</script>
<div class="modal fade text-left" id="SModal" tabindex="-1" role="dialog" aria-labelledby="SModal" aria-hidden="true" data-backdrop="static">
    <div class="modal-dialog" id="SModal-size" role="document">
        <div class="modal-content bg-dark">
            <div class="modal-header">
                <h5 class="modal-title" id="SModal-title"></h5>
                <button type="button" class="close" data-bs-dismiss="modal" aria-label="Close"><span aria-hidden="true" style="text-shadow: none; color:white;">&times;</span></button>
            </div>
            <div class="modal-body" id="SModal-body"></div>
        </div>
    </div>
</div>