<!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>Budget Management - 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);
        }

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

        .btn-outline-primary:hover {
            background: #4361ee;
            color: white;
            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.green { background: #e3f7ec; color: #10b981; }
        .stat-icon.orange { background: #fff2e0; color: #f97316; }
        .stat-icon.red { background: #fee9e9; color: #ef4444; }

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

        .stat-trend {
            font-size: 0.85rem;
            color: #64748b;
        }

        /* Filter Card */
        .filter-card {
            background: white;
            border-radius: 16px;
            padding: 1.5rem;
            box-shadow: 0 4px 15px rgba(0,0,0,0.02);
            margin-bottom: 1.5rem;
        }

        .filter-card h5 {
            font-size: 1rem;
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 1rem;
        }

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

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

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

        .btn-apply {
            background: #4361ee;
            color: white;
            border: none;
            border-radius: 10px;
            padding: 0.6rem 1.5rem;
            font-weight: 500;
            width: 100%;
            transition: all 0.2s;
        }

        .btn-apply:hover {
            background: #3651d4;
        }

        .btn-reset {
            background: #f1f5f9;
            color: #64748b;
            border: none;
            border-radius: 10px;
            padding: 0.6rem;
            font-size: 0.9rem;
            transition: all 0.2s;
        }

        .btn-reset:hover {
            background: #e2e8f0;
        }

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

        .table-header {
            padding: 1.2rem 1.5rem;
            border-bottom: 1px solid #f1f5f9;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

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

        .table-header i {
            color: #4361ee;
        }

        .table-responsive {
            padding: 0 1.5rem 1.5rem 1.5rem;
        }

        .table {
            margin: 0;
        }

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

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

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

        .account-info {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .account-icon {
            width: 35px;
            height: 35px;
            background: #e9efff;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #4361ee;
        }

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

        .badge-year, .badge-period {
            background: #f1f5f9;
            color: #475569;
            padding: 0.3rem 0.8rem;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: 500;
        }

        .amount-positive {
            color: #10b981;
            font-weight: 600;
        }

        .amount-negative {
            color: #ef4444;
            font-weight: 600;
        }

        /* Progress Bar */
        .progress-container {
            display: flex;
            align-items: center;
            gap: 10px;
            min-width: 120px;
        }

        .progress {
            flex: 1;
            height: 8px;
            border-radius: 10px;
            background: #f1f5f9;
        }

        .progress-bar {
            border-radius: 10px;
        }

        .progress-bar.bg-success { background: #10b981; }
        .progress-bar.bg-warning { background: #f97316; }
        .progress-bar.bg-danger { background: #ef4444; }

        .progress-percent {
            font-size: 0.85rem;
            font-weight: 500;
            color: #64748b;
            min-width: 45px;
        }

        /* Status Badges */
        .status-badge {
            padding: 0.3rem 0.8rem;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: 500;
            display: inline-flex;
            align-items: center;
            gap: 4px;
        }

        .status-badge.success { background: #e3f7ec; color: #10b981; }
        .status-badge.warning { background: #fff2e0; color: #f97316; }
        .status-badge.danger { background: #fee9e9; color: #ef4444; }
        .status-badge.info { background: #e9efff; color: #4361ee; }

        /* Action Buttons */
        .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; }

        /* Empty State */
        .empty-state {
            text-align: center;
            padding: 3rem;
        }

        .empty-state i {
            font-size: 4rem;
            color: #cbd5e1;
            margin-bottom: 1rem;
        }

        .empty-state p {
            color: #64748b;
            margin-bottom: 1.5rem;
        }

        /* 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;
        }

        /* 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;
            }

            .filter-row > div {
                margin-bottom: 0.5rem;
            }
        }
    </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">Budget Management</h1>
                </div>
                <p>Manage and track your financial budgets</p>
            </div>
            <div class="d-flex gap-2">
                <button class="btn-outline-primary" onclick="openVarianceModal()">
                    <i class="fas fa-chart-line"></i>
                    <span>Variance Report</span>
                </button>
                <button class="btn-primary" onclick="openBudgetModal()">
                    <i class="fas fa-plus"></i>
                    <span>New Budget</span>
                </button>
            </div>
        </div>

        <!-- Stats Cards -->
        <div class="stats-row">
            <div class="stat-card">
                <div class="stat-header">
                    <span class="stat-label">Total Budget</span>
                    <div class="stat-icon purple">
                        <i class="fas fa-wallet"></i>
                    </div>
                </div>
                <div class="stat-value" id="totalBudget">{{ number_format($totalBudget ?? 0) }}</div>
                <div class="stat-trend">Annual budget allocation</div>
            </div>

            <div class="stat-card">
                <div class="stat-header">
                    <span class="stat-label">Total Spent</span>
                    <div class="stat-icon green">
                        <i class="fas fa-credit-card"></i>
                    </div>
                </div>
                <div class="stat-value" id="totalSpent">{{ number_format($totalSpent ?? 0) }}</div>
                <div class="stat-trend">Year-to-date expenses</div>
            </div>

            <div class="stat-card">
                <div class="stat-header">
                    <span class="stat-label">Remaining</span>
                    <div class="stat-icon orange">
                        <i class="fas fa-piggy-bank"></i>
                    </div>
                </div>
                <div class="stat-value" id="totalRemaining">{{ number_format($totalRemaining ?? 0) }}</div>
                <div class="stat-trend">Available to spend</div>
            </div>

            <div class="stat-card">
                <div class="stat-header">
                    <span class="stat-label">Utilization</span>
                    <div class="stat-icon red">
                        <i class="fas fa-percent"></i>
                    </div>
                </div>
                <div class="stat-value" id="utilization">{{ $utilization ?? 0 }}%</div>
                <div class="stat-trend">
                    <div class="progress mt-2" style="height: 4px;">
                        <div class="progress-bar {{ ($utilization ?? 0) >= 80 ? 'bg-warning' : 'bg-success' }}" 
                             style="width: {{ min($utilization ?? 0, 100) }}%"></div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Filter Card -->
        <div class="filter-card">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h5><i class="fas fa-filter me-2" style="color: #4361ee;"></i>Filter Budgets</h5>
                <button class="btn-reset" onclick="resetFilters()">
                    <i class="fas fa-redo-alt me-1"></i>Reset
                </button>
            </div>
            <div class="row g-3">
                <div class="col-md-3">
                    <div class="filter-label">FISCAL YEAR</div>
                    <select class="form-select" id="filterYear">
                        <option value="">All Years</option>
                        @for($y = now()->year - 2; $y <= now()->year + 2; $y++)
                            <option value="{{ $y }}" {{ request('fiscal_year') == $y ? 'selected' : '' }}>{{ $y }}</option>
                        @endfor
                    </select>
                </div>
                <div class="col-md-3">
                    <div class="filter-label">PERIOD</div>
                    <select class="form-select" id="filterPeriod">
                        <option value="">All Periods</option>
                        <option value="monthly" {{ request('period') == 'monthly' ? 'selected' : '' }}>Monthly</option>
                        <option value="quarterly" {{ request('period') == 'quarterly' ? 'selected' : '' }}>Quarterly</option>
                        <option value="yearly" {{ request('period') == 'yearly' ? 'selected' : '' }}>Yearly</option>
                    </select>
                </div>
                <div class="col-md-4">
                    <div class="filter-label">ACCOUNT</div>
                    <select class="form-select" id="filterAccount">
                        <option value="">All Accounts</option>
                        @foreach($accounts as $account)
                            <option value="{{ $account->id }}" {{ request('account_id') == $account->id ? 'selected' : '' }}>
                                {{ $account->code }} - {{ $account->name }}
                            </option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-2 d-flex align-items-end">
                    <button class="btn-apply" onclick="applyFilters()">
                        <i class="fas fa-search me-2"></i>Apply
                    </button>
                </div>
            </div>
        </div>

        <!-- Budgets Table Card -->
        <div class="table-card">
            <div class="table-header">
                <h5><i class="fas fa-list me-2"></i>Budget List</h5>
            </div>
            <div class="table-responsive">
                <table class="table" id="budgetsTable">
                    <thead>
                        <tr>
                            <th>Account</th>
                            <th>Fiscal Year</th>
                            <th>Period</th>
                            <th class="text-end">Budget Amount</th>
                            <th class="text-end">Actual Spent</th>
                            <th class="text-end">Remaining</th>
                            <th class="text-center">Utilization</th>
                            <th>Status</th>
                            <th class="text-center">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        @forelse($budgets as $budget)
                            <tr>
                                <td>
                                    <div class="account-info">
                                        <div class="account-icon">
                                            <i class="fas fa-chart-pie"></i>
                                        </div>
                                        <div>
                                            <div class="account-code">{{ $budget->account->code }}</div>
                                            <small class="text-muted">{{ Str::limit($budget->account->name, 20) }}</small>
                                        </div>
                                    </div>
                                </td>
                                <td><span class="badge-year">{{ $budget->fiscal_year }}</span></td>
                                <td><span class="badge-period">{{ ucfirst($budget->period) }}</span></td>
                                <td class="text-end fw-bold">{{ number_format($budget->amount) }}</td>
                                <td class="text-end text-primary fw-bold">{{ number_format($budget->spent_amount) }}</td>
                                <td class="text-end {{ $budget->remaining_amount < 0 ? 'amount-negative' : 'amount-positive' }} fw-bold">
                                    {{ number_format($budget->remaining_amount) }}
                                </td>
                                <td>
                                    <div class="progress-container">
                                        <div class="progress">
                                            <div class="progress-bar 
                                                @if($budget->utilization_percentage >= 100) bg-danger
                                                @elseif($budget->utilization_percentage >= 80) bg-warning
                                                @else bg-success
                                                @endif"
                                                style="width: {{ min($budget->utilization_percentage, 100) }}%"></div>
                                        </div>
                                        <span class="progress-percent">{{ number_format($budget->utilization_percentage, 1) }}%</span>
                                    </div>
                                </td>
                                <td>
                                    @php 
                                        $status = $budget->status; 
                                        $statusClass = is_array($status) ? ($status['class'] ?? 'info') : 'info';
                                        $statusText = is_array($status) ? ($status['text'] ?? 'Unknown') : 'Unknown';
                                    @endphp
                                    <span class="status-badge {{ $statusClass }}">
                                        <i class="fas fa-{{ $statusClass == 'success' ? 'check-circle' : ($statusClass == 'warning' ? 'exclamation-circle' : ($statusClass == 'danger' ? 'times-circle' : 'info-circle')) }}"></i>
                                        {{ $statusText }}
                                    </span>
                                </td>
                                <td>
                                    <div class="action-btns">
                                        <button class="btn-icon info" onclick="viewBudget({{ $budget->id }})" title="View Details">
                                            <i class="fas fa-eye"></i>
                                        </button>
                                        <button class="btn-icon edit" onclick="editBudget({{ $budget->id }})" title="Edit Budget">
                                            <i class="fas fa-edit"></i>
                                        </button>
                                        <button class="btn-icon delete" onclick="deleteBudget({{ $budget->id }})" title="Delete Budget">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="9" class="text-center">
                                    <div class="empty-state">
                                        <i class="fas fa-chart-pie"></i>
                                        <p>No budgets found. Create your first budget to get started.</p>
                                        <button class="btn-primary" onclick="openBudgetModal()">
                                            <i class="fas fa-plus me-2"></i>Create Budget
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Budget Modal (Create/Edit) -->
    <div class="modal fade" id="budgetModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="budgetModalLabel">
                        <i class="fas fa-plus-circle me-2"></i>Create New Budget
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form id="budgetForm" action="/accounting/budgets" method="POST">
                    @csrf
                    <input type="hidden" id="budgetId" name="id">
                    <div class="modal-body">
                        <div class="mb-3">
                            <label class="form-label">Account <span class="text-danger">*</span></label>
                            <select class="form-select" id="budgetAccountId" name="account_id" required>
                                <option value="">Select Account</option>
                                @foreach($accounts as $account)
                                    <option value="{{ $account->id }}">{{ $account->code }} - {{ $account->name }}</option>
                                @endforeach
                            </select>
                        </div>

                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Fiscal Year <span class="text-danger">*</span></label>
                                <input type="number" class="form-control" id="budgetFiscalYear" name="fiscal_year" value="{{ date('Y') }}" min="2000" max="2100" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Period <span class="text-danger">*</span></label>
                                <select class="form-select" id="budgetPeriod" name="period" required>
                                    <option value="monthly">Monthly</option>
                                    <option value="quarterly">Quarterly</option>
                                    <option value="yearly">Yearly</option>
                                </select>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Budget Amount (UGX) <span class="text-danger">*</span></label>
                            <div class="input-group">
                                <span class="input-group-text bg-light">UGX</span>
                                <input type="number" class="form-control" id="budgetAmount" name="amount" step="1000" min="0" required>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Notes</label>
                            <textarea class="form-control" id="budgetNotes" name="notes" rows="3" placeholder="Add any additional notes..."></textarea>
                        </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 Budget
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- View Budget Modal -->
    <div class="modal fade" id="viewBudgetModal" 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>Budget Details
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body" id="viewBudgetContent">
                    <!-- 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-outline-primary" onclick="printBudget()">
                        <i class="fas fa-print me-2"></i>Print
                    </button>
                    <button type="button" class="btn btn-primary" onclick="editFromView()" id="editFromViewBtn">
                        <i class="fas fa-edit me-2"></i>Edit Budget
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Variance Modal -->
    <div class="modal fade" id="varianceModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="fas fa-chart-line me-2"></i>Variance Analysis Report
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body" id="varianceContent">
                    <!-- 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-success" onclick="exportVariance()">
                        <i class="fas fa-file-export me-2"></i>Export Report
                    </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 currentViewBudgetId = null;

        $(document).ready(function() {
            initializeDataTable();
            
            $('#budgetForm').on('submit', function(e) {
                e.preventDefault();
                saveBudget();
            });
        });

        function initializeDataTable() {
            const hasDataRows = $('#budgetsTable tbody tr').length > 0 && 
                               !$('#budgetsTable tbody tr td').hasClass('text-center');
            
            if (hasDataRows) {
                if ($.fn.DataTable && $.fn.DataTable.isDataTable('#budgetsTable')) {
                    $('#budgetsTable').DataTable().destroy();
                }
                
                $('#budgetsTable').DataTable({
                    responsive: true,
                    order: [[1, 'desc'], [2, 'asc']],
                    pageLength: 25,
                    columnDefs: [
                        { orderable: false, targets: [6,7,8] }
                    ],
                    language: {
                        emptyTable: "No budgets available",
                        info: "Showing _START_ to _END_ of _TOTAL_ budgets",
                        infoEmpty: "Showing 0 to 0 of 0 budgets",
                        infoFiltered: "(filtered from _MAX_ total budgets)",
                        lengthMenu: "Show _MENU_ budgets",
                        search: "Search:",
                        zeroRecords: "No matching budgets found",
                        paginate: {
                            first: "First",
                            last: "Last",
                            next: "Next",
                            previous: "Previous"
                        }
                    }
                });
            }
        }

        function openBudgetModal() {
            $('#budgetForm')[0].reset();
            $('#budgetId').val('');
            $('#budgetModalLabel').html('<i class="fas fa-plus-circle me-2"></i>Create New Budget');
            $('#budgetModal').modal('show');
        }

        function applyFilters() {
            const year = $('#filterYear').val();
            const period = $('#filterPeriod').val();
            const accountId = $('#filterAccount').val();

            window.location.href = '/accounting/budgets?' +
                'fiscal_year=' + year +
                '&period=' + period +
                '&account_id=' + accountId;
        }

        function resetFilters() {
            $('#filterYear').val('');
            $('#filterPeriod').val('');
            $('#filterAccount').val('');
            applyFilters();
        }

        function viewBudget(id) {
            currentViewBudgetId = id;
            
            Swal.fire({
                title: 'Loading...',
                allowOutsideClick: false,
                showConfirmButton: false,
                willOpen: () => Swal.showLoading()
            });

            fetch(`/accounting/budgets/${id}`)
                .then(response => response.json())
                .then(data => {
                    Swal.close();
                    // API returns { success, budget }; legacy may return flat budget fields
                    const b = data.budget != null ? data.budget : data;
                    if (!b || (data.success === false && !data.budget)) {
                        showToast(data.message || 'Could not load budget details', 'error');
                        return;
                    }
                    let status = b.status || {};
                    let statusClass = status.class || 'info';
                    let statusText = status.text || 'Unknown';

                    const fmtDate = (v) => {
                        if (v == null || v === '') return 'N/A';
                        const d = new Date(v);
                        return isNaN(d.getTime()) ? 'N/A' : d.toLocaleDateString();
                    };
                    
                    let html = `
                        <div class="budget-details">
                            <div class="text-center mb-4">
                                <div class="rounded-circle p-3 d-inline-block" style="background: #e9efff;">
                                    <i class="fas fa-chart-pie fa-2x" style="color: #4361ee;"></i>
                                </div>
                            </div>
                            
                            <div class="detail-item">
                                <div class="detail-label">Account</div>
                                <div class="detail-value">${b.account ? b.account.code + ' - ' + b.account.name : 'N/A'}</div>
                            </div>
                            
                            <div class="row">
                                <div class="col-6">
                                    <div class="detail-item">
                                        <div class="detail-label">Fiscal Year</div>
                                        <div class="detail-value">${b.fiscal_year != null ? b.fiscal_year : 'N/A'}</div>
                                    </div>
                                </div>
                                <div class="col-6">
                                    <div class="detail-item">
                                        <div class="detail-label">Period</div>
                                        <div class="detail-value">${b.period_name || b.period || 'N/A'}</div>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="detail-item">
                                <div class="detail-label">Status</div>
                                <div class="detail-value">
                                    <span class="status-badge ${statusClass}">
                                        <i class="fas fa-${statusClass == 'success' ? 'check-circle' : (statusClass == 'warning' ? 'exclamation-circle' : (statusClass == 'danger' ? 'times-circle' : 'info-circle'))}"></i>
                                        ${statusText}
                                    </span>
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-4">
                                    <div class="detail-item text-center">
                                        <div class="detail-label">Budget Amount</div>
                                        <div class="detail-value large">${formatCurrency(b.amount || 0)}</div>
                                    </div>
                                </div>
                                <div class="col-4">
                                    <div class="detail-item text-center">
                                        <div class="detail-label">Actual Spent</div>
                                        <div class="detail-value large text-primary">${formatCurrency(b.spent_amount || 0)}</div>
                                    </div>
                                </div>
                                <div class="col-4">
                                    <div class="detail-item text-center">
                                        <div class="detail-label">Remaining</div>
                                        <div class="detail-value large ${(b.remaining_amount || 0) < 0 ? 'text-danger' : 'text-success'}">${formatCurrency(b.remaining_amount || 0)}</div>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="detail-item">
                                <div class="detail-label mb-2">Utilization</div>
                                <div class="progress-container mb-2">
                                    <div class="progress" style="height: 10px;">
                                        <div class="progress-bar bg-${statusClass}" style="width: ${Math.min(b.utilization_percentage || 0, 100)}%"></div>
                                    </div>
                                    <span class="progress-percent">${(Number(b.utilization_percentage) || 0).toFixed(1)}%</span>
                                </div>
                            </div>
                            
                            <div class="detail-item">
                                <div class="detail-label">Notes</div>
                                <div class="detail-value">${b.notes || 'No notes available'}</div>
                            </div>
                            
                            <div class="detail-item">
                                <div class="detail-label">Created</div>
                                <div class="detail-value">${fmtDate(b.created_at)}</div>
                            </div>
                            
                            <div class="detail-item">
                                <div class="detail-label">Last Updated</div>
                                <div class="detail-value">${fmtDate(b.updated_at)}</div>
                            </div>
                        </div>
                    `;

                    $('#viewBudgetContent').html(html);
                    $('#viewBudgetModal').modal('show');
                })
                .catch(error => {
                    Swal.close();
                    showToast('Error loading budget details', 'error');
                });
        }

        function editFromView() {
            if (currentViewBudgetId) {
                $('#viewBudgetModal').modal('hide');
                setTimeout(() => {
                    editBudget(currentViewBudgetId);
                }, 500);
            }
        }

        function editBudget(id) {
            Swal.fire({
                title: 'Loading...',
                allowOutsideClick: false,
                showConfirmButton: false,
                willOpen: () => Swal.showLoading()
            });

            fetch(`/accounting/budgets/${id}/edit`)
                .then(response => response.json())
                .then(data => {
                    Swal.close();
                    const b = data.budget != null ? data.budget : data;
                    if (!b || !b.id) {
                        showToast(data.message || 'Could not load budget', 'error');
                        return;
                    }
                    $('#budgetId').val(b.id);
                    $('#budgetAccountId').val(b.account_id);
                    $('#budgetFiscalYear').val(b.fiscal_year);
                    $('#budgetPeriod').val(b.period);
                    $('#budgetAmount').val(b.amount);
                    $('#budgetNotes').val(b.notes);

                    $('#budgetModalLabel').html('<i class="fas fa-edit me-2"></i>Edit Budget');
                    $('#budgetModal').modal('show');
                })
                .catch(error => {
                    Swal.close();
                    showToast('Error loading budget', 'error');
                });
        }

        function deleteBudget(id) {
            Swal.fire({
                title: 'Delete Budget',
                text: 'Are you sure you want to delete this budget? 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/budgets/${id}`,
                        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('Budget deleted successfully', 'success');
                            setTimeout(() => location.reload(), 1500);
                        },
                        error: function(xhr) {
                            Swal.close();
                            showToast(xhr.responseJSON?.message || 'Error deleting budget', 'error');
                        }
                    });
                }
            });
        }

        function saveBudget() {
            const budgetId = $('#budgetId').val();
            const url = budgetId ? `/accounting/budgets/${budgetId}` : '/accounting/budgets';
            const method = budgetId ? 'PUT' : 'POST';

            $.ajax({
                url: url,
                type: method,
                data: $('#budgetForm').serialize(),
                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();
                    $('#budgetModal').modal('hide');
                    showToast(budgetId ? 'Budget updated successfully' : 'Budget created successfully', 'success');
                    setTimeout(() => location.reload(), 1500);
                },
                error: function(xhr) {
                    Swal.close();
                    showToast(xhr.responseJSON?.message || 'Error saving budget', 'error');
                }
            });
        }

        function openVarianceModal() {
            const year = $('#filterYear').val() || new Date().getFullYear();
            const period = $('#filterPeriod').val() || 'yearly';

            Swal.fire({
                title: 'Generating Report...',
                allowOutsideClick: false,
                showConfirmButton: false,
                willOpen: () => Swal.showLoading()
            });

            fetch(`/accounting/budgets/variance?fiscal_year=${year}&period=${period}`)
                .then(response => response.json())
                .then(data => {
                    Swal.close();
                    
                    let totalBudget = 0;
                    let totalActual = 0;
                    let totalVariance = 0;

                    if (data.data && data.data.length > 0) {
                        data.data.forEach(item => {
                            totalBudget += item.budget?.amount || 0;
                            totalActual += item.actual || 0;
                            totalVariance += item.variance || 0;
                        });
                    }

                    let totalVariancePercent = totalBudget > 0 ? (totalVariance / totalBudget) * 100 : 0;

                    let html = `
                        <div class="variance-report">
                            <div class="mb-4 text-center">
                                <h6 class="fw-bold">Budget Variance Report</h6>
                                <div class="d-flex justify-content-center gap-3">
                                    <span class="badge bg-light text-dark"><i class="fas fa-calendar me-1"></i>Year: ${year}</span>
                                    <span class="badge bg-light text-dark"><i class="fas fa-chart-bar me-1"></i>Period: ${period}</span>
                                </div>
                            </div>

                            <div class="table-responsive">
                                <table class="table table-hover align-middle">
                                    <thead class="bg-light">
                                        <tr>
                                            <th>Account</th>
                                            <th class="text-end">Budget</th>
                                            <th class="text-end">Actual</th>
                                            <th class="text-end">Variance</th>
                                            <th class="text-end">Variance %</th>
                                            <th class="text-center">Status</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                    `;

                    if (data.data && data.data.length > 0) {
                        data.data.forEach(item => {
                            const variance = item.variance || 0;
                            const variancePercent = item.variance_percent || 0;
                            const varianceClass = variance < 0 ? 'amount-negative' : 'amount-positive';
                            const percentClass = variancePercent < 0 ? 'amount-negative' : 'amount-positive';
                            const status = variance > 0 ? 'success' : (variance < 0 ? 'danger' : 'warning');
                            
                            html += `
                                <tr>
                                    <td>
                                        <div>
                                            <strong>${item.account?.code || 'N/A'}</strong>
                                            <div><small class="text-muted">${item.account?.name || 'Unknown'}</small></div>
                                        </div>
                                    </td>
                                    <td class="text-end fw-bold">${formatCurrency(item.budget?.amount || 0)}</td>
                                    <td class="text-end text-primary fw-bold">${formatCurrency(item.actual || 0)}</td>
                                    <td class="text-end ${varianceClass} fw-bold">${formatCurrency(variance)}</td>
                                    <td class="text-end ${percentClass} fw-bold">
                                        ${variancePercent.toFixed(2)}%
                                        ${variancePercent > 0 ? '<i class="fas fa-arrow-up ms-1"></i>' : (variancePercent < 0 ? '<i class="fas fa-arrow-down ms-1"></i>' : '')}
                                    </td>
                                    <td class="text-center">
                                        <span class="status-badge ${status}">
                                            <i class="fas fa-${status == 'success' ? 'check-circle' : (status == 'warning' ? 'minus-circle' : 'exclamation-circle')}"></i>
                                            ${variance > 0 ? 'Favorable' : (variance < 0 ? 'Unfavorable' : 'On Track')}
                                        </span>
                                    </td>
                                </tr>
                            `;
                        });
                    } else {
                        html += `
                            <tr>
                                <td colspan="6" class="text-center py-4">
                                    <i class="fas fa-chart-line fa-3x text-muted mb-3"></i>
                                    <p class="text-muted">No variance data available for the selected period.</p>
                                </td>
                            </tr>
                        `;
                    }

                    html += `
                                    </tbody>
                                    <tfoot class="bg-light fw-bold">
                                        <tr>
                                            <th>Totals:</th>
                                            <th class="text-end">${formatCurrency(totalBudget)}</th>
                                            <th class="text-end text-primary">${formatCurrency(totalActual)}</th>
                                            <th class="text-end ${totalVariance < 0 ? 'amount-negative' : 'amount-positive'}">${formatCurrency(totalVariance)}</th>
                                            <th class="text-end ${totalVariancePercent < 0 ? 'amount-negative' : 'amount-positive'}">
                                                ${totalVariancePercent.toFixed(2)}%
                                            </th>
                                            <th></th>
                                        </tr>
                                    </tfoot>
                                </table>
                            </div>

                            <div class="row mt-4 g-3">
                                <div class="col-md-4">
                                    <div class="p-3 bg-light rounded text-center">
                                        <small class="text-muted d-block">Total Budget</small>
                                        <strong class="fs-5">${formatCurrency(totalBudget)}</strong>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="p-3 bg-light rounded text-center">
                                        <small class="text-muted d-block">Total Actual</small>
                                        <strong class="fs-5 text-primary">${formatCurrency(totalActual)}</strong>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="p-3 bg-light rounded text-center">
                                        <small class="text-muted d-block">Net Variance</small>
                                        <strong class="fs-5 ${totalVariance < 0 ? 'amount-negative' : 'amount-positive'}">${formatCurrency(totalVariance)}</strong>
                                    </div>
                                </div>
                            </div>
                        </div>
                    `;

                    $('#varianceContent').html(html);
                    $('#varianceModal').modal('show');
                })
                .catch(error => {
                    Swal.close();
                    showToast('Error generating variance report', 'error');
                });
        }

        function formatCurrency(amount) {
            return 'UGX ' + new Intl.NumberFormat('en-US').format(amount || 0);
        }

        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
            });
        }

        function printBudget() {
            const printContent = document.getElementById('viewBudgetContent').innerHTML;
            const originalContent = document.body.innerHTML;

            document.body.innerHTML = `
                <div class="container py-4">
                    <h2 class="text-center mb-4">Budget Details</h2>
                    ${printContent}
                </div>
            `;

            window.print();
            document.body.innerHTML = originalContent;
            location.reload();
        }

        function exportVariance() {
            const year = $('#filterYear').val() || new Date().getFullYear();
            const period = $('#filterPeriod').val() || 'yearly';
            
            window.location.href = `/accounting/budgets/variance/export?fiscal_year=${year}&period=${period}`;
        }
    </script>
</body>
</html>