@extends('layouts.dashboard.adminapp')

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

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

@section('content')
<div class="container-fluid">
    <x-layout.page-header title="UEPL / Account 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="addAccountTypeBtn" style="width: auto;" title="Add Account 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="accountTypeTable">
                    <thead class="table-light">
                        <tr class="text-center align-middle">
                            <th>ID</th>
                            <th>Account Type</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- AJAX Loaded -->
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Add/Edit Modal -->
    <div class="modal fade" id="accountTypeModal" tabindex="-1" aria-labelledby="accountTypeModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <form id="accountTypeForm">
                @csrf
                <input type="hidden" name="accounttype_id" id="accounttype_id">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="accountTypeModalLabel">Add Account 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="account_type" class="form-label">Account Type</label>
                            <input type="text" name="account_type" id="account_type" class="form-control" required>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="submit" class="btn btn-primary" id="saveAccountTypeBtn">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="deleteAccountTypeModal" tabindex="-1" aria-labelledby="deleteAccountTypeLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Delete Account 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 Account 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 accountTypeModalEl = document.getElementById('accountTypeModal');
    const accountTypeModal = new bootstrap.Modal(accountTypeModalEl);
    const deleteAccountTypeModalEl = document.getElementById('deleteAccountTypeModal');
    const deleteAccountTypeModal = new bootstrap.Modal(deleteAccountTypeModalEl);

    let deleteId = null;

    // Load account types into the table
    function loadAccountTypes() {
        fetch("{{ route('admin.accounttype.list') }}")
        .then(res => res.json())
        .then(data => {
            const tbody = document.querySelector('#accountTypeTable tbody');
            tbody.innerHTML = '';
            data.data.forEach((accountType, index) => {
                tbody.innerHTML += `
                    <tr class="text-center align-middle">
                        <td>${accountType.id}</td>
                        <td>${accountType.accounttype}</td>
                        <td>
                            <button class="btn btn-sm btn-info editAccountTypeBtn" data-id="${accountType.id}" title="Edit">
                                <i class="fas fa-edit"></i>
                            </button>
                            <button class="btn btn-sm btn-danger deleteAccountTypeBtn" data-id="${accountType.id}" title="Delete">
                                <i class="fas fa-trash-alt"></i>
                            </button>
                        </td>
                    </tr>
                `;
            });
        })
        .catch(() => alert('Failed to load account types.'));
    }

    loadAccountTypes();

    // Show modal for adding new account type
    document.getElementById('addAccountTypeBtn').addEventListener('click', () => {
        document.getElementById('accountTypeForm').reset();
        document.getElementById('accounttype_id').value = '';
        document.getElementById('accountTypeModalLabel').textContent = 'Add Account Type';
        accountTypeModal.show();
    });

    // Edit button click (event delegation)
    document.getElementById('accountTypeTable').addEventListener('click', function(e) {
        if(e.target.closest('.editAccountTypeBtn')) {
            const btn = e.target.closest('.editAccountTypeBtn');
            const id = btn.dataset.id;

            fetch(`/admin/accounttypes/${id}`)
            .then(res => {
                if (!res.ok) throw new Error('Network response was not ok');
                return res.json();
            })
            .then(data => {
                document.getElementById('accounttype_id').value = data.id;
                document.getElementById('account_type').value = data.accounttype;
                document.getElementById('accountTypeModalLabel').textContent = 'Edit Account Type';
                accountTypeModal.show();
            })
            .catch(err => alert('Failed to load data: ' + err.message));
        }

        // Delete button click
        if(e.target.closest('.deleteAccountTypeBtn')) {
            deleteId = e.target.closest('.deleteAccountTypeBtn').dataset.id;
            deleteAccountTypeModal.show();
        }
    });

    // Submit add/edit form
    document.getElementById('accountTypeForm').addEventListener('submit', function(e) {
        e.preventDefault();

        let id = document.getElementById('accounttype_id').value;
        let url = id ? `/admin/accounttypes/update/${id}` : "{{ route('admin.accounttype.store') }}";

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

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

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

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