@extends('layouts.dashboard.superadminapp')

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

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

@section('content')
<div class="container-fluid">
    <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 / Account 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="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>Sl No</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" id="closeAndResetAccountTypeModalIcon">
                            <span>×</span>
                        </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" id="closeAndResetAccountTypeModalBtn">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" id="deleteAccountTypeModalIcon"></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" id="deleteAccountTypeModalBtn">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('superadmin.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>${index + 1}</td> <!-- Serial number instead of ID -->
                        <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();
    });
    
    // Added by Samar for accountType Modal Close Icon
    document.getElementById('closeAndResetAccountTypeModalIcon').addEventListener('click', () => {
        document.getElementById('accountTypeForm').reset();
        document.getElementById('accounttype_id').value = '';
        document.getElementById('accountTypeModalLabel').textContent = 'Add Account Type';
        accountTypeModal.hide();
    });
    
    // Added by Samar for accountType Modal Close btn
    document.getElementById('closeAndResetAccountTypeModalBtn').addEventListener('click', () => {
        document.getElementById('accountTypeForm').reset();
        document.getElementById('accounttype_id').value = '';
        document.getElementById('accountTypeModalLabel').textContent = 'Add Account Type';
        accountTypeModal.hide();
    });

    // 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("{{ route('superadmin.accounttype.single', ':id') }}".replace(':id', 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 ? "{{ route('superadmin.accounttype.update', ':id') }}".replace(':id', id) : "{{ route('superadmin.accounttype.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(async res => {
            const data = await res.json();
    
            if (res.ok && data.success) {
                accountTypeModal.hide();
                loadAccountTypes();
                alert(data.message);
            } else if (res.status === 422) {
                const firstField = Object.keys(data.errors)[0];
                const firstError = data.errors[firstField][0];
                alert(firstError);
            } 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("{{ route('superadmin.accounttype.delete', ':id') }}".replace(':id', 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.'));
    });
    
    // Added by Samar for deleteAccountTypeModal Close Icon
    document.getElementById('deleteAccountTypeModalIcon').addEventListener('click', () => {
        deleteAccountTypeModal.hide();
    });
    
    // Added by Samar for deleteAccountTypeModal btn
    document.getElementById('deleteAccountTypeModalBtn').addEventListener('click', () => {
        deleteAccountTypeModal.hide();
    });
});


</script>
@endsection
