@extends('layouts.dashboard.superadminapp')

@section('title', 'Manage RFQ Types')

<style>
    .btn {
        width: auto;
    }
</style>

@section('content')
<div class="container-fluid">
    <x-layout.page-header title="UEPL / RFQ Types" icon="database" iconColor="secondary" />

    <div class="card shadow mb-4">
        <div class="card-header d-flex justify-content-between align-items-center gap-3">
            <span class="fw-bold"> </span>
            <button class="btn btn-primary btn-sm" id="addRfqTypeBtn" style="width: auto;" title="Add RFQ Types">
                <i class="fas fa-plus-square"></i>
            </button>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-bordered table-hover text-dark w-100" id="rfqTypeTable">
                    <thead class="table-light">
                        <tr class="text-center align-middle">
                            <th>ID</th>
                            <th>RFQ Type</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- AJAX Loaded -->
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Add/Edit Modal -->
    <div class="modal fade" id="rfqTypeModal" tabindex="-1" aria-labelledby="rfqTypeModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <form id="rfqTypeForm">
                @csrf
                <input type="hidden" name="rfqtype_id" id="rfqtype_id">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="rfqTypeModalLabel">Add RFQ Type</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <div class="mb-3">
                            <label for="rfq_type" class="form-label">RFQ Type</label>
                            <input type="text" name="rfq_type" id="rfq_type" class="form-control" required>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="submit" class="btn btn-primary" id="saveRfqTypeBtn">Save</button>
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- Delete Confirmation Modal -->
    <div class="modal fade" id="deleteRfqTypeModal" tabindex="-1" aria-labelledby="deleteRfqTypeLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Delete RFQ Type</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    Are you sure you want to delete this RFQ Type?
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-danger" id="confirmDeleteBtn">Delete</button>
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@section('scripts')
<script>
document.addEventListener('DOMContentLoaded', function() {
    const rfqTypeModalEl = document.getElementById('rfqTypeModal');
    const rfqTypeModal = new bootstrap.Modal(rfqTypeModalEl);
    const deleteRfqTypeModalEl = document.getElementById('deleteRfqTypeModal');
    const deleteRfqTypeModal = new bootstrap.Modal(deleteRfqTypeModalEl);

    let deleteId = null;

    function loadRfqTypes() {
        fetch("{{ route('superadmin.rfqtype.list') }}")
        .then(res => res.json())
        .then(data => {
            const tbody = document.querySelector('#rfqTypeTable tbody');
            tbody.innerHTML = '';
            data.data.forEach((rfqType, index) => {
                tbody.innerHTML += `
                    <tr class="text-center align-middle">
                        <td>${rfqType.id}</td>
                        <td>${rfqType.rfqtype}</td>
                        <td>
                            <button class="btn btn-sm btn-info editRfqTypeBtn" data-id="${rfqType.id}" title="Edit">
                                <i class="fas fa-edit"></i> 
                            </button>
                            <button class="btn btn-sm btn-danger deleteRfqTypeBtn" data-id="${rfqType.id}" title="Delete">
                                <i class="fas fa-trash-alt"></i>
                            </button>
                        </td>
                    </tr>
                `;
            });
        })
        .catch(() => alert('Failed to load RFQ types.'));
    }

    loadRfqTypes();

    document.getElementById('addRfqTypeBtn').addEventListener('click', () => {
        document.getElementById('rfqTypeForm').reset();
        document.getElementById('rfqtype_id').value = '';
        document.getElementById('rfqTypeModalLabel').textContent = 'Add RFQ Type';
        rfqTypeModal.show();
    });

    document.getElementById('rfqTypeTable').addEventListener('click', function(e) {
        if(e.target.closest('.editRfqTypeBtn')) {
            const btn = e.target.closest('.editRfqTypeBtn');
            const id = btn.dataset.id;

            fetch(`/superadmin/rfqtypes/${id}`)
            .then(res => {
                if (!res.ok) throw new Error('Network response was not ok');
                return res.json();
            })
            .then(data => {
                document.getElementById('rfqtype_id').value = data.id;
                document.getElementById('rfq_type').value = data.rfqtype;
                document.getElementById('rfqTypeModalLabel').textContent = 'Edit RFQ Type';
                rfqTypeModal.show();
            })
            .catch(err => alert('Failed to load data: ' + err.message));
        }

        if(e.target.closest('.deleteRfqTypeBtn')) {
            deleteId = e.target.closest('.deleteRfqTypeBtn').dataset.id;
            deleteRfqTypeModal.show();
        }
    });

    document.getElementById('rfqTypeForm').addEventListener('submit', function(e) {
        e.preventDefault();

        let id = document.getElementById('rfqtype_id').value;
        let url = id ? `/superadmin/rfqtypes/update/${id}` : "{{ route('superadmin.rfqtype.store') }}";

        let formData = new FormData(this);
        if(id) formData.append('_method', 'PUT');

        fetch(url, {
            method: 'POST',
            headers: {
                'X-CSRF-TOKEN': "{{ csrf_token() }}"
            },
            body: formData,
        })
        .then(res => res.json())
        .then(data => {
            if(data.success) {
                rfqTypeModal.hide();
                loadRfqTypes();
                alert(data.message);
            } else {
                alert(data.message || 'Something went wrong!');
            }
        })
        .catch(() => alert('Error communicating with server.'));
    });

    document.getElementById('confirmDeleteBtn').addEventListener('click', function() {
        if (!deleteId) return;

        fetch(`/superadmin/rfqtypes/delete/${deleteId}`, {
            method: 'DELETE',
            headers: {
                'X-CSRF-TOKEN': "{{ csrf_token() }}"
            },
        })
        .then(res => res.json())
        .then(data => {
            if(data.success) {
                deleteRfqTypeModal.hide();
                loadRfqTypes();
                alert(data.message);
            } else {
                alert(data.message || 'Delete failed!');
            }
        })
        .catch(() => alert('Error communicating with server.'));
    });
});
</script>
@endsection
