<?php //echo $user;exit;?>
@extends('layouts/contentLayoutMaster')

@section('title', 'User')

@section('vendor-style')
    <link rel="stylesheet" href="{{ asset(mix('vendors/css/extensions/toastr.min.css')) }}">
@endsection
@section('page-style')
    <link rel="stylesheet" href="{{ asset(mix('css/base/plugins/extensions/ext-component-toastr.css')) }}">
@endsection
@section('content')
    <div class="card">
        <div class="card-header">
            <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#Add-New-User">Add New User</button>
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-1">
                    <select name="per_page" id="per-page" class="form-control" onchange="js:getUserList('<?= $token ?>',1,25,'<?= $user ?>','<?=$role?>','<?=$type?>')">
                        <option value="<?= PAGINATE_LIMIT ?>"><?= PAGINATE_LIMIT ?></option>
                        <option value="50">50</option>
                        <option value="100">100</option>
                        <option value="250">250</option>
                        <option value="500">500</option>
                    </select>
                </div>
                <div class="col-md-5"><input type="text" id="user" class="form-control" onkeyup="js:getUserList('<?= $token ?>',1,25,'<?= $user ?>','<?=$role?>','<?=$type?>')" placeholder="User Here"></div>
                
            </div>
            <br>
            <div class="row">
                <div class="table-responsive">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>Sr No.</th>
                                <th>Name</th>
                                @if($role == 'MARKETING' && $user == 'customer')
                                    <th>Email</th>
                                    <th>Contact Number</th>
                                @elseif($role != 'MARKETING' && $user == 'customer')
                                @elseif($role != 'MARKETING' && $user != 'customer')
                                    <th>Type</th>
                                    <th>Email</th>
                                    <th>Contact Number</th>
                                    <th>Role</th>
                                    @if (str_contains($user, 'branch_')) 
                                    <th>Branch</th>
                                    @endif
                                @endif
                                <th>Created At</th>
                                <th></th>
                            </tr>
                        </thead>
                        <tbody id="userlist">
                         
                        </tbody>
                    </table>
                </div>
                <div id="pagination-links"></div>
            </div>
            <div id="totalofrecord"></div>
        </div>
    </div>
    <div class="modal fade text-start" id="Add-New-User" tabindex="-1" aria-labelledby="myModalLabel17" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-lg">
            <div class="modal-content">
                <form id="register">
                    <div class="modal-header">
                      <h4 class="modal-title" id="myModalLabel17">Add New User</h4>
                      <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-12">
                                <lable><i>Email Id, Phone Number can not be duplicate!</i></lable>
                            </div>
                        </div>
                        <div class="row">
                            <input type="hidden" id="role" class="form-control mb-2" value="{{ $user }}" name="role">
                            <div class="col-md-6">
                            @if (str_contains($user, 'branch_')) 
    
                            <input type="hidden" id="branch" class="form-control mb-2" value="0" name="branch">
                            <select class="form-control mb-2 branch-dropdown" id="branch" name="branch">
                                <option value="">Select Branch</option>
                            </select>
                            @else
                                <input type="hidden" id="branch" class="form-control mb-2" value="0" name="branch">
                                
                                <?php $allowedRole = ['PURCHASE_MANAGER','BULLION_VENDOR','NORMAL_VENDOR','STOCK_MANAGER','CASHIER','ORDER_MANAGER','KARIGAR','MARKETING','RECEPTIONIST'];
                               // echo $user;
                               // print_r($role);
                               ?>
                                @if(($role == 'ADMIN' || $role == 'SUPER_ADMIN') && in_array(strtoupper($user),$allowedRole))
                                <?php //echo 'in array';?>
                                    <select name="metal_type" id="metal_type" class="form-control"><option value="gold">Gold</option><option value="silver">Silver</option><option value="diamond">Diamond</option></select>
                                @else
                                <?php// echo 'not in array';?>
                                    <input type="hidden" id="metal_type" class="form-control mb-2" value="{{ $type}}" name="metal_type">
                                @endif
                            
                            
                            @endif
                            </div>
                            <div class="col-md-12">
                                <input type="text" id="name" class="form-control mb-2" placeholder="Name" name="name">
                                <span id="name_error"></span>
                            </div>
                            <div class="col-md-6">
                                <input type="email" id="email" class="form-control mb-2" placeholder="Email" name="email">
                                <span id="email_error"></span>
                            </div>
                            <div class="col-md-6">
                            <input type="text" id="passwrd" class="form-control mb-2" placeholder="Password" name="password">
                            <span id="password_error"></span>
                            </div>
                            <div class="col-md-6">
                            <input type="text" id="short_code" class="form-control mb-2" placeholder="Short Code" name="short_code">
                            <span id="short_code_error"></span>
                            </div>
                            <div class="col-md-6">
                                <input type="number" id="contact_number" class="form-control mb-2" placeholder="Contact Number" name="contact_number">
                                <span id="contact_number_error"></span>
                            </div>
                            <div class="col-md-6">
                                <input type="number" id="aadharcard_number" class="form-control mb-2" placeholder="Aadhar Number" name="aadhar_number">
                                <span id="aadhar_number_error"></span>
                            </div>
                            <div class="col-md-6">
                                <input type="text" id="pancard_number" class="form-control mb-2" placeholder="Pancard Number" name="pancard_number">
                                <span id="pancard_number_error"></span>
                            </div>
                            <div class="col-md-6">
                                <input type="text" id="gst_number" class="form-control mb-2" placeholder="GST Number" name="gst">
                                <span id="gst_error"></span>
                            </div>
                            <div class="col-md-6">
                                <textarea id="address" class="form-control" placeholder="Address" name="address"></textarea>
                                <span id="address_error"></span>
                            </div>
                        </div>
                        
                        
                    </div>
                    <div class="modal-footer">
                      <!--<button type="button" class="btn btn-primary" onclick="js:createUser('{{ $token }}')">Save</button>-->
                      <button type="button" class="btn btn-primary" onclick="js:createUsers('{{ $token }}')">Save</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <div class="modal fade text-start" id="edit-user-detail" tabindex="-1" aria-labelledby="myModalLabel17" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-lg">
            <div class="modal-content">
                <form id="edit-user">
                    <div class="modal-header">
                      <h4 class="modal-title" id="myModalLabel17">Edit User</h4>
                      <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <div class="row">
                           <input type="hidden" id="id" class="form-control mb-2" placeholder="Name"  name="id">
                            <input type="text" id="name" class="form-control mb-2" placeholder="Name"  name="name">
                            
                            <input type="email" id="email" class="form-control mb-2" placeholder="Email" name="email" readonly>
                            
                            <input type="text" id="password" class="form-control mb-2" placeholder="Password" name="password">
                            <input type="text" id="short_code" class="form-control mb-2" placeholder="Short Code" name="short_code">
                            <input type="number" id="contact_number" class="form-control mb-2" placeholder="Contact Number" name="contact_number">
                            
                            
                        </div>
                    </div>
                    <div class="modal-footer">
                      <button type="button" class="btn btn-primary" onclick="js:editUsers('{{ $token }}')">Save</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
