@extends('layouts.dashboard.superadminapp')

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

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

@section('content')
<div class="container">
    <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 / Product 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>

    <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="addProductTypeBtn" title="Add Product Type">
                <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="productTypeTable">
                    <thead class="table-light">
                        <tr class="text-center align-middle">
                            <th>ID</th>
                            <th>Product Type</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- AJAX Loaded -->
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Add/Edit Modal -->
    <div class="modal fade" id="productTypeModal" tabindex="-1" aria-labelledby="productTypeModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <form id="productTypeForm">
                @csrf
                <input type="hidden" name="producttype_id" id="producttype_id">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="productTypeModalLabel">Add Product 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="product_type" class="form-label">Product Type</label>
                            <input type="text" name="product_type" id="product_type" class="form-control" required>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="submit" class="btn btn-primary">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="deleteProductTypeModal" tabindex="-1" aria-labelledby="deleteProductTypeLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Delete Product 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 Product 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 productTypeModal = new bootstrap.Modal(document.getElementById('productTypeModal'));
    const deleteProductTypeModal = new bootstrap.Modal(document.getElementById('deleteProductTypeModal'));
    let deleteId = null;

    function loadProductTypes() {
        fetch("{{ route('superadmin.producttype.list') }}")
        .then(res => res.json())
        .then(data => {
            const tbody = document.querySelector('#productTypeTable tbody');
            tbody.innerHTML = '';
            data.data.forEach(type => {
                tbody.innerHTML += `
                    <tr class="text-center align-middle">
                        <td>${type.id}</td>
                        <td>${type.name}</td>
                        <td>
                            <button class="btn btn-sm btn-info editProductTypeBtn" data-id="${type.id}" title="Edit">
                                <i class="fas fa-edit"></i>
                            </button>
                            <button class="btn btn-sm btn-danger deleteProductTypeBtn" data-id="${type.id}" title="Delete">
                                <i class="fas fa-trash-alt"></i> 
                            </button>
                        </td>
                    </tr>
                `;
            });
        })
        .catch(() => alert('Failed to load product types.'));
    }

    loadProductTypes();

    document.getElementById('addProductTypeBtn').addEventListener('click', () => {
        document.getElementById('productTypeForm').reset();
        document.getElementById('producttype_id').value = '';
        document.getElementById('productTypeModalLabel').textContent = 'Add Product Type';
        productTypeModal.show();
    });

    document.getElementById('productTypeTable').addEventListener('click', function(e) {
        if (e.target.closest('.editProductTypeBtn')) {
            const id = e.target.closest('.editProductTypeBtn').dataset.id;
            fetch(`/superadmin/producttypes/${id}`)
            .then(res => res.json())
            .then(data => {
                document.getElementById('producttype_id').value = data.id;
                document.getElementById('product_type').value = data.name;
                document.getElementById('productTypeModalLabel').textContent = 'Edit Product Type';
                productTypeModal.show();
            })
            .catch(err => alert('Failed to load data.'));
        }

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

    document.getElementById('productTypeForm').addEventListener('submit', function(e) {
        e.preventDefault();
        let id = document.getElementById('producttype_id').value;
        let url = id ? `/superadmin/producttypes/update/${id}` : "{{ route('superadmin.producttype.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) {
                productTypeModal.hide();
                loadProductTypes();
                alert(data.message);
            } else {
                alert(data.message || 'Something went wrong!');
            }
        })
        .catch(() => alert('Server error.'));
    });

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

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