@extends('template.app')

@section('meta')
@endsection

@section('title') Users @endsection

@section('styles')
    <link href="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/css/select2.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.7/css/jquery.dataTables.min.css">
    <style>
        .highlight {
            background-color: #ffff99; 
        }
        #data-table.dataTable tbody td {
            padding: 0px !important;
            height: 20px !important;
            line-height: 35px !important;
            font-size: 15px !important;
            text-align: center;
        }
        .form-group .custom_color {
            background-color: lightgrey !important;
        }
    </style>
@endsection

@section('content')
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
    <link href="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/css/select2.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.7/css/jquery.dataTables.min.css">
    <style>
        #data-table td {
            white-space: nowrap;
            padding: 0.5rem !important;
            font-size: 15px;
        }
        .width_150 {
            width: 150px;
        }
        .width_200 {
            width: 200px;
        }
        .width_250 {
            width: 250px;
        }
        .width_300 {
            width: 300px;
        }
        .width_350 {
            width: 350px;
        }
    </style>    

    <div class="page-breadcrumb">
        <div class="row">
            <div class="col-4 align-self-center">
                <h4 class="page-title text-truncate text-dark font-weight-medium mb-1">Users</h4>
                <div class="d-flex align-items-center">
                    <nav aria-label="breadcrumb">
                        <ol class="breadcrumb m-0 p-0">
                            <li class="breadcrumb-item"><a href="{{ route('dashboard') }}" class="text-muted">Dashboard</a></li>
                            <li class="breadcrumb-item"><a href="{{ route('user') }}" class="text-muted">Users</a></li>
                            <li class="breadcrumb-item text-muted active" aria-current="page">List</li>
                        </ol>
                    </nav>
                </div>
            </div>

            <div class="col-8 align-self-center">
                <div class="customize-input float-right">
                    <!-- Users -->
                    <a class="btn waves-effect waves-light btn-rounded btn-outline-primary pull-right"  href="{{ route('user') }}">Users</a>
                    <!-- Trash -->
                    <a class="btn waves-effect waves-light btn-rounded btn-outline-primary pull-right" href="{{ route('user.trash') }}">Trash</a>
                    <!-- Example Excel -->
                    <a class="btn waves-effect waves-light btn-rounded btn-outline-primary pull-right" href="{{url('/example-xlsx/example-users.xlsx')}}" download>Example Excel</a>
                    <!-- Import -->
                        <a class="btn waves-effect waves-light btn-rounded btn-outline-primary pull-right" data-toggle="modal" data-target="#exampleModal" href="Javascript:void(0)">Import</a>
                    <!-- Export -->
                        <button class="btn waves-effect waves-light btn-rounded btn-outline-primary pull-right" type="button" data-toggle="collapse" data-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample">Export</button>
                    <!-- Add New -->
                    @canany(['user-create'])
                        <a class="btn waves-effect waves-light btn-rounded btn-outline-primary pull-right" href="{{ route('user.create') }}">Add New</a>
                    @endcanany
                </div>
            </div>

            <div class="col-sm-8"></div>
            
            <div class="col-sm-4">
                <div class="col-md-12 align-self-center collapse" id="collapseExample">
                    <div class="customize-input float-right">
                        <form action="{{ route('user.export') }}" method="get">
                            <div class="row">
                                <div class="form-group col-md-6 ">
                                    <select name="slug" class="form-control" required>
                                        <option value="">Select Status</option>
                                        <option value="all">All</option>
                                        <option value="active">Active</option>
                                        <option value="inactive">Inactive</option>
                                        <option value="deleted">Deleted</option>
                                    </select>
                                </div>
                                <div class="form-group col-md-6">
                                    <button class="btn btn-primary" type="submit">Submit</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="container-fluid">
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-body table-responsive" id="datatable" style="text-align: center;">
                        <table class="table table-bordered data-table tables" id="data-table" cellspacing="0" width="100%">                
                            <thead>
                                <tr>
                                    <th>No</th>
                                    <th>Name</th>
                                    <th>Role</th>
                                    <th>Department</th>
                                    <th>Branch</th>
                                    <th>Phone</th>
                                    <th>E-mail</th>
                                    <th>Total Days of joining</th>
                                    <th>Status</th>
                                    <th>Action</th>
                                </tr>
                                <tr class="filterrow">
                                    <th></th>
                                    <th>
                                        <div class="search-box-container datatable-form-filter width_300">
                                            <div class="form-group is-empty">
                                                <input type="text" name="name" value="{{ request()->get('name', '') }}" class="form-control text-capitalize custom_color" autocomplete="off" autofocus tabindex="1">
                                            </div>
                                        </div>
                                    </th>
                                    <th>
                                        <div class="search-box-container datatable-form-filter width_150">
                                            <div class="form-group is-empty">
                                                <input type="text" name="role" value="{{ request()->get('role', '') }}" class="form-control text-capitalize custom_color" autocomplete="off" autofocus tabindex="2">
                                            </div>
                                        </div>
                                    </th>
                                    <th>
                                        <div class="search-box-container datatable-form-filter width_150">
                                            <div class="form-group is-empty">
                                                <input type="text" name="department" value="{{ request()->get('department', '') }}" class="form-control text-capitalize custom_color" autocomplete="off" autofocus tabindex="3">
                                            </div>
                                        </div>
                                    </th>
                                    <th>
                                        <div class="search-box-container datatable-form-filter width_350">
                                            <div class="form-group is-empty">
                                                <input type="text" name="branch" value="{{ request()->get('branch', '') }}" class="form-control text-capitalize custom_color" autocomplete="off" autofocus tabindex="4">
                                            </div>
                                        </div>
                                    </th>
                                    <th>
                                        <div class="search-box-container datatable-form-filter width_150">
                                            <div class="form-group is-empty">
                                                <input type="text" name="contact_number" value="{{ request()->get('contact_number', '') }}" class="form-control text-capitalize custom_color" autocomplete="off" autofocus tabindex="4">
                                            </div>
                                        </div>
                                    </th>
                                    <th>
                                        <div class="search-box-container datatable-form-filter width_250">
                                            <div class="form-group is-empty">
                                                <input type="text" name="email" value="{{ request()->get('email', '') }}" class="form-control text-capitalize custom_color" autocomplete="off" autofocus tabindex="4">
                                            </div>
                                        </div>
                                    </th>
                                    <th></th>
                                    <th></th>
                                    <th></th>
                                </tr>
                            </thead>
                        </table>
                    </div>
                </div>
            </div>

            <!-- Modal -->
            <div class="modal fade" id="exampleModal" role="dialog">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h3 class="modal-title">Import</h3>
                            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>

                        </div>
                        <form action="{{ route('user.import') }}" name="form" id="form" method="post" enctype="multipart/form-data">
                            @csrf
                            <div class="modal-body">
                                <div class="row">
                                    <div class="form-group col-sm-12">
                                        <label for="first_name">Upload File Here</label>
                                        <input type="file" name="file" id="file" class="form-control" placeholder="Plese upload file here" required>
                                        <span class="kt-form__help error file"></span>
                                    </div>
                                </div>
                            </div>
                            <div class="modal-footer">
                                <button type="submit" class="btn btn-default">Submit!</button>
                                <button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="row justify-content-center">
    <div class="col-md-8">
        <div class="card">
        <div class="card-header text-center">
            <h5 class="card-title mb-0">Department Wise</h5>
        </div>
        <div class="card-body">
            <div class="chart-container d-flex justify-content-center">
            <canvas id="pieChart1" width="900" height="250"></canvas>
            </div>
        </div>
        </div>
    </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

    <script>
        $(document).ready(function() {
            $.ajax({
                url: "{{ route('user.get-department-wise-data') }}",
                method: "GET",
                success: function (data) {
                    let labels = data.labels;
                    let counts = data.counts; 
                    
                    if (labels.length && counts.length) {
                        let ctx = document.getElementById('pieChart1').getContext('2d');
                        new Chart(ctx, {
                            type: 'pie',
                            data: {
                                labels: labels,
                                datasets: [{
                                    label: 'Department Wise',
                                    data: counts,
                                    backgroundColor: [
                                        '#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0', '#9966FF', '#FF9F40'
                                    ],
                                    borderWidth: 1
                                }]
                            },
                            options: {
                                responsive: true,
                                plugins: {
                                    legend: {
                                        position: 'top',
                                        labels: {
                                            color: '#fff' // Set legend font color to white
                                        }
                                    },
                                    tooltip: {
                                        callbacks: {
                                            label: function (context) {
                                                const total = context.dataset.data.reduce((a, b) => a + b, 0);
                                                const value = context.raw;
                                                const percentage = ((value / total) * 100).toFixed(2);
                                                return `${context.label}:  (${percentage}%)`;
                                            }
                                        }
                                    },
                                    datalabels: {
                                        formatter: (value, context) => {
                                            const total = context.dataset.data.reduce((a, b) => a + b, 0);
                                            const percentage = ((value / total) * 100).toFixed(2);
                                            return `${context.chart.data.labels}: ${percentage}%`;
                                        },
                                        color: '#fff',
                                        font: {
                                            weight: 'bold',
                                            size: 14
                                        }
                                    }
                                }
                            }
                        });
                    } else {
                        console.log('No data available for the pie chart');
                    }
                },
                error: function (xhr, status, error) {
                    console.error("Failed to fetch data:", error);
                }
            });
        });
    </script>
    <style>
    .chart-container {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100%;
    }

    canvas {
        max-width: 100%;
        max-height: 100%;
    }
    </style>

    <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2.0.0"></script>
