@extends('layouts.dashboard.superadminapp')

@section('title', 'Company Types')

@section('content')
    <!-- Page Heading -->
    <div class="bg-white p-2 d-sm-flex align-items-center justify-content-between mb-4">
        <h1 class="h5 mb-0 text-gray-800">UEPL / Company Types</h1>
        <div class="display-date">
            <span id="day">day</span>, <span id="daynum">00</span> <span id="month">month</span> <span id="year">0000</span>
        </div>
        <div class="display-time"></div>
    </div>

    <!-- Summary Card -->
    <div class="row mb-4">
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card border-left-primary shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">Total Company Types</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800" id="totalCount">0</div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-building fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Card Table -->
    <div class="card shadow mb-4">
        <div class="card-header d-flex justify-content-between align-items-center">
            <span class="fw-bold"><i class="fas fa-table me-2"></i> Company Types Data</span>
            <button class="btn btn-primary btn-sm" id="addCompanyTypeBtn" title="Add Company Type">
                <i class="fa fa-plus-square" aria-hidden="true"></i> Add Company Type
            </button>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-bordered table-hover text-dark w-100" id="companyTypeTable">
                    <thead class="table-light">
                        <tr class="text-center align-middle">
                            <th width="10%">Sl.No</th>
                            <th width="60%">Company Type</th>
                            <th width="30%">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- Loaded by AJAX -->
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Add/Edit Modal -->
    <div class="modal fade" id="companyTypeModal" tabindex="-1" aria-labelledby="companyTypeModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <form id="companyTypeForm">
                @csrf
                <input type="hidden" name="companytype_id" id="companytype_id">
                <div class="modal-content border-0 shadow">
                    <!-- Header -->
                    <div class="modal-header py-2 bg-primary">
                        <h6 class="modal-title text-white mb-0" id="companyTypeModalLabel">
                            <i class="fas fa-plus-circle mr-2" id="modalIcon"></i>Add Company Type
                        </h6>
                        <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                            <span>&times;</span>
                        </button>
                    </div>

                    <div class="modal-body py-3 px-3">
                        <!-- Error Alert -->
                        <div id="formErrors" class="alert alert-danger py-2 d-none mb-2" role="alert">
                            <small><i class="fas fa-exclamation-triangle mr-1"></i><strong>Error:</strong></small>
                            <ul class="mb-0 pl-3 small" id="errorList"></ul>
                        </div>

                        <div class="form-group mb-0">
                            <label class="small font-weight-bold mb-1">Company Type <span class="text-danger">*</span></label>
                            <input name="company_type" id="company_type" class="form-control form-control-sm" placeholder="Enter company type" required>
                        </div>
                    </div>

                    <!-- Footer -->
                    <div class="modal-footer py-2 bg-light">
                        <button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary btn-sm" id="saveBtn">
                            <span class="spinner-border spinner-border-sm d-none" role="status"></span>
                            <span class="btn-text">Save</span>
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- Delete Confirmation Modal -->
    <div class="modal fade" id="deleteCompanyTypeModal" tabindex="-1" aria-labelledby="deleteCompanyTypeLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header bg-danger text-white py-2">
                    <h6 class="modal-title mb-0"><i class="fas fa-exclamation-triangle mr-2"></i>Delete Company Type</h6>
                    <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                        <span>&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <p class="mb-1">Are you sure you want to delete this company type?</p>
                    <p class="mb-0"><strong id="deleteItemName"></strong></p>
                    <small class="text-muted">This action cannot be undone.</small>
                </div>
                <div class="modal-footer py-2">
                    <button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-danger btn-sm" id="confirmDeleteBtn">
                        <span class="spinner-border spinner-border-sm d-none" role="status"></span>
                        <span class="btn-text">Delete</span>
                    </button>
                </div>
            </div>
        </div>
    </div>
@endsection

