@extends('layouts.dashboard.adminapp')

@section('title', 'Manage Processes')
<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">
        <div class="card-header d-flex justify-content-between align-items-center gap-3">
            <span class="fw-bold"><i class="fas fa-table me-2"></i> Product Types</span>
            <button class="btn btn-primary btn-sm" id="addProcessBtn">
                <i class="fas fa-plus"></i> Add Process
            </button>
        </div>
        <div class="card-body">
            <table class="table table-bordered" id="processTable">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Product Type</th>
                        <th>Process Name</th>
                        <th>Order</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody><!-- Loaded via JS --></tbody>
            </table>
        </div>
    </div>

    <!-- Modal -->
    <div class="modal fade" id="processModal" tabindex="-1">
        <div class="modal-dialog">
            <form id="processForm">
                @csrf
                <input type="hidden" id="process_id" name="process_id">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">Add/Edit Process</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="mb-3">
                            <label>Product Type</label>
                            <select class="form-select" name="product_type_id" id="product_type_id" required>
                                @foreach($productTypes as $type)
                                    <option value="{{ $type->id }}">{{ $type->name }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="mb-3">
                            <label>Process Name</label>
                            <input type="text" class="form-control" name="name" id="name" required>
                        </div>
                        <div class="mb-3">
                            <label>Order</label>
                            <input type="number" class="form-control" name="order" id="order" required>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button class="btn btn-primary" type="submit">Save</button>
                        <button class="btn btn-secondary" type="button" data-bs-dismiss="modal">Cancel</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>
@endsection

@section('scripts')
<script>
document.addEventListener('DOMContentLoaded', function () {
    const processModal = new bootstrap.Modal(document.getElementById('processModal'));
    const form = document.getElementById('processForm');
    const tableBody = document.querySelector('#processTable tbody');
    let deleteId = null;

    // ✅ Updated to call new API route
    function loadProcesses() {
        fetch("{{ route('admin.process.api') }}")
            .then(res => res.json())
            .then(data => {
                tableBody.innerHTML = '';
                data.data.forEach(proc => {
                    tableBody.innerHTML += `
                        <tr>
                            <td>${proc.id}</td>
                            <td>${proc.product_type?.name || ''}</td>
                            <td>${proc.name}</td>
                            <td>${proc.order}</td>
                            <td>
                                <button class="btn btn-sm btn-info editBtn" data-id="${proc.id}">Edit</button>
                                <button class="btn btn-sm btn-danger deleteBtn" data-id="${proc.id}">Delete</button>
                            </td>
                        </tr>
                    `;
                });
            });
    }

    loadProcesses();

    document.getElementById('addProcessBtn').addEventListener('click', () => {
        form.reset();
        document.getElementById('process_id').value = '';
        processModal.show();
    });

    form.addEventListener('submit', function (e) {
        e.preventDefault();
        const id = document.getElementById('process_id').value;
        const formData = new FormData(this);
        if (id) formData.append('_method', 'PUT');

        // ✅ Use route helper or string paths consistent with route definitions
        const url = id 
            ? `/admin/processes/update/${id}` 
            : "{{ route('admin.process.store') }}";

        fetch(url, {
            method: 'POST',
            headers: {
                'X-CSRF-TOKEN': "{{ csrf_token() }}"
            },
            body: formData
        })
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                processModal.hide();
                loadProcesses();
                alert(data.message);
            }
        });
    });

    tableBody.addEventListener('click', function (e) {
        const editBtn = e.target.closest('.editBtn');
        const deleteBtn = e.target.closest('.deleteBtn');

        if (editBtn) {
            const id = editBtn.dataset.id;
            fetch(`/admin/processes/${id}`)
                .then(res => res.json())
                .then(data => {
                    document.getElementById('process_id').value = data.id;
                    document.getElementById('name').value = data.name;
                    document.getElementById('order').value = data.order;
                    document.getElementById('product_type_id').value = data.product_type_id;
                    processModal.show();
                });
        }

        if (deleteBtn) {
            deleteId = deleteBtn.dataset.id;
            if (confirm('Are you sure to delete?')) {
                fetch(`/admin/processes/delete/${deleteId}`, {
                    method: 'DELETE',
                    headers: {
                        'X-CSRF-TOKEN': "{{ csrf_token() }}"
                    }
                })
                .then(res => res.json())
                .then(data => {
                    if (data.success) {
                        loadProcesses();
                        alert(data.message);
                    }
                });
            }
        }
    });
});
</script>
@endsection
