@extends('layouts.admin-simple')

@section('title', 'Project Divisions')

@section('breadcrumb')
    <li class="breadcrumb-item">Warehouse</li>
    <li class="breadcrumb-item">Projects</li>
    <li class="breadcrumb-item active">Project Divisions</li>
@endsection

@section('page-title')
    <div class="d-flex justify-content-between align-items-center w-100">
        <div class="page-title-left">
            <h3 class="mb-1">Project Divisions</h3>
            <p class="text-muted mb-0" style="font-size: 13px;">Manage project divisions and organizational structure</p>
        </div>
        <div class="page-actions-right d-flex align-items-center">
            <button type="button" onclick="exportDivisions()" class="btn btn-sm btn-info" title="Export divisions to Excel">
                <i class="material-icons mr-1" style="font-size: 16px;">file_download</i>
                Export
            </button>
        </div>
    </div>
@endsection

@section('content')
    <!-- Statistics Cards -->
    <div class="row mb-4">
        <div class="col-xl-3 col-md-6 mb-4">
            <x-warehouse.stats-card
                title="Total Divisions"
                :value="\App\Models\Warehouse\ProjectDivision::count()"
                icon="corporate_fare"
                color="primary"
                subtitle="All project divisions"
            />
        </div>

        <div class="col-xl-3 col-md-6 mb-4">
            <x-warehouse.stats-card
                title="Active Divisions"
                :value="\App\Models\Warehouse\ProjectDivision::where('status', 'active')->count()"
                icon="check_circle"
                color="success"
                subtitle="Currently active"
            />
        </div>

        <div class="col-xl-3 col-md-6 mb-4">
            <x-warehouse.stats-card
                title="Total Projects"
                :value="\App\Models\Warehouse\Project::count()"
                icon="work"
                color="info"
                subtitle="Across all divisions"
            />
        </div>

        <div class="col-xl-3 col-md-6 mb-4">
            <x-warehouse.stats-card
                title="Avg Projects/Division"
                :value="\App\Models\Warehouse\ProjectDivision::count() > 0 ? round(\App\Models\Warehouse\Project::count() / \App\Models\Warehouse\ProjectDivision::count(), 1) : 0"
                icon="trending_up"
                color="warning"
                subtitle="Project distribution"
            />
        </div>
    </div>

    <!-- Project Divisions Table -->
    <div class="card">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h5 class="mb-0 d-flex align-items-center">
                <i class="material-icons mr-2">list</i>
                Project Divisions List
            </h5>
            <div class="d-flex align-items-center">
                <label class="text-muted mr-2" style="font-size: 14px;">Show:</label>
                <select id="entries-per-page" class="form-control form-control-sm" style="width: auto;">
                    <option value="10">10</option>
                    <option value="25">25</option>
                    <option value="50">50</option>
                    <option value="100">100</option>
                </select>
                <span class="text-muted ml-2" style="font-size: 14px;">entries</span>
            </div>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table id="divisions-table" class="table table-hover">
                    <thead>
                        <tr>
                            <th>Division</th>
                            <th>Code</th>
                            <th>Description</th>
                            <th>Status</th>
                            <th>Projects</th>
                            <th>Created</th>
                            <th class="text-right">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- Data will be populated by DataTables -->
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Add Division Modal -->
    <div class="modal fade" id="addDivisionModal" tabindex="-1" role="dialog" aria-labelledby="addDivisionModalLabel" aria-hidden="true" style="z-index: 999999;">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="addDivisionModalLabel">
                        <i class="material-icons mr-2">corporate_fare</i>
                        Add New Project Division
                    </h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="addDivisionForm">
                        @csrf
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="division_name">Division Name <span class="text-danger">*</span></label>
                                    <input type="text" name="division_name" id="division_name" class="form-control" required>
                                    <div class="invalid-feedback"></div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="division_code">Division Code <span class="text-danger">*</span></label>
                                    <input type="text" name="division_code" id="division_code" class="form-control" required maxlength="10" style="text-transform: uppercase;">
                                    <small class="form-text text-muted">Max 10 characters, will be used for project number prefixes</small>
                                    <div class="invalid-feedback"></div>
                                </div>
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="description">Description</label>
                            <textarea name="description" id="description" class="form-control" rows="3" placeholder="Optional description of the division"></textarea>
                            <div class="invalid-feedback"></div>
                        </div>

                        <div class="form-group">
                            <label for="status">Status <span class="text-danger">*</span></label>
                            <select name="status" id="status" class="form-control" required>
                                <option value="active">Active</option>
                                <option value="inactive">Inactive</option>
                            </select>
                            <div class="invalid-feedback"></div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="button" onclick="saveDivision()" class="btn btn-primary">
                        <i class="material-icons mr-1" style="font-size: 16px;">save</i>
                        Save Division
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Edit Division Modal -->
    <div class="modal fade" id="editDivisionModal" tabindex="-1" role="dialog" aria-labelledby="editDivisionModalLabel" aria-hidden="true" style="z-index: 999999;">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editDivisionModalLabel">
                        <i class="material-icons mr-2">edit</i>
                        Edit Project Division
                    </h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="editDivisionForm">
                        @csrf
                        <input type="hidden" id="edit_division_id" name="division_id">

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="edit_division_name">Division Name <span class="text-danger">*</span></label>
                                    <input type="text" name="division_name" id="edit_division_name" class="form-control" required>
                                    <div class="invalid-feedback"></div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="edit_division_code">Division Code <span class="text-danger">*</span></label>
                                    <input type="text" name="division_code" id="edit_division_code" class="form-control" required maxlength="10" style="text-transform: uppercase;">
                                    <small class="form-text text-muted">Max 10 characters, will be used for project number prefixes</small>
                                    <div class="invalid-feedback"></div>
                                </div>
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="edit_description">Description</label>
                            <textarea name="description" id="edit_description" class="form-control" rows="3" placeholder="Optional description of the division"></textarea>
                            <div class="invalid-feedback"></div>
                        </div>

                        <div class="form-group">
                            <label for="edit_status">Status <span class="text-danger">*</span></label>
                            <select name="status" id="edit_status" class="form-control" required>
                                <option value="active">Active</option>
                                <option value="inactive">Inactive</option>
                            </select>
                            <div class="invalid-feedback"></div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="button" onclick="updateDivision()" class="btn btn-primary">
                        <i class="material-icons mr-1" style="font-size: 16px;">save</i>
                        Update Division
                    </button>
                </div>
            </div>
        </div>
    </div>
