@extends('layouts.dashboard.adminapp')

@section('title', 'Manage Conversion 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 / Conversion Processes</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"><i class="fas fa-cogs me-2"></i> Conversion Processes</span>
            <button class="btn btn-primary btn-sm" id="addProcessBtn">
                <i class="fas fa-plus"></i> Add Process
            </button>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-bordered table-hover text-dark w-100" id="processTable">
                    <thead class="table-light">
                        <tr class="text-center align-middle">
                            <th>ID</th>
                            <th>Process Name</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- AJAX Loaded -->
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Add/Edit Modal -->
    <div class="modal fade" id="processModal" tabindex="-1" aria-labelledby="processModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <form id="processForm">
                @csrf
                <input type="hidden" name="process_id" id="process_id">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="processModalLabel">Add Conversion Process</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="process_name" class="form-label">Process Name</label>
                            <input type="text" name="process_name" id="process_name" class="form-control" required>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="submit" class="btn btn-primary" id="saveProcessBtn">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="deleteProcessModal" tabindex="-1" aria-labelledby="deleteProcessLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Delete Conversion Process</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 Conversion Process?
                </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 processModal = new bootstrap.Modal(document.getElementById('processModal'));
    const deleteProcessModal = new bootstrap.Modal(document.getElementById('deleteProcessModal'));
    let deleteId = null;

    function loadProcesses() {
        fetch("{{ route('admin.conversionprocess.list') }}")
        .then(res => {
            if (!res.ok) throw new Error('Network error');
            return res.json();
        })
        .then(data => {
            const tbody = document.querySelector('#processTable tbody');  // fixed selector
            tbody.innerHTML = '';
            data.data.forEach(process => {
                tbody.innerHTML += `
                    <tr>
                        <td>${process.id}</td>
                        <td>${process.process_name}</td>
                        <td>
                            <button class="btn btn-sm btn-info editBtn" data-id="${process.id}">Edit</button>
                            <button class="btn btn-sm btn-danger deleteBtn" data-id="${process.id}">Delete</button>
                        </td>
                    </tr>
                `;
            });
        })
        .catch(() => alert('Failed to load conversion processes.'));
    }

    loadProcesses();

    document.getElementById('addProcessBtn').addEventListener('click', () => {
        document.getElementById('processForm').reset();
        document.getElementById('process_id').value = '';
        document.getElementById('processModalLabel').textContent = 'Add Conversion Process';
        processModal.show();
    });

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

        if (editBtn) {
            console.log('Edit clicked, id:', editBtn.dataset.id);
            const id = editBtn.dataset.id;
            fetch(`/admin/conversionprocesses/${id}`)
                .then(res => res.json())
                .then(data => {
                    document.getElementById('process_id').value = data.id;
                    document.getElementById('process_name').value = data.process_name;
                    document.getElementById('processModalLabel').textContent = 'Edit Conversion Process';
                    processModal.show();
                });
        }

        if (deleteBtn) {
            console.log('Delete clicked, id:', deleteBtn.dataset.id);
            deleteId = deleteBtn.dataset.id;
            deleteProcessModal.show();
        }
    });

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

        const url = id
            ? `/admin/conversionprocesses/update/${id}`
            : "{{ route('admin.conversionprocess.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);
            } else {
                alert('Failed to save process.');
            }
        })
        .catch(() => alert('Failed to save process.'));
    });

    document.getElementById('confirmDeleteBtn').addEventListener('click', function () {
        if (!deleteId) return;
        fetch(`/admin/conversionprocesses/delete/${deleteId}`, {
            method: 'DELETE',
            headers: { 'X-CSRF-TOKEN': "{{ csrf_token() }}" },
        })
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                deleteProcessModal.hide();
                loadProcesses();
                alert(data.message);
            } else {
                alert('Failed to delete process.');
            }
        })
        .catch(() => alert('Failed to delete process.'));
    });
});
</script>
@endsection