@endsection

@section('vendor-script')
    <script src="{{ asset(mix('vendors/js/extensions/toastr.min.js')) }}"></script>
@endsection

@section('page-script')
    <script src="{{ asset(mix('js/scripts/custom/common.js')) }}"></script>
<script>
$(document).ready(function() {
    //console.log('reached here');
    getUserList('<?=$token?>',1,25,'<?=$user?>','<?=$role?>','<?=$type?>');
});
function getUserList(token,page_no,per_page,user,role,type){
    try{
        //console.log('reached in getuserlist');
       // url: "/api/user/getAllUser",
      
        var per_page = $('#per-page').val();
        var name = $('#user').val();
        $.ajax({
        url: "/api/user/getRoleWiseUser",
        type: "get",
        dataType: "json",
        headers: {
            Authorization: "Bearer " + token,
        },
        data: {
            page:page_no,
            per_page:per_page,
            role:user,
            name:name,
            type:type
        },
        success: function (response) {
            $("#pagination-links").empty();
            $('#userlist').empty();
            var i = 0;
        response.data.forEach(response_data => {
           
            i++;
            var list = `<tr id="`+response_data.id+`">
            <td>`+i+`</td>
            <td>`+response_data.name+`</td>`;
            if(role == 'MARKETING' && user == 'customer'){
                list+=`<td>${response_data.email}</td>
                <td>${response_data.contact_number}</td>`;
            }else if(role != 'MARKETING' && user == 'customer'){
            }else if(role != 'MARKETING' && user != 'customer'){
                list+=`<td>${response_data.metal_type}</td>
                <td>${response_data.email}</td>
                <td>${response_data.contact_number}</td>
                <td>`+response_data.role+`</td>`;
                if(user.includes("branch")){
               // if (str_contains($user, 'BRANCH_')){
		            list+=`<td>`+response_data.city+`</td>`;
                }
               
            }
            list+=`<td>`+response_data.created_at+`</td>`;
            if((role == 'MARKETING' && user == 'customer') || (role !== 'MARKETING' && user !== 'customer')){
               list+='<td><button type="button" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#edit-user-detail" id="edit_'+response_data.id+'" onclick="js:userDetail(\''+token+'\','+response_data.id+')">Edit </button></td>'; 
            }
            
            list+=`</tr>`;
            $('#userlist').append(list);
            
        });
        //PAGINATION LINKS
        response.links.forEach(element => {
            let url_page_no = 1;
            if (element.url != null) {
                url_page_no = element.url.split('?')[1].split('=')[1];   
            }
            $("#pagination-links").append(`<button onclick="js:getUserList('`+token+`',${url_page_no}, ${per_page},'`+user+`')" class="btn btn-dark">${element.label}</button>`);
        });
        $('#totalofrecord').text('Total No. of Records = '+response.total);
            },
    });
    }catch(e){
        console.log(e);
    }
}