@endsection

@push('styles')
    <link href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css" rel="stylesheet" />
    <style>

        .btn-sm {
            padding: 6px 12px;
            font-size: 12px;
            line-height: 1.5;
            border-radius: 4px;
        }

        .btn-sm .material-icons {
            font-size: 16px !important;
        }

        .table th {
            border-top: none;
            font-weight: 600;
            color: #495057;
            background-color: #f8f9fa;
        }

        .table-responsive {
            border-radius: 0.375rem;
        }


        .status-badge {
            display: inline-flex;
            align-items: center;
            padding: 0.25rem 0.75rem;
            font-size: 0.75rem;
            font-weight: 500;
            line-height: 1;
            border-radius: 0.375rem;
        }

        .status-active {
            color: #155724;
            background-color: #d4edda;
            border: 1px solid #c3e6cb;
        }

        .status-inactive {
            color: #721c24;
            background-color: #f8d7da;
            border: 1px solid #f5c6cb;
        }

        .status-primary {
            color: #155724;
            background-color: #cce5ff;
            border: 1px solid #99d3ff;
        }

        .status-success {
            color: #155724;
            background-color: #d4edda;
            border: 1px solid #c3e6cb;
        }

        .status-warning {
            color: #856404;
            background-color: #fff3cd;
            border: 1px solid #ffeaa7;
        }

        .status-danger {
            color: #721c24;
            background-color: #f8d7da;
            border: 1px solid #f5c6cb;
        }

        .status-info {
            color: #0c5460;
            background-color: #d1ecf1;
            border: 1px solid #bee5eb;
        }

        .status-secondary {
            color: #383d41;
            background-color: #e2e3e5;
            border: 1px solid #d6d8db;
        }

        /* Modal styles */
        .modal,
        #addDivisionModal,
        #editDivisionModal {
            z-index: 999999 !important;
            position: fixed !important;
        }

        .modal-backdrop,
        .modal-backdrop.fade,
        .modal-backdrop.show {
            z-index: 999998 !important;
            position: fixed !important;
        }

        .modal-dialog {
            z-index: 1000000 !important;
            position: relative !important;
        }

        .modal-content {
            z-index: 1000001 !important;
            position: relative !important;
        }

        .modal.show,
        .modal.fade.show {
            display: block !important;
            z-index: 999999 !important;
            opacity: 1 !important;
        }

        .modal * {
            position: relative;
        }

        body.modal-open {
            overflow: hidden !important;
        }

        @keyframes spin {
            from { transform: rotate(0deg); }
            to { transform: rotate(360deg); }
        }

        /* SweetAlert2 custom button styling */
        .swal2-actions {
            gap: 12px !important;
        }

        .swal2-actions .btn {
            min-height: 38px !important;
            height: 38px !important;
            display: inline-flex !important;
            align-items: center !important;
            justify-content: center !important;
        }

        .swal2-actions .btn:focus,
        .swal2-actions .btn:focus-visible {
            outline: none !important;
            box-shadow: none !important;
        }

        .swal2-actions .btn:active {
            transform: scale(0.98);
        }
    </style>
