@extends('layouts.dashboard.adminapp')

@section('title', 'Manage Raw Materials')

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

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

    <div class="card shadow mb-4">
        <div class="card-header d-flex justify-content-between align-items-center gap-3" title="Add Raw Materials">
            <span class="fw-bold"></span>
            <button class="btn btn-primary btn-sm" id="addMaterialBtn">
                <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="rawMaterialTable">
                    <thead class="table-light">
                        <tr class="text-center align-middle">
                            <th>ID</th>
                            <th>Raw Material</th>
                            <th>ISO Specification</th>
                            <th>Material Density</th>
                            <th>Mechanical Properties</th>
                            <th>Chemical Properties</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- AJAX Loaded -->
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Add/Edit Modal -->
    <div class="modal fade" id="addRawMaterialModal" tabindex="-1" role="dialog"
        aria-labelledby="addRawMaterialLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <form id="addRawMaterialForm">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="addRawMaterialLabel">Add New Raw Material</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"
                            style="width:auto">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <input type="hidden" name="material_id" id="material_id">
                    <div class="modal-body">
                        <div class="mb-2">
                            <label>Raw Material Name *</label>
                            <input type="text" name="name" class="form-control" required>
                        </div>
                        <div class="mb-2">
                            <label>ISO Specification</label>
                            <input type="text" name="iso_specification" class="form-control">
                        </div>
                        <div class="mb-2">
                            <label>Material Density *</label>
                            <input type="text" name="density" class="form-control" required>
                        </div>
                        <div class="mb-2">
                            <label>Mechanical Properties</label>
                            <input type="text" name="mechanical_properties" class="form-control">
                        </div>
                        <div class="mb-2">
                            <label>Chemical Properties</label>
                            <input type="text" name="chemical_properties" class="form-control">
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="submit" class="btn btn-success">Add</button>
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- Delete Confirmation Modal -->
    <div class="modal fade" id="deleteRawMaterialModal" tabindex="-1" aria-labelledby="deleteRawMaterialLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Delete Raw Material</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 Raw Material?
                </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 addRawMaterialModal = new bootstrap.Modal(document.getElementById('addRawMaterialModal'));
        const deleteRawMaterialModal = new bootstrap.Modal(document.getElementById('deleteRawMaterialModal'));
        let deleteId = null;

        function loadRawMaterials() {
            fetch("{{ route('admin.rawmaterial.list') }}")
            .then(res => res.json())
            .then(data => {
                const tbody = document.querySelector('#rawMaterialTable tbody');
                tbody.innerHTML = '';
                data.data.forEach(item => {
                    tbody.innerHTML += `
                        <tr class="text-center align-middle">
                            <td>${item.id}</td>
                            <td>${item.name}</td>
                            <td>${item.iso_specification}</td>
                            <td>${item.density || '-'}</td>
                            <td>${item.mechanical_properties || '-'}</td>
                            <td>${item.chemical_properties || '-'}</td>
                            <td>
                                <button class="btn btn-sm btn-info editMaterialBtn" data-id="${item.id}" title=""Edit>
                                    <i class="fas fa-edit"></i> 
                                </button>
                                <button class="btn btn-sm btn-danger deleteMaterialBtn" data-id="${item.id}" title="Delete">
                                    <i class="fas fa-trash-alt"></i> 
                                </button>
                            </td>
                        </tr>
                    `;
                });
            })
            .catch(() => alert('Failed to load raw materials.'));
        }

        loadRawMaterials();

        document.getElementById('addMaterialBtn').addEventListener('click', () => {
            document.getElementById('addRawMaterialForm').reset();
            document.getElementById('material_id').value = '';
            document.getElementById('addRawMaterialLabel').textContent = 'Add New Raw Material';
            addRawMaterialModal.show();
        });

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

            const id = document.getElementById('material_id').value;
            const url = id ? `/admin/rawmaterials/update/${id}` : "{{ route('admin.rawmaterial.store') }}";

            const 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) {
                    addRawMaterialModal.hide();
                    loadRawMaterials();
                    alert(data.message);
                } else {
                    alert(data.message || 'Something went wrong.');
                }
            })
            .catch(() => alert('Server error.'));
        });

        document.getElementById('rawMaterialTable').addEventListener('click', function (e) {
            // Handle Edit
            if (e.target.closest('.editMaterialBtn')) {
                const id = e.target.closest('.editMaterialBtn').dataset.id;

                fetch(`/admin/rawmaterials/${id}`)
                    .then(res => res.json())
                    .then(data => {
                        document.getElementById('material_id').value = data.id;
                        document.querySelector('[name="name"]').value = data.name;
                        document.querySelector('[name="iso_specification"]').value = data.iso_specification;
                        document.querySelector('[name="density"]').value = data.density || '';
                        document.querySelector('[name="mechanical_properties"]').value = data.mechanical_properties || '';
                        document.querySelector('[name="chemical_properties"]').value = data.chemical_properties || '';

                        document.getElementById('addRawMaterialLabel').textContent = 'Edit Raw Material';
                        addRawMaterialModal.show();
                    })
                    .catch(() => alert('Failed to load data.'));
            }

            // Handle Delete
            if (e.target.closest('.deleteMaterialBtn')) {
                deleteId = e.target.closest('.deleteMaterialBtn').dataset.id;
                deleteRawMaterialModal.show();
            }
        });

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

            fetch(`/admin/rawmaterials/delete/${deleteId}`, {
                method: 'DELETE',
                headers: {
                    'X-CSRF-TOKEN': "{{ csrf_token() }}"
                },
            })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    deleteRawMaterialModal.hide();
                    loadRawMaterials();
                    alert(data.message);
                } else {
                    alert(data.message || 'Delete failed.');
                }
            })
            .catch(() => alert('Error deleting material.'));
        });
    });
</script>

@endsection
