<?php
require_once 'config/database.php';
requireAdmin();

require_once 'templates/header.php';
require_once 'templates/navbar.php';
require_once '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">Expense Categories</h1>
                </div>
                <div class="col-sm-6">
                    <ol class="breadcrumb float-sm-right">
                        <li class="breadcrumb-item"><a href="index.php">Home</a></li>
                        <li class="breadcrumb-item"><a href="finance.php">Finance</a></li>
                        <li class="breadcrumb-item active">Expense Categories</li>
                    </ol>
                </div>
            </div>
        </div>
    </div>

    <!-- Main content -->
    <section class="content">
        <div class="container-fluid">
            <div class="row">
                <div class="col-md-4">
                    <!-- Add New Category -->
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Add New Category</h3>
                        </div>
                        <form id="addCategoryForm">
                            <div class="card-body">
                                <div class="form-group">
                                    <label>Category Name *</label>
                                    <input type="text" class="form-control" name="category_name" required>
                                </div>
                                <div class="form-group">
                                    <label>Description</label>
                                    <textarea class="form-control" name="description" rows="3"></textarea>
                                </div>
                                <div class="form-group">
                                    <label>Category Type</label>
                                    <select class="form-control" name="category_type">
                                        <option value="expense">Expense</option>
                                        <option value="income">Income</option>
                                    </select>
                                </div>
                                <div class="form-group">
                                    <label>Budget Limit (Optional)</label>
                                    <input type="number" class="form-control" name="budget_limit" step="0.01">
                                </div>
                                <div class="form-group">
                                    <label>Icon Color</label>
                                    <input type="color" class="form-control" name="icon_color" value="#007bff">
                                </div>
                                <div class="form-group">
                                    <div class="custom-control custom-switch">
                                        <input type="checkbox" class="custom-control-input" id="isActive" name="is_active" checked>
                                        <label class="custom-control-label" for="isActive">Active</label>
                                    </div>
                                </div>
                            </div>
                            <div class="card-footer">
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-plus"></i> Add Category
                                </button>
                            </div>
                        </form>
                    </div>

                    <!-- Category Statistics -->
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Category Statistics</h3>
                        </div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-6">
                                    <div class="description-block border-right">
                                        <span class="description-percentage text-success">
                                            <i class="fas fa-caret-up"></i> 
                                            <span id="totalExpenseCategories">0</span>
                                        </span>
                                        <h5 class="description-header">Expense Categories</h5>
                                    </div>
                                </div>
                                <div class="col-6">
                                    <div class="description-block">
                                        <span class="description-percentage text-warning">
                                            <i class="fas fa-caret-up"></i> 
                                            <span id="totalIncomeCategories">0</span>
                                        </span>
                                        <h5 class="description-header">Income Categories</h5>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="col-md-8">
                    <!-- Categories Table -->
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Expense Categories</h3>
                            <div class="card-tools">
                                <div class="input-group input-group-sm" style="width: 150px;">
                                    <input type="text" id="searchCategories" class="form-control" placeholder="Search...">
                                    <div class="input-group-append">
                                        <button type="button" class="btn btn-default">
                                            <i class="fas fa-search"></i>
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="card-body table-responsive p-0">
                            <table class="table table-hover text-nowrap" id="categoriesTable">
                                <thead>
                                    <tr>
                                        <th>Category</th>
                                        <th>Type</th>
                                        <th>Budget Limit</th>
                                        <th>Current Usage</th>
                                        <th>Status</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <!-- Categories will be populated here -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Budget Overview -->
            <div class="row">
                <div class="col-md-12">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Budget Overview</h3>
                        </div>
                        <div class="card-body">
                            <div class="row" id="budgetOverview">
                                <!-- Budget cards will be populated here -->
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
</div>

<!-- Edit Category Modal -->
<div class="modal fade" id="editCategoryModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Edit Category</h4>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <form id="editCategoryForm">
                <div class="modal-body">
                    <input type="hidden" name="category_id" id="edit_category_id">
                    <div class="form-group">
                        <label>Category Name *</label>
                        <input type="text" class="form-control" name="category_name" required>
                    </div>
                    <div class="form-group">
                        <label>Description</label>
                        <textarea class="form-control" name="description" rows="3"></textarea>
                    </div>
                    <div class="form-group">
                        <label>Category Type</label>
                        <select class="form-control" name="category_type">
                            <option value="expense">Expense</option>
                            <option value="income">Income</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Budget Limit (Optional)</label>
                        <input type="number" class="form-control" name="budget_limit" step="0.01">
                    </div>
                    <div class="form-group">
                        <label>Icon Color</label>
                        <input type="color" class="form-control" name="icon_color">
                    </div>
                    <div class="form-group">
                        <div class="custom-control custom-switch">
                            <input type="checkbox" class="custom-control-input" id="editIsActive" name="is_active">
                            <label class="custom-control-label" for="editIsActive">Active</label>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                    <button type="submit" class="btn btn-primary">Update Category</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Budget Alert Modal -->