@section('scripts')
<script>
$(document).ready(function() {
    var companyTypesData = [];

    // Load company types function
    function loadCompanyTypes() {
        // Destroy DataTable first if it exists
        if ($.fn.DataTable.isDataTable('#companyTypeTable')) {
            $('#companyTypeTable').DataTable().clear().destroy();
        }
        $('#companyTypeTable tbody').empty();

        $.get('{{ route('superadmin.companytype.list') }}', function(res) {
            companyTypesData = res.data;
            let rows = '';

            $.each(res.data, function(i, item) {
                rows += `<tr class="text-center align-middle">
                    <td>${i + 1}</td>
                    <td class="text-left">${item.companytype}</td>
                    <td>
                        <div class="btn-group" role="group">
                            <button class="btn btn-sm btn-info editBtn" title="Edit"
                                data-id="${item.id}"
                                data-companytype="${item.companytype}">
                                <i class="fas fa-edit"></i>
                            </button>
                            <button class="btn btn-sm btn-danger deleteBtn" title="Delete"
                                data-id="${item.id}"
                                data-companytype="${item.companytype}">
                                <i class="fas fa-trash-alt"></i>
                            </button>
                        </div>
                    </td>
                </tr>`;
            });

            $('#companyTypeTable tbody').html(rows);
            updateSummaryCard();

            // Initialize DataTable
            $('#companyTypeTable').DataTable({
                pageLength: 10,
                lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                order: [],
                columnDefs: [
                    { orderable: false, targets: [2] }
                ]
            });
        }).fail(function(err) {
            console.error('Failed to load company types:', err);
            showToast('error', 'Failed to load data. Please refresh the page.');
        });
    }

    // Initial load
    loadCompanyTypes();

    // Update summary card
    function updateSummaryCard() {
        $('#totalCount').text(companyTypesData.length);
    }

    // Add button click - show modal
    $('#addCompanyTypeBtn').on('click', function() {
        $('#companyTypeForm')[0].reset();
        $('#companytype_id').val('');
        $('#formErrors').addClass('d-none');
        $('#modalIcon').removeClass('fa-edit').addClass('fa-plus-circle');
        $('#companyTypeModalLabel').html('<i class="fas fa-plus-circle mr-2" id="modalIcon"></i>Add Company Type');
        $('#companyTypeModal').modal('show');
    });

    // Edit button click - populate form and show modal
    $('#companyTypeTable').on('click', '.editBtn', function() {
        $('#companyTypeForm')[0].reset();
        $('#formErrors').addClass('d-none');

        $('#companytype_id').val($(this).data('id'));
        $('#company_type').val($(this).data('companytype'));

        $('#modalIcon').removeClass('fa-plus-circle').addClass('fa-edit');
        $('#companyTypeModalLabel').html('<i class="fas fa-edit mr-2" id="modalIcon"></i>Edit Company Type');
        $('#companyTypeModal').modal('show');
    });

    // Form submission (Add/Update)
    $('#companyTypeForm').submit(function(e) {
        e.preventDefault();

        var $btn = $('#saveBtn');
        var $spinner = $btn.find('.spinner-border');
        var $text = $btn.find('.btn-text');

        // Disable button and show spinner
        $btn.prop('disabled', true);
        $spinner.removeClass('d-none');
        $text.text('Saving...');

        var id = $('#companytype_id').val();
        var url = id
            ? "{{ url('superadmin/companytypes/update') }}/" + id
            : "{{ route('superadmin.companytype.store') }}";

        $.ajax({
            url: url,
            type: 'POST',
            data: $(this).serialize(),
            success: function(res) {
                $('#companyTypeModal').modal('hide');
                loadCompanyTypes();
                showToast('success', res.message || 'Company Type saved successfully!');
            },
            error: function(err) {
                var errors = err.responseJSON?.errors || {};
                var message = err.responseJSON?.message || 'An error occurred';

                if (Object.keys(errors).length > 0) {
                    var errorHtml = '';
                    $.each(errors, function(field, messages) {
                        $.each(messages, function(i, msg) {
                            errorHtml += '<li>' + msg + '</li>';
                        });
                    });
                    $('#errorList').html(errorHtml);
                    $('#formErrors').removeClass('d-none');
                } else {
                    showToast('error', message);
                }
            },
            complete: function() {
                $btn.prop('disabled', false);
                $spinner.addClass('d-none');
                $text.text('Save');
            }
        });
    });

    // Delete button click - show confirmation modal
    var deleteId = null;
    $('#companyTypeTable').on('click', '.deleteBtn', function() {
        deleteId = $(this).data('id');
        $('#deleteItemName').text($(this).data('companytype'));
        $('#deleteCompanyTypeModal').modal('show');
    });

    // Confirm delete
    $('#confirmDeleteBtn').on('click', function() {
        if (!deleteId) return;

        var $btn = $(this);
        var $spinner = $btn.find('.spinner-border');
        var $text = $btn.find('.btn-text');

        $btn.prop('disabled', true);
        $spinner.removeClass('d-none');
        $text.text('Deleting...');

        $.ajax({
            url: "{{ url('superadmin/companytypes/delete') }}/" + deleteId,
            type: 'DELETE',
            data: { '_token': '{{ csrf_token() }}' },
            success: function(res) {
                $('#deleteCompanyTypeModal').modal('hide');
                loadCompanyTypes();
                showToast('success', res.message || 'Company Type deleted successfully!');
            },
            error: function(err) {
                showToast('error', err.responseJSON?.message || 'Failed to delete');
            },
            complete: function() {
                $btn.prop('disabled', false);
                $spinner.addClass('d-none');
                $text.text('Delete');
                deleteId = null;
            }
        });
    });

    // Toast notification helper
    function showToast(type, message) {
        var bgClass = type === 'success' ? 'bg-success' : 'bg-danger';
        var icon = type === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle';

        var toastHtml = `
            <div class="toast ${bgClass} text-white" role="alert" aria-live="assertive" aria-atomic="true" data-delay="3000" style="position: fixed; top: 20px; right: 20px; z-index: 9999; min-width: 250px;">
                <div class="toast-body d-flex align-items-center">
                    <i class="fas ${icon} mr-2"></i>
                    <span>${message}</span>
                    <button type="button" class="ml-auto close text-white" data-dismiss="toast" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
            </div>
        `;

        var $toast = $(toastHtml);
        $('body').append($toast);
        $toast.toast('show');

        $toast.on('hidden.bs.toast', function() {
            $(this).remove();
        });
    }
});
</script>
@endsection
