<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Chart of Accounts - Accounting</title>
    
    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome 6 -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- DataTables -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/dataTables.bootstrap5.min.css">
    <!-- SweetAlert2 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
            background: #f5f7fb;
        }

        /* Navbar */
        .navbar {
            background: white;
            padding: 0.75rem 2rem;
            box-shadow: 0 2px 10px rgba(0,0,0,0.03);
        }

        .navbar-brand {
            font-weight: 600;
            color: #2d3748;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .brand-icon {
            background: #4361ee;
            color: white;
            width: 35px;
            height: 35px;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1rem;
        }

        .nav-link {
            color: #64748b !important;
            font-weight: 500;
            padding: 0.5rem 1.2rem !important;
            margin: 0 0.2rem;
            border-radius: 8px;
            transition: all 0.2s;
        }

        .nav-link:hover, .nav-link.active {
            background: #f1f5f9;
            color: #4361ee !important;
        }

        .nav-link i {
            margin-right: 8px;
            font-size: 0.9rem;
        }

        .user-avatar {
            width: 38px;
            height: 38px;
            background: #e2e8f0;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            color: #475569;
        }

        /* Main Container */
        .main-container {
            padding: 2rem;
            max-width: 1400px;
            margin: 0 auto;
        }

        /* Page Header */
        .page-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 2rem;
        }

        .page-header h1 {
            font-size: 1.8rem;
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 0.3rem;
        }

        .page-header p {
            color: #64748b;
        }

        .btn-primary {
            background: #4361ee;
            border: none;
            padding: 0.6rem 1.5rem;
            border-radius: 10px;
            font-weight: 500;
            display: flex;
            align-items: center;
            gap: 8px;
            transition: all 0.2s;
        }

        .btn-primary:hover {
            background: #3651d4;
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(67, 97, 238, 0.2);
        }

        /* Stats Cards */
        .stats-row {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 1.5rem;
            margin-bottom: 2rem;
        }

        .stat-card {
            background: white;
            border-radius: 16px;
            padding: 1.5rem;
            box-shadow: 0 4px 15px rgba(0,0,0,0.02);
            transition: transform 0.2s;
            border: 1px solid rgba(0,0,0,0.02);
        }

        .stat-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 10px 25px rgba(0,0,0,0.05);
        }

        .stat-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1rem;
        }

        .stat-label {
            color: #64748b;
            font-size: 0.9rem;
            font-weight: 500;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .stat-icon {
            width: 45px;
            height: 45px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.2rem;
        }

        .stat-icon.purple { background: #e9efff; color: #4361ee; }
        .stat-icon.blue { background: #e3f7ec; color: #10b981; }
        .stat-icon.green { background: #fff2e0; color: #f97316; }
        .stat-icon.orange { background: #fee9e9; color: #ef4444; }

        .stat-value {
            font-size: 1.8rem;
            font-weight: 700;
            color: #1e293b;
            margin-bottom: 0.2rem;
        }

        /* Card */
        .card {
            background: white;
            border-radius: 16px;
            border: none;
            box-shadow: 0 4px 15px rgba(0,0,0,0.02);
            overflow: hidden;
        }

        .card-header {
            background: white;
            border-bottom: 1px solid #f1f5f9;
            padding: 1.2rem 1.5rem;
        }

        .card-header h5 {
            font-weight: 600;
            color: #1e293b;
            margin: 0;
        }

        .card-body {
            padding: 1.5rem;
        }

        /* Table */
        .table {
            margin: 0;
        }

        .table thead th {
            background: #f8fafc;
            border-bottom: 2px solid #e2e8f0;
            color: #475569;
            font-weight: 600;
            font-size: 0.9rem;
            padding: 1rem;
        }

        .table tbody td {
            padding: 1rem;
            vertical-align: middle;
            border-bottom: 1px solid #f1f5f9;
            color: #1e293b;
        }

        .table tbody tr:hover {
            background: #f8fafc;
        }

        .account-code {
            font-weight: 600;
            color: #4361ee;
            cursor: pointer;
        }

        .account-code:hover {
            text-decoration: underline;
        }

        .account-name {
            font-weight: 500;
        }

        .account-level-0 td:first-child { padding-left: 1rem !important; }
        .account-level-1 td:first-child { padding-left: 2.5rem !important; }
        .account-level-2 td:first-child { padding-left: 4rem !important; }
        .account-level-3 td:first-child { padding-left: 5.5rem !important; }
        .account-level-4 td:first-child { padding-left: 7rem !important; }

        .badge-type {
            padding: 0.3rem 0.8rem;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: 500;
        }

        .badge-type.P { background: #e3f7ec; color: #10b981; }
        .badge-type.H { background: #e9efff; color: #4361ee; }

        .badge-status {
            padding: 0.3rem 0.8rem;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: 500;
        }

        .badge-status.active { background: #e3f7ec; color: #10b981; }
        .badge-status.inactive { background: #f1f5f9; color: #64748b; }

        .action-btns {
            display: flex;
            gap: 5px;
        }

        .btn-icon {
            width: 32px;
            height: 32px;
            padding: 0;
            border-radius: 8px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            border: 1px solid #e2e8f0;
            background: white;
            color: #64748b;
            transition: all 0.2s;
            cursor: pointer;
        }

        .btn-icon:hover {
            background: #f1f5f9;
            border-color: #4361ee;
        }

        .btn-icon.info:hover { color: #4361ee; border-color: #4361ee; }
        .btn-icon.edit:hover { color: #f97316; border-color: #f97316; }
        .btn-icon.delete:hover { color: #ef4444; border-color: #ef4444; }

        /* Modal */
        .modal-content {
            border: none;
            border-radius: 16px;
            overflow: hidden;
        }

        .modal-header {
            background: #4361ee;
            color: white;
            border: none;
            padding: 1.2rem 1.5rem;
        }

        .modal-header .btn-close {
            filter: brightness(0) invert(1);
        }

        .modal-body {
            padding: 1.5rem;
        }

        .modal-footer {
            border-top: 1px solid #f1f5f9;
            padding: 1.2rem 1.5rem;
        }

        .form-label {
            font-weight: 500;
            color: #475569;
            margin-bottom: 0.3rem;
        }

        .form-control, .form-select {
            border: 1px solid #e2e8f0;
            border-radius: 10px;
            padding: 0.6rem 1rem;
            transition: all 0.2s;
        }

        .form-control:focus, .form-select:focus {
            border-color: #4361ee;
            box-shadow: 0 0 0 3px rgba(67, 97, 238, 0.1);
        }

        .form-check-input:checked {
            background-color: #4361ee;
            border-color: #4361ee;
        }

        /* Detail View */
        .detail-item {
            background: #f8fafc;
            border-radius: 10px;
            padding: 1rem;
            margin-bottom: 0.8rem;
        }

        .detail-label {
            color: #64748b;
            font-size: 0.85rem;
            margin-bottom: 0.3rem;
        }

        .detail-value {
            font-weight: 600;
            color: #1e293b;
            font-size: 1rem;
        }

        .detail-value.large {
            font-size: 1.5rem;
            color: #4361ee;
        }

        /* Responsive */
        @media (max-width: 992px) {
            .stats-row {
                grid-template-columns: repeat(2, 1fr);
            }
        }

        @media (max-width: 768px) {
            .main-container {
                padding: 1rem;
            }
            
            .page-header {
                flex-direction: column;
                gap: 1rem;
                text-align: center;
            }
            
            .stats-row {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <!-- Navbar -->
    <nav class="navbar">
        <div class="container-fluid">
            <a class="navbar-brand" href="/accounting/dashboard">
                <div class="brand-icon">
                    <i class="fas fa-calculator"></i>
                </div>
                <span>{{ hotelName() }} ACCOUNTING</span>
            </a>

            <div class="d-flex align-items-center gap-4">
                <div class="d-flex">
                    <a href="/accounting/dashboard" class="nav-link {{ request()->is('accounting/dashboard') ? 'active' : '' }}">
                        <i class="fas fa-home"></i>Dashboard
                    </a>
                    <a href="/accounting/chart-of-accounts" class="nav-link {{ request()->is('accounting/chart-of-accounts') ? 'active' : '' }}">
                        <i class="fas fa-book"></i>Accounts
                    </a>
                    <a href="/accounting/journal-entries" class="nav-link {{ request()->is('accounting/journal-entries*') ? 'active' : '' }}">
                        <i class="fas fa-receipt"></i>Journal
                    </a>
                    <a href="/accounting/budgets" class="nav-link {{ request()->is('accounting/budgets') ? 'active' : '' }}">
                        <i class="fas fa-chart-pie"></i>Budgets
                    </a>
                    <a href="/contacts/vendors" class="nav-link {{ request()->is('contacts/vendors*') ? 'active' : '' }}">
                        <i class="fas fa-truck"></i>Vendors
                    </a>
                    <div class="dropdown d-inline">
                        <a href="#" class="nav-link dropdown-toggle" data-bs-toggle="dropdown">
                            <i class="fas fa-file-alt"></i>Reports
                        </a>
                        <ul class="dropdown-menu">
                            <li><a class="dropdown-item" href="/accounting/reports/trial-balance">Trial Balance</a></li>
                            <li><a class="dropdown-item" href="/accounting/reports/profit-loss">Profit & Loss</a></li>
                            <li><a class="dropdown-item" href="/accounting/reports/balance-sheet">Balance Sheet</a></li>
                            <li><a class="dropdown-item" href="/accounting/reports/general-ledger">General Ledger</a></li>
                        </ul>
                    </div>
                </div>
                <div class="user-avatar">
                    <span>{{ substr(Auth::user()->name ?? 'U', 0, 1) }}</span>
                </div>
            </div>
        </div>
    </nav>

    <!-- Main Container -->
    <div class="main-container">
        <!-- Page Header -->
        <div class="page-header">
            <div>
                <div class="d-flex align-items-center gap-3 mb-2">
                    <a href="{{ route('accounting.dashboard') }}" class="btn btn-sm btn-outline-secondary">
                        <i class="fas fa-arrow-left"></i>
                    </a>
                    <h1 class="mb-0">Chart of Accounts</h1>
                </div>
                <p>Manage your hotel's chart of accounts</p>
            </div>
            <button class="btn btn-primary" onclick="openAccountModal()">
                <i class="fas fa-plus"></i>
                <span>New Account</span>
            </button>
        </div>

        <!-- Stats Cards -->
        <div class="stats-row">
            <div class="stat-card">
                <div class="stat-header">
                    <span class="stat-label">Total Accounts</span>
                    <div class="stat-icon purple">
                        <i class="fas fa-folder"></i>
                    </div>
                </div>
                <div class="stat-value">{{ $stats['total_accounts'] ?? 0 }}</div>
            </div>

            <div class="stat-card">
                <div class="stat-header">
                    <span class="stat-label">Posting Accounts</span>
                    <div class="stat-icon blue">
                        <i class="fas fa-pen"></i>
                    </div>
                </div>
                <div class="stat-value">{{ $stats['posting_accounts'] ?? 0 }}</div>
            </div>

            <div class="stat-card">
                <div class="stat-header">
                    <span class="stat-label">Header Accounts</span>
                    <div class="stat-icon green">
                        <i class="fas fa-folder-open"></i>
                    </div>
                </div>
                <div class="stat-value">{{ $stats['header_accounts'] ?? 0 }}</div>
            </div>

            <div class="stat-card">
                <div class="stat-header">
                    <span class="stat-label">Active Accounts</span>
                    <div class="stat-icon orange">
                        <i class="fas fa-check-circle"></i>
                    </div>
                </div>
                <div class="stat-value">{{ $stats['active_accounts'] ?? 0 }}</div>
            </div>
        </div>

        <!-- Accounts Card -->
        <div class="card">
            <div class="card-header">
                <h5><i class="fas fa-list me-2" style="color: #4361ee;"></i>Account List</h5>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table" id="accountsTable">
                        <thead>
                            <tr>
                                <th>Code</th>
                                <th>Name</th>
                                <th>Type</th>
                                <th>Category</th>
                                <th>Balance</th>
                                <th>Status</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach($accountTree ?? [] as $node)
                                @include('accounting.partials.account-tree-row', ['node' => $node, 'level' => 0])
                            @endforeach
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- Account Modal (Create/Edit) -->
    <div class="modal fade" id="accountModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="accountModalTitle">
                        <i class="fas fa-plus-circle me-2"></i>Create New Account
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form id="accountForm" action="/accounting/accounts" method="POST">
                    @csrf
                    <input type="hidden" id="accountId" name="id">
                    <div class="modal-body">
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label class="form-label">Account Code <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="accountCode" name="code" required>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Account Name <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="accountName" name="name" required>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Account Type <span class="text-danger">*</span></label>
                                <select class="form-select" id="accountType" name="account_type" required>
                                    <option value="">Select Type</option>
                                    <option value="H">Header Account</option>
                                    <option value="P">Posting Account</option>
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Normal Balance <span class="text-danger">*</span></label>
                                <select class="form-select" id="accountNormalBalance" name="normal_balance" required>
                                    <option value="">Select Balance</option>
                                    <option value="Dr">Debit</option>
                                    <option value="Cr">Credit</option>
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Category</label>
                                <input type="text" class="form-control" id="accountCategory" name="category">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">P&L Line</label>
                                <input type="text" class="form-control" id="accountPlLine" name="pl_line">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Report Section</label>
                                <select class="form-select" id="accountReportSection" name="report_section">
                                    <option value="">Select Section</option>
                                    <option value="REVENUE">Revenue</option>
                                    <option value="REVENUE_DEPT">Revenue Department</option>
                                    <option value="COGS">Cost of Sales</option>
                                    <option value="COGS_DEPT">COGS Department</option>
                                    <option value="OPEX">Operating Expenses</option>
                                    <option value="NON_OP">Non-Operating</option>
                                    <option value="BS">Balance Sheet</option>
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Parent Account</label>
                                <select class="form-select" id="accountParentId" name="parent_id">
                                    <option value="">None (Top Level)</option>
                                    @foreach($accounts ?? [] as $account)
                                        <option value="{{ $account->id }}">{{ $account->code }} - {{ $account->name }}</option>
                                    @endforeach
                                </select>
                            </div>
                            <div class="col-12">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" id="accountIsActive" name="is_active" value="1" checked>
                                    <label class="form-check-label" for="accountIsActive">
                                        Active Account
                                    </label>
                                </div>
                            </div>
                            <div class="col-12">
                                <label class="form-label">Notes</label>
                                <textarea class="form-control" id="accountNotes" name="notes" rows="3"></textarea>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-save me-2"></i>Save Account
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- View Account Modal -->
    <div class="modal fade" id="viewAccountModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="fas fa-info-circle me-2"></i>Account Details
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body" id="viewAccountContent">
                    <!-- Content loaded dynamically -->
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-light" data-bs-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary" onclick="editFromView()" id="editFromViewBtn">
                        <i class="fas fa-edit me-2"></i>Edit Account
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
    <!-- DataTables -->
    <script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.4/js/dataTables.bootstrap5.min.js"></script>
    <!-- SweetAlert2 -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

    <script>
        let currentViewAccountId = null;

        $(document).ready(function() {
            $('#accountsTable').DataTable({
                responsive: true,
                order: [[0, 'asc']],
                pageLength: 25,
                columnDefs: [
                    { orderable: false, targets: -1 }
                ],
                language: {
                    search: "Search accounts:",
                    lengthMenu: "Show _MENU_ accounts",
                    info: "Showing _START_ to _END_ of _TOTAL_ accounts"
                }
            });
        });

        // Open modal for create/edit
        function openAccountModal(accountId = null) {
            if (accountId) {
                // Edit existing account
                $.ajax({
                    url: `/accounting/accounts/${accountId}/edit`,
                    type: 'GET',
                    success: function(data) {
                        $('#accountId').val(data.id);
                        $('#accountCode').val(data.code);
                        $('#accountName').val(data.name);
                        $('#accountType').val(data.account_type);
                        $('#accountNormalBalance').val(data.normal_balance);
                        $('#accountCategory').val(data.category);
                        $('#accountPlLine').val(data.pl_line);
                        $('#accountReportSection').val(data.report_section);
                        $('#accountParentId').val(data.parent_id);
                        $('#accountIsActive').prop('checked', data.is_active);
                        $('#accountNotes').val(data.notes);
                        
                        $('#accountModalTitle').html('<i class="fas fa-edit me-2"></i>Edit Account');
                        $('#accountModal').modal('show');
                    },
                    error: function(xhr) {
                        showToast('Error loading account data', 'error');
                    }
                });
            } else {
                // Create new account
                $('#accountForm')[0].reset();
                $('#accountId').val('');
                $('#accountIsActive').prop('checked', true);
                $('#accountModalTitle').html('<i class="fas fa-plus-circle me-2"></i>Create New Account');
                $('#accountModal').modal('show');
            }
        }

        // View account details
        function viewAccount(accountId) {
            currentViewAccountId = accountId;
            
            $.ajax({
                url: `/accounting/accounts/${accountId}`,
                type: 'GET',
                beforeSend: function() {
                    $('#viewAccountContent').html(`
                        <div class="text-center py-4">
                            <div class="spinner-border text-primary" role="status">
                                <span class="visually-hidden">Loading...</span>
                            </div>
                            <p class="mt-2 text-muted">Loading account details...</p>
                        </div>
                    `);
                },
                success: function(data) {
                    let balance = data.balance || 0;
                    let balanceClass = balance >= 0 ? 'text-success' : 'text-danger';
                    
                    let html = `
                        <div class="account-details">
                            <div class="text-center mb-4">
                                <div class="rounded-circle p-3 d-inline-block" style="background: #e9efff;">
                                    <i class="fas fa-book fa-2x" style="color: #4361ee;"></i>
                                </div>
                            </div>
                            
                            <div class="detail-item">
                                <div class="detail-label">Account Code</div>
                                <div class="detail-value">${data.code}</div>
                            </div>
                            
                            <div class="detail-item">
                                <div class="detail-label">Account Name</div>
                                <div class="detail-value">${data.name}</div>
                            </div>
                            
                            <div class="row">
                                <div class="col-6">
                                    <div class="detail-item">
                                        <div class="detail-label">Type</div>
                                        <div class="detail-value">
                                            <span class="badge-type ${data.account_type}">
                                                ${data.account_type === 'P' ? 'Posting Account' : 'Header Account'}
                                            </span>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-6">
                                    <div class="detail-item">
                                        <div class="detail-label">Normal Balance</div>
                                        <div class="detail-value">${data.normal_balance === 'Dr' ? 'Debit' : 'Credit'}</div>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="detail-item">
                                <div class="detail-label">Category</div>
                                <div class="detail-value">${data.category || 'Not specified'}</div>
                            </div>
                            
                            <div class="detail-item">
                                <div class="detail-label">P&L Line</div>
                                <div class="detail-value">${data.pl_line || 'Not specified'}</div>
                            </div>
                            
                            <div class="detail-item">
                                <div class="detail-label">Report Section</div>
                                <div class="detail-value">${data.report_section || 'Not specified'}</div>
                            </div>
                            
                            <div class="detail-item">
                                <div class="detail-label">Parent Account</div>
                                <div class="detail-value">${data.parent ? data.parent.code + ' - ' + data.parent.name : 'None (Top Level)'}</div>
                            </div>
                            
                            <div class="detail-item">
                                <div class="detail-label">Status</div>
                                <div class="detail-value">
                                    <span class="badge-status ${data.is_active ? 'active' : 'inactive'}">
                                        ${data.is_active ? 'Active' : 'Inactive'}
                                    </span>
                                </div>
                            </div>
                            
                            <div class="detail-item">
                                <div class="detail-label">Current Balance</div>
                                <div class="detail-value large ${balanceClass}">UGX ${balance.toLocaleString()}</div>
                            </div>
                            
                            <div class="detail-item">
                                <div class="detail-label">Notes</div>
                                <div class="detail-value">${data.notes || 'No notes available'}</div>
                            </div>
                            
                            <div class="detail-item">
                                <div class="detail-label">Created</div>
                                <div class="detail-value">${new Date(data.created_at).toLocaleDateString()}</div>
                            </div>
                            
                            <div class="detail-item">
                                <div class="detail-label">Last Updated</div>
                                <div class="detail-value">${new Date(data.updated_at).toLocaleDateString()}</div>
                            </div>
                        </div>
                    `;
                    
                    $('#viewAccountContent').html(html);
                    $('#viewAccountModal').modal('show');
                },
                error: function(xhr) {
                    showToast('Error loading account details', 'error');
                    $('#viewAccountModal').modal('hide');
                }
            });
        }

        // Edit from view modal
        function editFromView() {
            if (currentViewAccountId) {
                $('#viewAccountModal').modal('hide');
                setTimeout(() => {
                    openAccountModal(currentViewAccountId);
                }, 500);
            }
        }

        // Delete account
        function deleteAccount(accountId) {
            Swal.fire({
                title: 'Delete Account',
                text: 'Are you sure you want to delete this account? This action cannot be undone.',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#ef4444',
                confirmButtonText: 'Yes, delete',
                cancelButtonText: 'Cancel',
                reverseButtons: true
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: `/accounting/accounts/${accountId}`,
                        type: 'DELETE',
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        },
                        beforeSend: function() {
                            Swal.fire({
                                title: 'Deleting...',
                                allowOutsideClick: false,
                                showConfirmButton: false,
                                willOpen: () => Swal.showLoading()
                            });
                        },
                        success: function(response) {
                            Swal.close();
                            showToast('Account deleted successfully', 'success');
                            setTimeout(() => location.reload(), 1500);
                        },
                        error: function(xhr) {
                            Swal.close();
                            let message = xhr.responseJSON?.message || 'Error deleting account';
                            showToast(message, 'error');
                        }
                    });
                }
            });
        }

        // Submit form (create/update)
        $('#accountForm').on('submit', function(e) {
            e.preventDefault();
            
            const accountId = $('#accountId').val();
            const url = accountId ? `/accounting/accounts/${accountId}` : '/accounting/accounts';
            const method = accountId ? 'PUT' : 'POST';
            
            // Get form data
            let formData = $(this).serialize();
            
            $.ajax({
                url: url,
                type: method,
                data: formData,
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                beforeSend: function() {
                    Swal.fire({
                        title: 'Saving...',
                        allowOutsideClick: false,
                        showConfirmButton: false,
                        willOpen: () => Swal.showLoading()
                    });
                },
                success: function(response) {
                    Swal.close();
                    $('#accountModal').modal('hide');
                    showToast(accountId ? 'Account updated successfully' : 'Account created successfully', 'success');
                    setTimeout(() => location.reload(), 1500);
                },
                error: function(xhr) {
                    Swal.close();
                    let message = xhr.responseJSON?.message || 'Error saving account';
                    showToast(message, 'error');
                }
            });
        });

        // Show toast notification
        function showToast(message, type) {
            const Toast = Swal.mixin({
                toast: true,
                position: 'top-end',
                showConfirmButton: false,
                timer: 3000,
                timerProgressBar: true,
                didOpen: (toast) => {
                    toast.addEventListener('mouseenter', Swal.stopTimer);
                    toast.addEventListener('mouseleave', Swal.resumeTimer);
                }
            });

            Toast.fire({
                icon: type,
                title: message
            });
        }
    </script>
</body>
</html>