<?php
// filename: list_expenses.php
session_start();
include 'layouts/dbconn.php';
include 'layouts/session.php';
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}
$allowed_roles = ['SUPER_ADMIN', 'HOSPITAL_ADMIN', 'BILLING_CLERK', 'FINANCE_MANAGER'];
if (!in_array($_SESSION['role_code'], $allowed_roles)) {
    header('Location: dashboard.php');
    exit();
}
$user_id = $_SESSION['user_id'];
// Filters
$status_filter = $_GET['status'] ?? '';
$category_filter = $_GET['category'] ?? '';
$date_from = $_GET['date_from'] ?? date('Y-m-01');
$date_to = $_GET['date_to'] ?? date('Y-m-d');
// Build query for expense journals (journal_entries with lines in EXPENSE accounts)
$expense_sql = "SELECT je.*, u.full_name as posted_by_name,
                       (SELECT COUNT(*) FROM journal_entry_lines jel WHERE jel.journal_id = je.journal_id AND jel.account_id IN (SELECT ca.account_id FROM chart_of_accounts ca WHERE ca.account_type = 'EXPENSE')) as expense_line_count,
                       COALESCE((SELECT SUM(jel2.debit_amount) FROM journal_entry_lines jel2 WHERE jel2.journal_id = je.journal_id AND jel2.account_id IN (SELECT ca.account_id FROM chart_of_accounts ca WHERE ca.account_type = 'EXPENSE')), 0) as total_expense
                FROM journal_entries je
                LEFT JOIN users u ON je.posted_by = u.user_id
                WHERE je.entry_type IN ('MANUAL', 'AUTO_EXPENSE')";
$params = [];
$types = '';
if (!empty($status_filter)) {
    $expense_sql .= " AND je.status = ?";
    $params[] = $status_filter;
    $types .= 's';
}
if (!empty($category_filter)) {
    $expense_sql .= " AND je.journal_id IN (SELECT jel.journal_id FROM journal_entry_lines jel JOIN chart_of_accounts ca ON jel.account_id = ca.account_id WHERE ca.account_category = ?)";
    $params[] = $category_filter;
    $types .= 's';
}
$expense_sql .= " AND je.entry_date BETWEEN ? AND ?";
$params[] = $date_from;
$params[] = $date_to;
$types .= 'ss';
$expense_sql .= " GROUP BY je.journal_id HAVING expense_line_count > 0 ORDER BY je.entry_date DESC LIMIT 100";
$stmt = $conn->prepare($expense_sql);
if (!empty($params)) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$expense_result = $stmt->get_result();
// Fetch categories for filter (from chart_of_accounts.account_category where account_type = 'EXPENSE')
$cat_sql = "SELECT DISTINCT account_category FROM chart_of_accounts WHERE account_type = 'EXPENSE' AND account_category IS NOT NULL ORDER BY account_category";
$cat_result = $conn->query($cat_sql);
?>
<?php include 'layouts/main.php'; ?>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Expenses List')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
   
    <style>
        .expense-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            margin-bottom: 1rem;
        }
       
        .expense-header {
            padding: 1.5rem;
            border-bottom: 1px solid #e2e8f0;
            background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
            color: white;
            border-radius: 12px 12px 0 0;
        }
       
        .expense-entry {
            padding: 1rem 1.5rem;
            border-bottom: 1px solid #f1f5f9;
            transition: background 0.2s;
        }
       
        .expense-entry:hover {
            background: #f8fafc;
        }
       
        .expense-entry:last-child {
            border-bottom: none;
        }
       
        .expense-number {
            font-family: 'Courier New', monospace;
            font-weight: 600;
            font-size: 1.1rem;
            color: #1e293b;
        }
       
        .status-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 6px;
            font-size: 0.875rem;
            font-weight: 600;
        }
       
        .status-posted {
            background: #d1fae5;
            color: #065f46;
        }
       
        .status-draft {
            background: #fef3c7;
            color: #92400e;
        }
       
        .category-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 6px;
            font-size: 0.75rem;
            background: #e0e7ff;
            color: #3730a3;
        }
       
        .amount-display {
            font-weight: 700;
            font-size: 1.1rem;
            color: #dc2626;
        }
    </style>