<div class="modal fade" id="budgetAlertModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Budget Alert Settings</h4>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <form id="budgetAlertForm">
                <div class="modal-body">
                    <input type="hidden" name="category_id" id="alert_category_id">
                    <div class="form-group">
                        <label>Alert Threshold (%)</label>
                        <input type="number" class="form-control" name="alert_threshold" min="1" max="100" value="80">
                        <small class="form-text text-muted">Alert when spending reaches this percentage of budget</small>
                    </div>
                    <div class="form-group">
                        <div class="custom-control custom-switch">
                            <input type="checkbox" class="custom-control-input" id="emailAlerts" name="email_alerts" checked>
                            <label class="custom-control-label" for="emailAlerts">Email Alerts</label>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="custom-control custom-switch">
                            <input type="checkbox" class="custom-control-input" id="dashboardAlerts" name="dashboard_alerts" checked>
                            <label class="custom-control-label" for="dashboardAlerts">Dashboard Alerts</label>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                    <button type="submit" class="btn btn-primary">Save Alert Settings</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    loadCategories();
    loadStatistics();
    loadBudgetOverview();
    
    // Search functionality
    $('#searchCategories').on('input', function() {
        loadCategories();
    });
});

function loadCategories() {
    const search = $('#searchCategories').val();
    
    $.ajax({
        url: 'api/finance/fetch_expense_categories.php',
        type: 'GET',
        data: { search: search },
        success: function(response) {
            if (response.success) {
                let html = '';
                response.categories.forEach(function(category) {
                    const usage = category.current_usage || 0;
                    const limit = category.budget_limit || 0;
                    const percentage = limit > 0 ? (usage / limit * 100).toFixed(1) : 0;
                    const progressClass = percentage > 80 ? 'danger' : percentage > 60 ? 'warning' : 'success';
                    
                    html += `
                        <tr>
                            <td>
                                <div class="d-flex align-items-center">
                                    <div class="mr-2" style="width: 20px; height: 20px; background-color: ${category.icon_color}; border-radius: 3px;"></div>
                                    <div>
                                        <strong>${category.category_name}</strong>
                                        <br><small class="text-muted">${category.description || 'No description'}</small>
                                    </div>
                                </div>
                            </td>
                            <td>
                                <span class="badge badge-${category.category_type === 'expense' ? 'danger' : 'success'}">
                                    ${category.category_type.charAt(0).toUpperCase() + category.category_type.slice(1)}
                                </span>
                            </td>
                            <td>${limit > 0 ? '₹' + limit.toLocaleString() : 'No limit'}</td>
                            <td>
                                <div>
                                    ₹${usage.toLocaleString()}
                                    ${limit > 0 ? `
                                        <div class="progress" style="height: 5px;">
                                            <div class="progress-bar bg-${progressClass}" style="width: ${percentage}%"></div>
                                        </div>
                                        <small class="text-muted">${percentage}% used</small>
                                    ` : ''}
                                </div>
                            </td>
                            <td>
                                <span class="badge badge-${category.is_active ? 'success' : 'secondary'}">
                                    ${category.is_active ? 'Active' : 'Inactive'}
                                </span>
                            </td>
                            <td>
                                <div class="btn-group btn-group-sm">
                                    <button class="btn btn-outline-primary" onclick="editCategory(${category.id})">
                                        <i class="fas fa-edit"></i>
                                    </button>
                                    <button class="btn btn-outline-info" onclick="setBudgetAlert(${category.id})">
                                        <i class="fas fa-bell"></i>
                                    </button>
                                    <button class="btn btn-outline-success" onclick="viewCategoryReport(${category.id})">
                                        <i class="fas fa-chart-line"></i>
                                    </button>
                                    <button class="btn btn-outline-danger" onclick="deleteCategory(${category.id})">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </div>
                            </td>
                        </tr>
                    `;
                });
                
                $('#categoriesTable tbody').html(html);
            }
        }
    });
}