@endsection

@section('scripts')
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
<script src="https://cdn.datatables.net/1.13.7/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/js/select2.min.js"></script>
<script type="text/javascript">

    $(document).ready(function() {
        (function(window, $) {
            window.LaravelDataTables = window.LaravelDataTables || {};
            window.LaravelDataTables["dataTableBuilder"] = $("#data-table").DataTable({
                processing: true,
                serverSide: true,
                language: {
                    "info": "_START_ - _END_ of _TOTAL_",
                    "lengthMenu": "_MENU_ ",
                    "infoFiltered": ""
                },
                scrollCollapse: true,
                paging: true,
                searching: false,
                bSortCellsTop : true,
                ajax: {        
            
                    url: '{!! route("user") !!}',
                    data: function (d) {
                        d.name = jQuery(".datatable-form-filter input[name='name']").val();
                        d.role = jQuery(".datatable-form-filter input[name='role']").val();
                        d.department = jQuery(".datatable-form-filter input[name='department']").val();
                        d.branch = jQuery(".datatable-form-filter input[name='branch']").val();
                        d.contact_number = jQuery(".datatable-form-filter input[name='contact_number']").val();
                        d.email = jQuery(".datatable-form-filter input[name='email']").val();
                    },
                    error : function(d) {}
                },
                columns: [
                    {data: 'DT_RowIndex', name: 'DT_RowIndex',class:'text-center DT_RowIndex',title: 'No.', orderable: false, width:100,default: true},
                    {data: 'name', name: 'name',class:'text-center name',title: 'Name', orderable: false,default: true},
                    {data: 'role', name: 'role',class:'text-center role',title: 'Role', orderable: false,default: true},
                    {data: 'department', name: 'department',class:'text-center department',title: 'Department', orderable: false,default: true},
                    {data: 'branch', name: 'branch',class:'text-center branch',title: 'Branch', orderable: false,default: true},
                    {data: 'contact_number', name: 'contact_number',class:'text-center contact_number',title: 'Phone', orderable: false,default: true},
                    {data: 'email', name: 'email',class:'text-center email',title: 'E-mail', orderable: false,default: true},
                    {data: 'days_since_joining', name: 'days_since_joining',class:'text-center days_since_joining',title: 'Total Days of Joining', orderable: false,default: true},
                    {data: 'status', name: 'status',class:'text-center status',title: 'Status', orderable: false,default: true},
                    {data: 'action', name: 'action',title: 'Action', orderable: false, searchable: false, width:50,class:'text-center action_column',default: true}
                ],
                lengthMenu: [
                    [25, 50,100, -1 ],['25', '50','100', 'Show all' ]
                ],
                order: [ [0,'DESC'] ],
                responsive: true,
                colReorder:{
                    enable: false,
                },
                dom: '<"top"f>rt<"bottom"ipl><"clear">',
                fnInitComplete: function(settings, json) {
                    jQuery('table.table input:checkbox').map(function() {
                        if(jQuery(this).prop("checked") != true){
                            var column = table.column( jQuery(this).attr('data-column') );
                            column.visible(false);
                        }
                    });
                },
                pageLength: 25,
            });
        })(window, jQuery);
    });    
    
    function change_status(object) {
        var id = $(object).data("id");
        var status = $(object).data("status");

        if (confirm('Are you sure?')) {
            $.ajax({
                "url": "{!! route('user.change.status') !!}",
                "dataType": "json",
                "type": "POST",
                "data": {
                    id: id,
                    status: status,
                    _token: "{{ csrf_token() }}"
                },
                success: function(response) {
                    if (response.code == 200) {
                        $('#datatable').DataTable().ajax.reload();
                        toastr.success('Status changed successfully', 'Success');
                        location.reload();
                    } else {
                        toastr.error('Failed to change status', 'Error');
                    }
                }
            });
        }
    }


    jQuery('.datatable-form-filter input').on('keyup', function (e) {
        if(jQuery(this).val().length >= 3 || e.keyCode == 13 || !jQuery(this).val()) {
            window.LaravelDataTables["dataTableBuilder"].draw();
            e.preventDefault();
        }
    });

    jQuery('.datatable-form-filter select').on('change', function (e) {
        window.LaravelDataTables["dataTableBuilder"].draw();
        e.preventDefault();
    });

    jQuery('input:checkbox[name="name_sort_asc"],input:checkbox[name="name_sort_desc"]').on('click', function (e) {
        window.LaravelDataTables["dataTableBuilder"].draw();
        e.preventDefault();
    });
</script>
@endsection