@extends('layouts.app')

@push('css')
<style>
    #orgChartContainer { 
        width: 100%; 
        height: 600px; 
        border: 1px solid #e2e8f0; 
        background: #f8fafc; 
        border-radius: 12px; 
        overflow: auto; 
    }
    /* OrgChart Light Mode */
    .orgchart { background: transparent; }
    .orgchart .node .title { background-color: #3a86ff !important; color: #fff !important; border-radius: 8px 8px 0 0; }
    .orgchart .node .content { background-color: #ffffff !important; color: #1e293b !important; border: 1px solid #e2e8f0 !important; border-radius: 0 0 8px 8px; }
    .orgchart .lines .down-line { background-color: #cbd5e1 !important; }
    .orgchart .lines .right-line { border-right: 1px solid #cbd5e1 !important; }
    .orgchart .lines .left-line { border-left: 1px solid #cbd5e1 !important; }
    .orgchart .lines .top-line { border-top: 1px solid #cbd5e1 !important; }
</style>
<!-- OrgChart CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/orgchart/3.1.1/css/jquery.orgchart.min.css">
@endpush

@section('title', 'Employee Management')

@section('content')
<div class="row">
    <div class="col-12">
        <!-- Summary Widgets -->
        <div class="row mb-4">
            <div class="col-md-3">
                <div class="info-box premium-info-box bg-premium-primary shadow-sm">
                    <span class="info-box-icon"><i class="fa-solid fa-users"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text text-uppercase">Total Strength</span>
                        <span class="info-box-number h5 mb-0" id="widget_total_staff">0</span>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="info-box premium-info-box bg-premium-warning shadow-sm">
                    <span class="info-box-icon"><i class="fa-solid fa-user-clock"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text text-uppercase">On Probation</span>
                        <span class="info-box-number h5 mb-0" id="widget_on_probation">0</span>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="info-box premium-info-box bg-premium-success shadow-sm">
                    <span class="info-box-icon"><i class="fa-solid fa-user-plus"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text text-uppercase">New Joiners</span>
                        <span class="info-box-number h5 mb-0" id="widget_new_joiners">0</span>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="info-box premium-info-box bg-premium-info shadow-sm">
                    <span class="info-box-icon"><i class="fa-solid fa-sitemap"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text text-uppercase">Departments</span>
                        <span class="info-box-number h5 mb-0" id="widget_departments">0</span>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="col-md-12">

    <div class="card card-primary card-outline">
        <div class="card-header">
            <h3 class="card-title"><i class="fas fa-filter mr-2"></i>Filter Employees</h3>
        </div>
        <div class="card-body">
            <form id="filterForm" class="row">
                <div class="col-md-5">
                    <div class="form-group">
                        <label>Joined From</label>
                        <input type="date" id="joined_date_from" class="form-control">
                    </div>
                </div>
                <div class="col-md-5">
                    <div class="form-group">
                        <label>Joined To</label>
                        <input type="date" id="joined_date_to" class="form-control">
                    </div>
                </div>
                <div class="col-md-2" style="margin-top: 32px;">
                    <button type="button" id="applyFilter" class="btn btn-primary">
                        <i class="fas fa-filter mr-1"></i> Filter
                    </button>
                    <button type="button" id="resetFilter" class="btn btn-default" title="Reset">
                        <i class="fas fa-undo"></i>
                    </button>
                </div>
            </form>
        </div>
    </div>

    <div class="card card-outline card-tabs mt-4">
        <div class="card-header p-0 pt-1 border-bottom-0">
            <ul class="nav nav-tabs" id="employeeTabs" role="tablist">
                <li class="nav-item">
                    <a class="nav-link active" id="list-tab" data-toggle="tab" href="#list" role="tab" aria-controls="list" aria-selected="true">
                        <i class="fas fa-list mr-1"></i> Employee List
                    </a>
                </li>
                @if(auth()->user()->canAccess('employees.org_chart'))
                <li class="nav-item">
                    <a class="nav-link" id="chart-tab" data-toggle="tab" href="#chart" role="tab" aria-controls="chart" aria-selected="false">
                        <i class="fas fa-sitemap mr-1"></i> Organisation Chart
                    </a>
                </li>
                @endif
                @if(auth()->user()->canAccess('employees.create'))
                 <li class="nav-item ml-auto mr-2 pt-1">
                     <a href="{{ route('employees.create') }}" class="btn btn-xs btn-primary">
                        <i class="fas fa-plus mr-1"></i> Add Employee
                    </a>
                </li>
                @endif
            </ul>
        </div>
        <div class="card-body">
            <div class="tab-content" id="employeeTabsContent">
                <div class="tab-pane fade show active" id="list" role="tabpanel" aria-labelledby="list-tab">
                    <div class="table-responsive">
                        <table class="table table-hover table-striped table-bordered w-100" id="employeesTable">
                            <thead>
                                <tr>
                                    <th>Photo</th>
                                    <th>Name</th>
                                    <th>Email</th>
                                    <th>Designation</th>
                                    <th>Manager</th>
                                    <th style="width: 150px;">Action</th>
                                </tr>
                            </thead>
                        </table>
                    </div>
                </div>
                <div class="tab-pane fade" id="chart" role="tabpanel" aria-labelledby="chart-tab">
                    <div id="orgChartContainer"></div>
                </div>
            </div>
        </div>
    </div>
</div>
</div>
@endsection

@push('scripts')
<script src="https://cdnjs.cloudflare.com/ajax/libs/orgchart/3.1.1/js/jquery.orgchart.min.js"></script>
<script>
$(function() {
    // DataTable
    // DataTable
    var table = $('#employeesTable').DataTable({
        processing: true,
        serverSide: true,
        ajax: {
            url: "{{ route('employees.data') }}",
            data: function (d) {
                d.joined_date_from = $('#joined_date_from').val();
                d.joined_date_to = $('#joined_date_to').val();
            }
        },
        columns: [
            {data: 'photo', name: 'photo', orderable: false, searchable: false},
            {data: 'name', name: 'name'},
            {data: 'email', name: 'email'},
            {data: 'designation', name: 'designation'},
            {data: 'manager', name: 'manager'},
            {data: 'action', name: 'action', orderable: false, searchable: false}
        ],
        dom: "<'row'<'col-sm-6'l><'col-sm-6'f>>" +
             "<'row'<'col-sm-12'tr>>" +
             "<'row'<'col-sm-5'i><'col-sm-7'p>>",
        scrollX: true,
        language: {
            search: "_INPUT_",
            searchPlaceholder: "Search employees...",
            paginate: {
                previous: '<i class="fas fa-chevron-left"></i>',
                next: '<i class="fas fa-chevron-right"></i>'
            }
        },
        drawCallback: function(settings) {
            $('.dataTables_paginate > .pagination').addClass('pagination-sm');
            
            // Update widgets from AJAX response
            if (settings.json && settings.json.aggregates) {
                const agg = settings.json.aggregates;
                $('#widget_total_staff').text(agg.total_staff);
                $('#widget_on_probation').text(agg.on_probation);
                $('#widget_new_joiners').text(agg.new_joiners);
                $('#widget_departments').text(agg.departments);
            }
        }
    });

    $('#applyFilter').click(function(){ table.draw(); });
    $('#resetFilter').click(function(){
        $('#filterForm')[0].reset();
        table.draw();
    });

    // Delete
    $('body').on('click', '.delete-employee', function() {
        var id = $(this).data('id');
        Swal.fire({
            title: 'Are you sure?',
            text: "This will also delete the associated user account!",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            cancelButtonColor: '#6c757d',
            confirmButtonText: 'Yes, delete it!',
            customClass: {
                confirmButton: 'btn btn-danger',
                cancelButton: 'btn btn-secondary'
            }
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: "{{ url('employees') }}/" + id,
                    type: 'DELETE',
                    data: { _token: "{{ csrf_token() }}" },
                    success: function() {
                        Swal.fire({
                            title: 'Deleted!',
                            icon: 'success',
                            toast: true,
                            position: 'top-end',
                            showConfirmButton: false,
                            timer: 3000
                        });
                        table.draw();
                        if($('#chart').hasClass('active')) loadOrgChart();
                    }
                });
            }
        });
    });

    // Org Chart
    function loadOrgChart() {
        $('#orgChartContainer').empty();
        $.get("{{ route('employees.org-chart') }}", function(data) {
            if(data.length > 0) {
                // Find root (no pid)
                let root = data.find(e => !e.pid);
                if(!root) root = data[0]; // Fallback

                function buildTree(item) {
                    let obj = { 
                        'name': item.name, 
                        'title': item.title,
                        'image': item.img 
                    };
                    let children = data.filter(e => e.pid == item.id);
                    if(children.length > 0) {
                        obj.children = children.map(c => buildTree(c));
                    }
                    return obj;
                }

                let datascource = buildTree(root);

                $('#orgChartContainer').orgchart({
                    'data' : datascource,
                    'nodeContent': 'title',
                    'nodeId': 'id',
                    'pan': true,
                    'zoom': true
                });
            }
        });
    }

    $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
        if ($(e.target).attr('href') === '#chart') {
            loadOrgChart();
        }
    });
});
</script>
@endpush