function loadStatistics() {
    $.ajax({
        url: 'api/finance/fetch_category_statistics.php',
        type: 'GET',
        success: function(response) {
            if (response.success) {
                $('#totalExpenseCategories').text(response.stats.expense_categories);
                $('#totalIncomeCategories').text(response.stats.income_categories);
            }
        }
    });
}

function loadBudgetOverview() {
    $.ajax({
        url: 'api/finance/fetch_budget_overview.php',
        type: 'GET',
        success: function(response) {
            if (response.success) {
                let html = '';
                response.budgets.forEach(function(budget) {
                    const percentage = budget.budget_limit > 0 ? (budget.current_usage / budget.budget_limit * 100).toFixed(1) : 0;
                    const progressClass = percentage > 80 ? 'danger' : percentage > 60 ? 'warning' : 'success';
                    
                    html += `
                        <div class="col-md-4 mb-3">
                            <div class="card">
                                <div class="card-body">
                                    <div class="d-flex justify-content-between">
                                        <h5 class="card-title">${budget.category_name}</h5>
                                        <span class="badge badge-${progressClass}">${percentage}%</span>
                                    </div>
                                    <div class="progress mb-2" style="height: 10px;">
                                        <div class="progress-bar bg-${progressClass}" style="width: ${percentage}%"></div>
                                    </div>
                                    <div class="d-flex justify-content-between">
                                        <span>₹${budget.current_usage.toLocaleString()}</span>
                                        <span>₹${budget.budget_limit.toLocaleString()}</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    `;
                });
                
                $('#budgetOverview').html(html);
            }
        }
    });
}

function editCategory(categoryId) {
    $.ajax({
        url: 'api/fetch_expense_category.php',
        type: 'GET',
        data: { id: categoryId },
        success: function(response) {
            if (response.success) {
                const category = response.category;
                
                $('#edit_category_id').val(category.id);
                $('#editCategoryForm input[name="category_name"]').val(category.category_name);
                $('#editCategoryForm textarea[name="description"]').val(category.description);
                $('#editCategoryForm select[name="category_type"]').val(category.category_type);
                $('#editCategoryForm input[name="budget_limit"]').val(category.budget_limit);
                $('#editCategoryForm input[name="icon_color"]').val(category.icon_color);
                $('#editIsActive').prop('checked', category.is_active == 1);
                
                $('#editCategoryModal').modal('show');
            }
        }
    });
}

function setBudgetAlert(categoryId) {
    $('#alert_category_id').val(categoryId);
    $('#budgetAlertModal').modal('show');
}

function viewCategoryReport(categoryId) {
    window.location.href = `category-report.php?id=${categoryId}`;
}

function deleteCategory(categoryId) {
    if (confirm('Are you sure you want to delete this category? This action cannot be undone.')) {
        $.ajax({
            url: 'api/delete_expense_category.php',
            type: 'POST',
            data: { category_id: categoryId },
            success: function(response) {
                if (response.success) {
                    toastr.success('Category deleted successfully');
                    loadCategories();
                    loadStatistics();
                } else {
                    toastr.error(response.message);
                }
            }
        });
    }
}

// Form submissions
$('#addCategoryForm').on('submit', function(e) {
    e.preventDefault();
    
    $.ajax({
        url: 'api/create_expense_category.php',
        type: 'POST',
        data: $(this).serialize(),
        success: function(response) {
            if (response.success) {
                toastr.success('Category created successfully');
                $('#addCategoryForm')[0].reset();
                $('#isActive').prop('checked', true);
                loadCategories();
                loadStatistics();
                loadBudgetOverview();
            } else {
                toastr.error(response.message);
            }
        }
    });
});

$('#editCategoryForm').on('submit', function(e) {
    e.preventDefault();
    
    $.ajax({
        url: 'api/update_expense_category.php',
        type: 'POST',
        data: $(this).serialize(),
        success: function(response) {
            if (response.success) {
                toastr.success('Category updated successfully');
                $('#editCategoryModal').modal('hide');
                loadCategories();
                loadBudgetOverview();
            } else {
                toastr.error(response.message);
            }
        }
    });
});

$('#budgetAlertForm').on('submit', function(e) {
    e.preventDefault();
    
    $.ajax({
        url: 'api/save_budget_alert.php',
        type: 'POST',
        data: $(this).serialize(),
        success: function(response) {
            if (response.success) {
                toastr.success('Budget alert settings saved');
                $('#budgetAlertModal').modal('hide');
            } else {
                toastr.error(response.message);
            }
        }
    });
});
</script>

<?php require_once 'templates/footer.php'; ?>