</head>
<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
       
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">Expenses List</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
                                        <li class="breadcrumb-item active">Expenses</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>
                    <!-- Filters -->
                    <div class="expense-card">
                        <div class="expense-header">
                            <h5 class="mb-0"><i class="ri-filter-line me-2"></i>Filters</h5>
                        </div>
                        <div class="card-body">
                            <form method="GET" action="">
                                <div class="row">
                                    <div class="col-md-3 mb-3">
                                        <label class="form-label">Status</label>
                                        <select class="form-select" name="status">
                                            <option value="">All Statuses</option>
                                            <option value="DRAFT" <?php echo $status_filter === 'DRAFT' ? 'selected' : ''; ?>>Draft</option>
                                            <option value="POSTED" <?php echo $status_filter === 'POSTED' ? 'selected' : ''; ?>>Posted</option>
                                        </select>
                                    </div>
                                    <div class="col-md-3 mb-3">
                                        <label class="form-label">Category</label>
                                        <select class="form-select" name="category">
                                            <option value="">All Categories</option>
                                            <?php while ($cat = $cat_result->fetch_assoc()): ?>
                                            <option value="<?php echo htmlspecialchars($cat['account_category']); ?>" <?php echo $category_filter === $cat['account_category'] ? 'selected' : ''; ?>>
                                                <?php echo htmlspecialchars($cat['account_category']); ?>
                                            </option>
                                            <?php endwhile; ?>
                                        </select>
                                    </div>
                                    <div class="col-md-2 mb-3">
                                        <label class="form-label">From Date</label>
                                        <input type="date" class="form-control" name="date_from" value="<?php echo $date_from; ?>">
                                    </div>
                                    <div class="col-md-2 mb-3">
                                        <label class="form-label">To Date</label>
                                        <input type="date" class="form-control" name="date_to" value="<?php echo $date_to; ?>">
                                    </div>
                                    <div class="col-md-2 mb-3">
                                        <label class="form-label">&nbsp;</label>
                                        <button type="submit" class="btn btn-primary w-100">
                                            <i class="ri-search-line me-1"></i>Filter
                                        </button>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                    <!-- Expenses List -->
                    <div class="expense-card">
                        <div class="expense-header">
                            <div class="d-flex justify-content-between align-items-center">
                                <h5 class="mb-0"><i class="ri-file-list-3-line me-2"></i>Recorded Expenses</h5>
                                <a href="record_expense.php" class="btn btn-light btn-sm">
                                    <i class="ri-add-line me-1"></i>Record New Expense
                                </a>
                            </div>
                        </div>
                        <div class="card-body p-0">
                            <?php if ($expense_result->num_rows > 0): ?>
                                <?php while ($expense = $expense_result->fetch_assoc()): ?>
                                <div class="expense-entry">
                                    <div class="row align-items-center">
                                        <div class="col-md-2">
                                            <div class="expense-number"><?php echo htmlspecialchars($expense['journal_number']); ?></div>
                                            <small class="text-muted"><?php echo date('d M Y', strtotime($expense['entry_date'])); ?></small>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="fw-medium"><?php echo htmlspecialchars($expense['description']); ?></div>
                                            <div class="d-flex gap-2 mt-1">
                                                <span class="category-badge">
                                                    <?php echo htmlspecialchars($expense['entry_type']); ?>
                                                </span>
                                                <?php if ($expense['reference_type']): ?>
                                                <span class="badge bg-secondary">
                                                    <?php echo $expense['reference_type'] . ' #' . $expense['reference_id']; ?>
                                                </span>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                        <div class="col-md-2 text-center">
                                            <span class="status-badge status-<?php echo strtolower($expense['status']); ?>">
                                                <?php echo $expense['status']; ?>
                                            </span>
                                        </div>
                                        <div class="col-md-2 text-center">
                                            <div class="amount-display">
                                                KES <?php echo number_format($expense['total_expense'], 2); ?>
                                            </div>
                                            <small class="text-muted"><?php echo $expense['expense_line_count']; ?> lines</small>
                                        </div>
                                        <div class="col-md-2 text-end">
                                            <button class="btn btn-sm btn-outline-primary" onclick="viewExpense(<?php echo $expense['journal_id']; ?>)">
                                                <i class="ri-eye-line"></i> View
                                            </button>
                                        </div>
                                    </div>
                                </div>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <div class="text-center py-5">
                                    <i class="ri-file-line" style="font-size: 3rem; color: #cbd5e1;"></i>
                                    <p class="text-muted mt-2">No expenses found</p>
                                    <a href="record_expense.php" class="btn btn-primary mt-3">Record First Expense</a>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    <!-- Expense Details Modal -->
    <div class="modal fade" id="expenseDetailsModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Expense Details</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body" id="expenseDetailsContent">
                    <div class="text-center py-4">
                        <div class="spinner-border text-primary" role="status"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    <script src="assets/js/app.js"></script>
   
    <script>
    function viewExpense(journalId) {
        $('#expenseDetailsModal').modal('show');
       
        $.ajax({
            url: 'ajax/get_expense_details.php',
            method: 'GET',
            data: { journal_id: journalId },
            success: function(response) {
                $('#expenseDetailsContent').html(response);
            },
            error: function() {
                $('#expenseDetailsContent').html(
                    '<div class="alert alert-danger">Failed to load expense details</div>'
                );
            }
        });
    }
    </script>
</body>
</html>