<?php
session_start();
require_once 'config/config.php';
require_once 'auth/check_auth.php';

if (!isset($_SESSION['admin_id'])) {
    header('Location: login.php');
    exit();
}

$pageTitle = 'Enhanced Expense Categories';
$currentPage = 'expense-categories';
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><?php echo $pageTitle; ?> | KSO Chandigarh</title>
    
    <!-- AdminLTE CSS -->
    <link rel="stylesheet" href="dist/css/adminlte.min.css">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <!-- SweetAlert2 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
    
    <style>
        .expense-header {
            background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%);
            color: white;
            border-radius: 15px;
            padding: 25px;
            margin-bottom: 25px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }
        
        .category-card {
            background: white;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            border-left: 4px solid #007bff;
            transition: transform 0.3s ease;
        }
        
        .category-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 5px 20px rgba(0,0,0,0.15);
        }
        
        .category-icon {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            color: white;
            margin-bottom: 15px;
        }
        
        .budget-progress {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 15px;
        }
        
        .budget-bar {
            background: #e9ecef;
            border-radius: 10px;
            height: 8px;
            overflow: hidden;
            margin-bottom: 10px;
        }
        
        .budget-fill {
            height: 100%;
            background: linear-gradient(90deg, #28a745 0%, #20c997 100%);
            transition: width 0.3s ease;
        }
        
        .budget-fill.warning {
            background: linear-gradient(90deg, #ffc107 0%, #fd7e14 100%);
        }
        
        .budget-fill.danger {
            background: linear-gradient(90deg, #dc3545 0%, #e55353 100%);
        }
        
        .approval-workflow {
            background: #f0f8ff;
            border: 1px solid #b8daff;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
        }
        
        .expense-analytics {
            background: white;
            border-radius: 10px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .subcategory-tree {
            margin-left: 20px;
            border-left: 2px solid #dee2e6;
            padding-left: 15px;
        }
        
        .tree-item {
            padding: 8px 0;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }
        
        .tree-item:hover {
            background-color: #f8f9fa;
            border-radius: 5px;
        }
        
        .recurring-expense {
            background: #fff3cd;
            border: 1px solid #ffeaa7;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 15px;
        }
    </style>
</head>

<body class="hold-transition sidebar-mini layout-fixed">
<div class="wrapper">
    <!-- Include header -->
    <?php include 'templates/header.php'; ?>
    
    <!-- Include sidebar -->
    <?php include 'templates/sidebar.php'; ?>
    
    <!-- Content Wrapper -->
    <div class="content-wrapper">
        <!-- Content Header -->
        <div class="content-header">
            <div class="container-fluid">
                <div class="row mb-2">
                    <div class="col-sm-6">
                        <h1 class="m-0">
                            <i class="fas fa-layer-group text-primary"></i> Enhanced Expense Categories
                        </h1>
                    </div>
                    <div class="col-sm-6">
                        <ol class="breadcrumb float-sm-right">
                            <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
                            <li class="breadcrumb-item active">Expense Categories</li>
                        </ol>
                    </div>
                </div>
            </div>
        </div>

        <!-- Main content -->
        <section class="content">
            <div class="container-fluid">
                
                <!-- Expense Header -->
                <div class="expense-header">
                    <div class="row">
                        <div class="col-md-3">
                            <div class="text-center">
                                <h3 class="mb-1" id="totalCategories">0</h3>
                                <p class="mb-0">Total Categories</p>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="text-center">
                                <h3 class="mb-1" id="totalBudget">₹0</h3>
                                <p class="mb-0">Total Budget</p>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="text-center">
                                <h3 class="mb-1" id="totalSpent">₹0</h3>
                                <p class="mb-0">Total Spent</p>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="text-center">
                                <h3 class="mb-1" id="budgetUtilization">0%</h3>
                                <p class="mb-0">Budget Utilization</p>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Category Management -->
                <div class="row">
                    <div class="col-md-8">
                        <div class="card">
                            <div class="card-header">
                                <h3 class="card-title">
                                    <i class="fas fa-list"></i> Category Management
                                </h3>
                                <div class="card-tools">
                                    <button class="btn btn-primary btn-sm" onclick="showAddCategoryModal()">
                                        <i class="fas fa-plus"></i> Add Category
                                    </button>
                                </div>
                            </div>
                            <div class="card-body">
                                <div id="categoryList">
                                    <!-- Categories will be loaded here -->
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-md-4">
                        <div class="card">
                            <div class="card-header">
                                <h3 class="card-title">
                                    <i class="fas fa-chart-pie"></i> Budget Distribution
                                </h3>
                            </div>
                            <div class="card-body">
                                <canvas id="budgetChart" width="400" height="300"></canvas>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Approval Workflow -->
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-check-circle"></i> Approval Workflow
                        </h3>
                    </div>
                    <div class="card-body">
                        <div class="approval-workflow">
                            <h6>Expense Approval Settings</h6>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label>Approval Required Above (₹)</label>
                                        <input type="number" class="form-control" id="approvalThreshold" value="5000">
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label>Default Approver</label>
                                        <select class="form-control" id="defaultApprover">
                                            <option value="admin">Admin</option>
                                            <option value="treasurer">Treasurer</option>
                                            <option value="president">President</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <div class="custom-control custom-checkbox">
                                            <input type="checkbox" class="custom-control-input" id="emailNotification">
                                            <label class="custom-control-label" for="emailNotification">Email Notifications</label>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <div class="custom-control custom-checkbox">
                                            <input type="checkbox" class="custom-control-input" id="multiLevelApproval">
                                            <label class="custom-control-label" for="multiLevelApproval">Multi-level Approval</label>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <button class="btn btn-success" onclick="saveApprovalSettings()">
                                <i class="fas fa-save"></i> Save Settings
                            </button>
                        </div>
                    </div>
                </div>

                <!-- Recurring Expenses -->
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-redo-alt"></i> Recurring Expenses
                        </h3>
                    </div>
                    <div class="card-body">
                        <div id="recurringExpenses">
                            <!-- Recurring expenses will be loaded here -->
                        </div>
                    </div>
                </div>

                <!-- Expense Analytics -->
                <div class="row">
                    <div class="col-md-6">
                        <div class="card">
                            <div class="card-header">
                                <h3 class="card-title">
                                    <i class="fas fa-chart-line"></i> Expense Trends
                                </h3>
                            </div>
                            <div class="card-body">
                                <canvas id="trendChart" width="400" height="300"></canvas>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-md-6">
                        <div class="card">
                            <div class="card-header">
                                <h3 class="card-title">
                                    <i class="fas fa-exclamation-triangle"></i> Budget Alerts
                                </h3>
                            </div>
                            <div class="card-body">
                                <div id="budgetAlerts">
                                    <!-- Budget alerts will be loaded here -->
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

            </div>
        </section>
    </div>
</div>

<!-- Add Category Modal -->
<div class="modal fade" id="addCategoryModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Add New Category</h4>
                <button type="button" class="close" data-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form id="categoryForm">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Category Name</label>
                                <input type="text" class="form-control" id="categoryName" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Category Code</label>
                                <input type="text" class="form-control" id="categoryCode" required>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Budget Amount (₹)</label>
                                <input type="number" class="form-control" id="budgetAmount" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Parent Category</label>
                                <select class="form-control" id="parentCategory">
                                    <option value="">None (Main Category)</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Icon</label>
                                <select class="form-control" id="categoryIcon">
                                    <option value="fa-folder">Folder</option>
                                    <option value="fa-home">Home</option>
                                    <option value="fa-car">Transportation</option>
                                    <option value="fa-utensils">Food</option>
                                    <option value="fa-laptop">Technology</option>
                                    <option value="fa-tools">Maintenance</option>
                                    <option value="fa-users">Events</option>
                                    <option value="fa-graduation-cap">Education</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Color</label>
                                <input type="color" class="form-control" id="categoryColor" value="#007bff">
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label>Description</label>
                        <textarea class="form-control" id="categoryDescription" rows="3"></textarea>
                    </div>
                    <div class="form-group">
                        <div class="custom-control custom-checkbox">
                            <input type="checkbox" class="custom-control-input" id="requiresApproval">
                            <label class="custom-control-label" for="requiresApproval">Requires Approval</label>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" onclick="saveCategory()">Save Category</button>
            </div>
        </div>
    </div>
</div>

<!-- Include footer -->
<?php include 'templates/footer.php'; ?>

<!-- Scripts -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="dist/js/adminlte.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<script>
// Enhanced Expense Categories System
$(document).ready(function() {
    loadCategoryStats();
    loadCategoryList();
    loadBudgetChart();
    loadTrendChart();
    loadRecurringExpenses();
    loadBudgetAlerts();
    loadParentCategories();
    loadApprovalSettings();
});

function loadCategoryStats() {
    $.ajax({
        url: 'api/expense-categories/stats.php',
        method: 'GET',
        success: function(response) {
            if (response.success) {
                $('#totalCategories').text(response.stats.total_categories);
                $('#totalBudget').text('₹' + response.stats.total_budget.toLocaleString());
                $('#totalSpent').text('₹' + response.stats.total_spent.toLocaleString());
                $('#budgetUtilization').text(response.stats.utilization + '%');
            }
        }
    });
}

function loadCategoryList() {
    $.ajax({
        url: 'api/expense-categories/list.php',
        method: 'GET',
        success: function(response) {
            if (response.success) {
                const list = $('#categoryList');
                list.empty();
                
                response.categories.forEach(function(category) {
                    list.append(createCategoryCard(category));
                });
            }
        }
    });
}

function createCategoryCard(category) {
    const utilization = category.budget_amount > 0 ? (category.spent_amount / category.budget_amount * 100) : 0;
    const progressClass = utilization > 80 ? 'danger' : (utilization > 60 ? 'warning' : '');
    
    return `
        <div class="category-card">
            <div class="row">
                <div class="col-md-2">
                    <div class="category-icon" style="background-color: ${category.color}">
                        <i class="fas ${category.icon}"></i>
                    </div>
                </div>
                <div class="col-md-6">
                    <h5>${category.name}</h5>
                    <p class="text-muted mb-1">${category.description}</p>
                    <small class="text-muted">Code: ${category.code}</small>
                </div>
                <div class="col-md-4">
                    <div class="budget-progress">
                        <div class="d-flex justify-content-between">
                            <span>Budget: ₹${category.budget_amount.toLocaleString()}</span>
                            <span>Spent: ₹${category.spent_amount.toLocaleString()}</span>
                        </div>
                        <div class="budget-bar">
                            <div class="budget-fill ${progressClass}" style="width: ${utilization}%"></div>
                        </div>
                        <small class="text-muted">${utilization.toFixed(1)}% utilized</small>
                    </div>
                    <div class="btn-group btn-group-sm" role="group">
                        <button class="btn btn-outline-primary" onclick="editCategory(${category.id})">
                            <i class="fas fa-edit"></i>
                        </button>
                        <button class="btn btn-outline-danger" onclick="deleteCategory(${category.id})">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                </div>
            </div>
            ${category.subcategories ? createSubcategoryTree(category.subcategories) : ''}
        </div>
    `;
}

function createSubcategoryTree(subcategories) {
    let html = '<div class="subcategory-tree">';
    subcategories.forEach(function(sub) {
        html += `<div class="tree-item">${sub.name} (₹${sub.budget_amount.toLocaleString()})</div>`;
    });
    html += '</div>';
    return html;
}

function showAddCategoryModal() {
    $('#addCategoryModal').modal('show');
}

function saveCategory() {
    const formData = {
        name: $('#categoryName').val(),
        code: $('#categoryCode').val(),
        budget_amount: $('#budgetAmount').val(),
        parent_id: $('#parentCategory').val(),
        icon: $('#categoryIcon').val(),
        color: $('#categoryColor').val(),
        description: $('#categoryDescription').val(),
        requires_approval: $('#requiresApproval').is(':checked')
    };
    
    $.ajax({
        url: 'api/expense-categories/save.php',
        method: 'POST',
        data: formData,
        success: function(response) {
            if (response.success) {
                $('#addCategoryModal').modal('hide');
                if (window.ksoToast) {
                    window.ksoToast.success('Category saved successfully!');
                }
                loadCategoryList();
                loadCategoryStats();
                loadBudgetChart();
                clearForm();
            } else {
                if (window.ksoToast) {
                    window.ksoToast.error('Error: ' + response.message);
                }
            }
        }
    });
}

function loadBudgetChart() {
    $.ajax({
        url: 'api/expense-categories/budget-chart.php',
        method: 'GET',
        success: function(response) {
            if (response.success) {
                const ctx = document.getElementById('budgetChart').getContext('2d');
                new Chart(ctx, {
                    type: 'doughnut',
                    data: {
                        labels: response.labels,
                        datasets: [{
                            data: response.data,
                            backgroundColor: response.colors
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                position: 'bottom'
                            }
                        }
                    }
                });
            }
        }
    });
}

function loadTrendChart() {
    $.ajax({
        url: 'api/expense-categories/trend-chart.php',
        method: 'GET',
        success: function(response) {
            if (response.success) {
                const ctx = document.getElementById('trendChart').getContext('2d');
                new Chart(ctx, {
                    type: 'line',
                    data: {
                        labels: response.labels,
                        datasets: [{
                            label: 'Expenses',
                            data: response.data,
                            borderColor: 'rgb(75, 192, 192)',
                            backgroundColor: 'rgba(75, 192, 192, 0.2)',
                            tension: 0.1
                        }]
                    },
                    options: {
                        responsive: true,
                        scales: {
                            y: {
                                beginAtZero: true
                            }
                        }
                    }
                });
            }
        }
    });
}

function loadRecurringExpenses() {
    $.ajax({
        url: 'api/expense-categories/recurring.php',
        method: 'GET',
        success: function(response) {
            if (response.success) {
                const container = $('#recurringExpenses');
                container.empty();
                
                response.expenses.forEach(function(expense) {
                    container.append(createRecurringExpenseCard(expense));
                });
            }
        }
    });
}

function createRecurringExpenseCard(expense) {
    return `
        <div class="recurring-expense">
            <div class="row">
                <div class="col-md-6">
                    <h6>${expense.name}</h6>
                    <p class="text-muted mb-0">${expense.description}</p>
                </div>
                <div class="col-md-3">
                    <p class="mb-0">Amount: ₹${expense.amount.toLocaleString()}</p>
                    <small class="text-muted">Frequency: ${expense.frequency}</small>
                </div>
                <div class="col-md-3">
                    <p class="mb-0">Next Due: ${expense.next_due}</p>
                    <button class="btn btn-sm btn-primary" onclick="processRecurring(${expense.id})">
                        <i class="fas fa-play"></i> Process
                    </button>
                </div>
            </div>
        </div>
    `;
}

function loadBudgetAlerts() {
    $.ajax({
        url: 'api/expense-categories/alerts.php',
        method: 'GET',
        success: function(response) {
            if (response.success) {
                const container = $('#budgetAlerts');
                container.empty();
                
                response.alerts.forEach(function(alert) {
                    container.append(createBudgetAlert(alert));
                });
            }
        }
    });
}

function createBudgetAlert(alert) {
    const alertClass = alert.type === 'danger' ? 'alert-danger' : 'alert-warning';
    return `
        <div class="alert ${alertClass}">
            <i class="fas fa-exclamation-triangle"></i>
            <strong>${alert.category_name}</strong> - ${alert.message}
        </div>
    `;
}

function saveApprovalSettings() {
    const settings = {
        threshold: $('#approvalThreshold').val(),
        approver: $('#defaultApprover').val(),
        email_notifications: $('#emailNotification').is(':checked'),
        multi_level: $('#multiLevelApproval').is(':checked')
    };
    
    $.ajax({
        url: 'api/expense-categories/save-approval-settings.php',
        method: 'POST',
        data: settings,
        success: function(response) {
            if (response.success) {
                if (window.ksoToast) {
                    window.ksoToast.success('Settings saved successfully!');
                }
            } else {
                if (window.ksoToast) {
                    window.ksoToast.error('Error: ' + response.message);
                }
            }
        }
    });
}

function loadApprovalSettings() {
    $.ajax({
        url: 'api/expense-categories/approval-settings.php',
        method: 'GET',
        success: function(response) {
            if (response.success) {
                const settings = response.settings;
                $('#approvalThreshold').val(settings.threshold || 5000);
                $('#defaultApprover').val(settings.approver || 'admin');
                $('#emailNotification').prop('checked', settings.email_notifications || false);
                $('#multiLevelApproval').prop('checked', settings.multi_level || false);
            }
        }
    });
}

function loadParentCategories() {
    $.ajax({
        url: 'api/expense-categories/parent-list.php',
        method: 'GET',
        success: function(response) {
            if (response.success) {
                const select = $('#parentCategory');
                select.empty();
                select.append('<option value="">None (Main Category)</option>');
                
                response.categories.forEach(function(category) {
                    select.append(`<option value="${category.id}">${category.name}</option>`);
                });
            }
        }
    });
}

function clearForm() {
    $('#categoryForm')[0].reset();
    $('#categoryColor').val('#007bff');
}

function editCategory(categoryId) {
    // Implementation for editing category
    console.log('Edit category:', categoryId);
}

function deleteCategory(categoryId) {
    if (confirm('Are you sure you want to delete this category?')) {
        $.ajax({
            url: 'api/expense-categories/delete.php',
            method: 'POST',
            data: { id: categoryId },
            success: function(response) {
                if (response.success) {
                    if (window.ksoToast) {
                        window.ksoToast.success('Category deleted successfully!');
                    }
                    loadCategoryList();
                    loadCategoryStats();
                } else {
                    if (window.ksoToast) {
                        window.ksoToast.error('Error: ' + response.message);
                    }
                }
            }
        });
    }
}

function processRecurring(expenseId) {
    $.ajax({
        url: 'api/expense-categories/process-recurring.php',
        method: 'POST',
        data: { id: expenseId },
        success: function(response) {
            if (response.success) {
                if (window.ksoToast) {
                    window.ksoToast.success('Recurring expense processed successfully!');
                }
                loadRecurringExpenses();
            } else {
                if (window.ksoToast) {
                    window.ksoToast.error('Error: ' + response.message);
                }
            }
        }
    });
}
</script>

</body>
</html>