@endpush

@push('scripts')
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script src="https://cdn.datatables.net/1.13.7/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.7/js/dataTables.bootstrap4.min.js"></script>

    <script>
        let divisionsTable;

        $(document).ready(function() {
            initializeDataTable();

            // Entries per page change handler
            $('#entries-per-page').change(function() {
                divisionsTable.page.len($(this).val()).draw();
            });

            // Auto-uppercase division code
            $('#division_code, #edit_division_code').on('input', function() {
                $(this).val($(this).val().toUpperCase());
            });
        });

        function initializeDataTable() {
            divisionsTable = $('#divisions-table').DataTable({
                processing: true,
                serverSide: true,
                ajax: {
                    url: '{{ route("warehouse.project-divisions.index") }}'
                },
                columns: [
                    {
                        data: 'division_name',
                        name: 'division_name',
                        render: function(data, type, row) {
                            return `
                                <div class="d-flex align-items-center">
                                    <div class="mr-3">
                                        <div class="bg-primary text-white d-flex align-items-center justify-content-center rounded-circle" style="width: 40px; height: 40px;">
                                            <span class="font-weight-bold" style="font-size: 14px;">${data.charAt(0).toUpperCase()}</span>
                                        </div>
                                    </div>
                                    <div>
                                        <div class="font-weight-medium">${data}</div>
                                        <small class="text-muted">${row.division_code}</small>
                                    </div>
                                </div>
                            `;
                        }
                    },
                    {
                        data: 'division_code',
                        name: 'division_code',
                        render: function(data) {
                            return `<span class="status-badge status-secondary">${data}</span>`;
                        }
                    },
                    {
                        data: 'description',
                        name: 'description',
                        render: function(data) {
                            return data || '<span class="text-muted">No description</span>';
                        }
                    },
                    {
                        data: 'status',
                        name: 'status',
                        render: function(data) {
                            const statusClass = data === 'active' ? 'status-success' : 'status-danger';
                            return `<span class="status-badge ${statusClass}">${data.charAt(0).toUpperCase() + data.slice(1)}</span>`;
                        }
                    },
                    {
                        data: 'projects_count',
                        name: 'projects_count',
                        render: function(data) {
                            return `<span class="status-badge status-info">${data} projects</span>`;
                        }
                    },
                    {
                        data: 'created_at',
                        name: 'created_at',
                        render: function(data) {
                            return new Date(data).toLocaleDateString();
                        }
                    },
                    {
                        data: null,
                        name: 'actions',
                        orderable: false,
                        searchable: false,
                        render: function(data) {
                            return `
                                <div class="btn-group" role="group">
                                    @can('warehouse.project-divisions.edit')
                                    <button onclick="editDivision(${data.id})" class="btn btn-sm btn-outline-success" title="Edit">
                                        <i class="material-icons" style="font-size: 16px;">edit</i>
                                    </button>
                                    @endcan
                                    @can('warehouse.project-divisions.delete')
                                    <button onclick="deleteDivision(${data.id}, '${data.division_name}')" class="btn btn-sm btn-outline-danger" title="Delete">
                                        <i class="material-icons" style="font-size: 16px;">delete</i>
                                    </button>
                                    @endcan
                                </div>
                            `;
                        }
                    }
                ],
                order: [[5, 'desc']],
                pageLength: 25,
                lengthMenu: [[10, 25, 50, 100], [10, 25, 50, 100]],
                language: {
                    processing: '<div class="text-center"><div class="spinner-border text-primary" role="status"><span class="sr-only">Loading...</span></div></div>',
                    emptyTable: 'No project divisions found',
                    zeroRecords: 'No matching divisions found'
                },
                drawCallback: function(settings) {
                    $('#entries-per-page').val(settings._iDisplayLength);
                }
            });
        }

        function exportDivisions() {
            const btn = event.target.closest('button');
            const originalHtml = btn.innerHTML;
            btn.innerHTML = '<i class="material-icons mr-1" style="font-size: 16px; animation: spin 1s linear infinite;">sync</i>Exporting...';
            btn.disabled = true;

            setTimeout(() => {
                btn.innerHTML = originalHtml;
                btn.disabled = false;
                showAlert('Export functionality will be implemented', 'info');
            }, 1000);
        }

        function showAddDivisionModal() {
            // Clear form and validation errors
            $('#addDivisionForm')[0].reset();
            clearValidationErrors();

            // Force very high z-index before showing
            $('#addDivisionModal').css({
                'z-index': 999999,
                'position': 'fixed',
                'display': 'block'
            });

            // Show modal
            $('#addDivisionModal').modal({
                backdrop: true,
                keyboard: true,
                show: true
            });

            // Aggressively force z-index after modal is shown
            $('#addDivisionModal').on('shown.bs.modal', function() {
                $(this).css({
                    'z-index': 999999,
                    'position': 'fixed'
                });
                $('.modal-backdrop').css({
                    'z-index': 999998,
                    'position': 'fixed'
                });
                $('.modal-dialog').css({
                    'z-index': 1000000,
                    'position': 'relative'
                });
                $('.modal-content').css({
                    'z-index': 1000001,
                    'position': 'relative'
                });

                // Move modal to body if it's not already there
                if (!$('#addDivisionModal').parent().is('body')) {
                    $('#addDivisionModal').appendTo('body');
                }
            });
        }

        function saveDivision() {
            const form = $('#addDivisionForm')[0];
            const formData = new FormData(form);

            clearValidationErrors();

            const saveBtn = $('button[onclick="saveDivision()"]');
            const originalHtml = saveBtn.html();
            saveBtn.prop('disabled', true);
            saveBtn.html('<i class="material-icons mr-1" style="font-size: 16px; animation: spin 1s linear infinite;">sync</i>Saving...');

            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });

            $.ajax({
                url: '{{ route("warehouse.project-divisions.store") }}',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function(response) {
                    if (response.success) {
                        $('#addDivisionModal').modal('hide');
                        divisionsTable.draw();
                        showAlert('Project division created successfully!', 'success');
                    } else {
                        showAlert(response.message || 'Error creating division', 'error');
                    }
                },
                error: function(xhr) {
                    if (xhr.status === 422) {
                        const errors = xhr.responseJSON.errors;
                        displayValidationErrors(errors);
                    } else {
                        showAlert('Error creating division. Please try again.', 'error');
                    }
                },
                complete: function() {
                    saveBtn.prop('disabled', false);
                    saveBtn.html(originalHtml);
                }
            });
        }

        function editDivision(id) {
            // Fetch division data and populate edit modal
            $.get(`{{ url('warehouse/project-divisions') }}/${id}`)
                .done(function(data) {
                    $('#edit_division_id').val(data.id);
                    $('#edit_division_name').val(data.division_name);
                    $('#edit_division_code').val(data.division_code);
                    $('#edit_description').val(data.description);
                    $('#edit_status').val(data.status);

                    clearValidationErrors();
                    $('#editDivisionModal').modal('show');
                })
                .fail(function() {
                    showAlert('Error loading division data', 'error');
                });
        }

        function updateDivision() {
            const id = $('#edit_division_id').val();
            const form = $('#editDivisionForm')[0];
            const formData = new FormData(form);

            clearValidationErrors();

            const updateBtn = $('button[onclick="updateDivision()"]');
            const originalHtml = updateBtn.html();
            updateBtn.prop('disabled', true);
            updateBtn.html('<i class="material-icons mr-1" style="font-size: 16px; animation: spin 1s linear infinite;">sync</i>Updating...');

            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });

            $.ajax({
                url: `{{ url('warehouse/project-divisions') }}/${id}`,
                type: 'PUT',
                data: formData,
                processData: false,
                contentType: false,
                success: function(response) {
                    if (response.success) {
                        $('#editDivisionModal').modal('hide');
                        divisionsTable.draw();
                        showAlert('Project division updated successfully!', 'success');
                    } else {
                        showAlert(response.message || 'Error updating division', 'error');
                    }
                },
                error: function(xhr) {
                    if (xhr.status === 422) {
                        const errors = xhr.responseJSON.errors;
                        displayValidationErrors(errors);
                    } else {
                        showAlert('Error updating division. Please try again.', 'error');
                    }
                },
                complete: function() {
                    updateBtn.prop('disabled', false);
                    updateBtn.html(originalHtml);
                }
            });
        }

        function deleteDivision(id, divisionName) {
            Swal.fire({
                title: 'Delete Division?',
                html: `Are you sure you want to delete <strong>"${divisionName}"</strong>?<br><small class="text-muted">This action cannot be undone.</small>`,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#dc3545',
                cancelButtonColor: '#6c757d',
                confirmButtonText: '<i class="material-icons" style="font-size: 16px; vertical-align: middle;">delete</i> Yes, Delete',
                cancelButtonText: '<i class="material-icons" style="font-size: 16px; vertical-align: middle;">cancel</i> Cancel',
                reverseButtons: true,
                focusCancel: true,
                customClass: {
                    confirmButton: 'btn btn-danger px-4',
                    cancelButton: 'btn btn-secondary px-4'
                },
                buttonsStyling: false
            }).then((result) => {
                if (result.isConfirmed) {
                    // Show loading state
                    Swal.fire({
                        title: 'Deleting...',
                        text: 'Please wait while we delete the division.',
                        icon: 'info',
                        allowOutsideClick: false,
                        allowEscapeKey: false,
                        showConfirmButton: false,
                        didOpen: () => {
                            Swal.showLoading();
                        }
                    });

                    $.ajaxSetup({
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        }
                    });

                    $.ajax({
                        url: `{{ url('warehouse/project-divisions') }}/${id}`,
                        type: 'DELETE',
                        success: function(response) {
                            if (response.success) {
                                Swal.fire({
                                    title: 'Deleted!',
                                    text: 'Project division deleted successfully',
                                    icon: 'success',
                                    timer: 2000,
                                    showConfirmButton: false
                                });
                                divisionsTable.draw();
                            } else {
                                Swal.fire({
                                    title: 'Error!',
                                    text: response.message || 'Failed to delete division',
                                    icon: 'error',
                                    confirmButtonText: 'OK',
                                    customClass: {
                                        confirmButton: 'btn btn-primary'
                                    },
                                    buttonsStyling: false
                                });
                            }
                        },
                        error: function(xhr) {
                            Swal.fire({
                                title: 'Error!',
                                text: 'Error deleting division. Please try again.',
                                icon: 'error',
                                confirmButtonText: 'OK',
                                customClass: {
                                    confirmButton: 'btn btn-primary'
                                },
                                buttonsStyling: false
                            });
                        }
                    });
                }
            });
        }

        function clearValidationErrors() {
            $('.form-control').removeClass('is-invalid');
            $('.invalid-feedback').text('');
        }

        function displayValidationErrors(errors) {
            $.each(errors, function(field, messages) {
                const input = $(`[name="${field}"]`);
                input.addClass('is-invalid');
                input.siblings('.invalid-feedback').text(messages[0]);
            });
        }

        function showAlert(message, type) {
            const alertClass = type === 'success' ? 'alert-success' : 'alert-danger';
            const alert = `
                <div class="alert ${alertClass} alert-dismissible fade show position-fixed" style="top: 20px; right: 20px; z-index: 9999;">
                    ${message}
                    <button type="button" class="close" data-dismiss="alert">&times;</button>
                </div>
            `;
            $('body').append(alert);
            setTimeout(() => $('.alert').alert('close'), 5000);
        }
    </script>
@endpush