function userDetail(token,id){
            try{
                $.ajax({
                    url: "/api/gold-management/user/userDetail",
                    type: "get",
                    dataType: 'json',
                    headers: {
                        'Authorization': 'Bearer '+token 
                    },
                    data:{
                        'id':id
                    },
                    success: function(response){
                       // console.log(response);
                        //if(response.status === 'true'){
                            $('#edit-user-detail #id').val(response.id);
                            $('#edit-user-detail #name').val(response.name);
                            $('#edit-user-detail #short_code').val(response.short_code);
                            $('#edit-user-detail #email').val(response.email);
                            $('#edit-user-detail #password').val(response.password);
                            $('#edit-user-detail #contact_number').val(response.contact_number);
                        /*}else{
                           
                        }*/
                    }
                });
            }catch(e){
                console.log(e);
            }
        }
        
        function editUsers(token){
             try{
        //console.log('reached here');
        var formData = new FormData(document.getElementById("edit-user"));
        $.ajax({
            url: "/api/gold-management/user/edit",
            type: "post",
            dataType: 'json',
            headers: {
                'Authorization': 'Bearer '+token
            },
            data:formData,
            async: false,
            cache: false,
            contentType: false,
            processData: false,
            success: function(response){
                console.log(response);
                //alert(response);
                if(response.status == true){
                    $('#edit-user-detail').modal('hide');
                    setTimeout(function () {
                            toastr["success"](
                                "",
                                response.msg,
                                {
                                    closeButton: false,
                                    tapToDismiss: false,
                                    rtl: "rtl",
                                }
                            );
                        }, 2000);
                        $('#edit-user')[0].reset();
                    
                    location.reload();
                }else{
                    setTimeout(function () {
                            toastr["success"](
                                "",
                                response.msg,
                                {
                                    closeButton: false,
                                    tapToDismiss: false,
                                    rtl: "rtl",
                                }
                            );
                        }, 2000);
                }
                   
            },
            fail:function(response){
                console.log('in failure');
            },
        });
    }catch(e){
        console.log(e);
    }
        }
        
    
    
    function deleteUser(token, id){
        try{
            alert('Are You Sure Want To Delete this User');
            $.ajax({
                url: "/api/gold-management/user/deleteUser",
                type: "get",
                dataType: 'json',
                headers: {
                    'Authorization': 'Bearer '+token
                },
                data:{'id':id},
                success: function(response){
                    if(response.status == true){
                       location.reload();
                    }else{
                        setTimeout(function () {
                            toastr["error"](
                                "",
                                response.msg,
                                {
                                    closeButton: false,
                                    tapToDismiss: false,
                                    rtl: "rtl",
                                }
                            );
                        }, 2000);
                    }  
                },
                fail:function(response){
                    console.log('in failure');
                },
            });
        }catch(e){
            console.log(e);
        }
    }
</script>
@endsection
