<?php
require_once __DIR__ . '/../config/auth.php';
require_once __DIR__ . '/../includes/functions.php';
requirePermission('expense_management');

$pdo = getDB();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    if ($action === 'add' || $action === 'edit') {
        $id = (int)($_POST['id'] ?? 0);
        $cat_id = !empty($_POST['category_id']) ? (int)$_POST['category_id'] : null;
        $title = trim($_POST['title']);
        $amount = (float)$_POST['amount'];
        $expense_date = $_POST['expense_date'];
        $payment_method = $_POST['payment_method'];
        $notes = trim($_POST['notes']);

        if (empty($title) || $amount <= 0) {
            $_SESSION['error'] = 'Title and valid amount required.';
        } else {
            $description = $title . ($notes ? ' - ' . $notes : '');
            if ($action === 'add') {
                $stmt = $pdo->prepare("INSERT INTO expenses (expense_category_id, description, amount, expense_date, payment_method, created_by) VALUES (?,?,?,?,?,?)");
                $stmt->execute([$cat_id, $description, $amount, $expense_date, $payment_method, $_SESSION['user_id']]);
                $_SESSION['success'] = 'Expense added.';
            } else {
                $stmt = $pdo->prepare("UPDATE expenses SET expense_category_id=?, description=?, amount=?, expense_date=?, payment_method=? WHERE id=?");
                $stmt->execute([$cat_id, $description, $amount, $expense_date, $payment_method, $id]);
                $_SESSION['success'] = 'Expense updated.';
            }
        }
        header('Location: expenses.php'); exit;
    }
    if ($action === 'delete') {
        $stmt = $pdo->prepare("DELETE FROM expenses WHERE id=?");
        $stmt->execute([(int)$_POST['id']]);
        $_SESSION['success'] = 'Expense deleted.';
        header('Location: expenses.php'); exit;
    }
    if ($action === 'add_category') {
        $name = trim($_POST['name']);
        if ($name) {
            $stmt = $pdo->prepare("INSERT INTO expense_categories (category_name) VALUES (?)");
            $stmt->execute([$name]);
            $_SESSION['success'] = 'Category added.';
        }
        header('Location: expenses.php'); exit;
    }
}

$expenses = $pdo->query("SELECT e.*, ec.category_name as category_name, u.name as created_by_name FROM expenses e LEFT JOIN expense_categories ec ON e.expense_category_id = ec.id LEFT JOIN users u ON e.created_by = u.id ORDER BY e.id DESC")->fetchAll();
$categories = $pdo->query("SELECT * FROM expense_categories WHERE status=1 ORDER BY category_name")->fetchAll();

include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>
<div class="content-wrapper">
    <div class="container-fluid">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h4 class="page-title mb-0"><i class="fas fa-receipt me-2"></i>Expenses</h4>
            <div>
                <button class="btn btn-outline-primary" data-bs-toggle="modal" data-bs-target="#catModal"><i class="fas fa-folder-plus me-1"></i>Add Category</button>
                <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#expenseModal" onclick="resetExpenseForm()"><i class="fas fa-plus me-1"></i>Add Expense</button>
            </div>
        </div>
        <?php if (isset($_SESSION['success'])): ?><div class="alert alert-success alert-dismissible"><?= $_SESSION['success']; unset($_SESSION['success']); ?></div><?php endif; ?>
        <?php if (isset($_SESSION['error'])): ?><div class="alert alert-danger alert-dismissible"><?= $_SESSION['error']; unset($_SESSION['error']); ?></div><?php endif; ?>
        <div class="card">
            <div class="card-body">
                <div class="table-responsive">
                    <table id="expensesTable" class="table table-hover datatable">
                        <thead><tr><th>Date</th><th>Category</th><th>Title</th><th>Amount</th><th>Payment Method</th><th>Added By</th><th>Actions</th></tr></thead>
                        <tbody>
                            <?php foreach ($expenses as $e): ?>
                            <tr>
                                <td><?= formatDate($e['expense_date']) ?></td>
                                <td><span class="badge bg-secondary"><?= htmlspecialchars($e['category_name'] ?? 'Other') ?></span></td>
                                <td><?= htmlspecialchars($e['description']) ?></td>
                                <td><strong><?= formatCurrency($e['amount']) ?></strong></td>
                                <td><?= $e['payment_method'] ?></td>
                                <td><?= htmlspecialchars($e['created_by_name'] ?? '-') ?></td>
                                <td>
                                    <button class="btn btn-sm btn-info" onclick="editExpense(<?= htmlspecialchars(json_encode($e)) ?>)"><i class="fas fa-edit"></i></button>
                                    <form method="POST" style="display:inline;" onsubmit="return confirm('Delete this expense?');">
                                        <input type="hidden" name="action" value="delete">
                                        <input type="hidden" name="id" value="<?= $e['id'] ?>">
                                        <button type="submit" class="btn btn-sm btn-danger"><i class="fas fa-trash"></i></button>
                                    </form>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Expense Modal -->
<div class="modal fade" id="expenseModal" tabindex="-1">
    <div class="modal-dialog">
        <form method="POST" class="modal-content">
            <input type="hidden" name="action" id="expAction" value="add">
            <input type="hidden" name="id" id="expId" value="0">
            <div class="modal-header"><h5 class="modal-title" id="expModalTitle">Add Expense</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label">Category</label>
                    <select name="category_id" class="form-select">
                        <option value="">Select</option>
                        <?php foreach ($categories as $cat): ?>
                        <option value="<?= $cat['id'] ?>"><?= htmlspecialchars($cat['category_name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="mb-3">
                    <label class="form-label">Title *</label>
                    <input type="text" name="title" id="expTitle" class="form-control" required>
                </div>
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Amount *</label>
                        <input type="number" step="0.01" name="amount" id="expAmount" class="form-control" required>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Date</label>
                        <input type="date" name="expense_date" class="form-control" value="<?= date('Y-m-d') ?>">
                    </div>
                </div>
                <div class="mb-3">
                    <label class="form-label">Payment Method</label>
                    <select name="payment_method" class="form-select">
                        <option value="Cash">Cash</option>
                        <option value="Card">Card</option>
                        <option value="Bank Transfer">Bank Transfer</option>
                        <option value="Online Payment">Online Payment</option>
                    </select>
                </div>
                <div class="mb-3">
                    <label class="form-label">Notes</label>
                    <textarea name="notes" class="form-control" rows="2"></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="submit" class="btn btn-primary">Save</button>
            </div>
        </form>
    </div>
</div>

<!-- Category Modal -->
<div class="modal fade" id="catModal" tabindex="-1">
    <div class="modal-dialog">
        <form method="POST" class="modal-content">
            <input type="hidden" name="action" value="add_category">
            <div class="modal-header"><h5 class="modal-title">Add Expense Category</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label">Category Name *</label>
                    <input type="text" name="name" class="form-control" required>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="submit" class="btn btn-primary">Save</button>
            </div>
        </form>
    </div>
</div>

<script>
function resetExpenseForm() { $('#expAction').val('add');$('#expId').val(0);$('#expModalTitle').text('Add Expense');$('#expTitle, #expAmount').val(''); }
function editExpense(e) { $('#expAction').val('edit');$('#expId').val(e.id);$('#expModalTitle').text('Edit Expense');$('#expTitle').val(e.description);$('#expAmount').val(e.amount);$('#expenseModal').modal('show'); }
</script>
<?php include __DIR__ . '/../includes/footer.php'; ?>
