<?php
/**
 * Expenses List
 * LandSales Pro - Manage project expenses
 */
define('APP_RUNNING', true);
require_once '../../db_connect.php';
require_once '../../includes/auth.php';
require_once '../../includes/subscription.php';
require_once '../../includes/functions.php';

initSecureSession();
requireAuth();
requireSubscription();
requireViewPermission('expenses');

$userId = $_SESSION['user_id'];

// Search and filter
$search = $_GET['search'] ?? '';
$category = $_GET['category'] ?? '';
$projectId = $_GET['project_id'] ?? '';
$dateFrom = $_GET['date_from'] ?? '';
$dateTo = $_GET['date_to'] ?? '';

// Build query
$whereClause = "WHERE e.user_id = ?";
$params = [$userId];
$types = 'i';

if ($search) {
    $whereClause .= " AND (e.description LIKE ? OR e.vendor_name LIKE ? OR e.reference_number LIKE ?)";
    $searchTerm = "%{$search}%";
    $params[] = $searchTerm;
    $params[] = $searchTerm;
    $params[] = $searchTerm;
    $types .= 'sss';
}

if ($category) {
    $whereClause .= " AND e.category_id = ?";
    $params[] = $category;
    $types .= 'i';
}

if ($projectId) {
    $whereClause .= " AND e.project_id = ?";
    $params[] = $projectId;
    $types .= 'i';
}

if ($dateFrom) {
    $whereClause .= " AND e.expense_date >= ?";
    $params[] = $dateFrom;
    $types .= 's';
}

if ($dateTo) {
    $whereClause .= " AND e.expense_date <= ?";
    $params[] = $dateTo;
    $types .= 's';
}

// Pagination
$page = max(1, intval($_GET['page'] ?? 1));
$perPage = 20;
$offset = ($page - 1) * $perPage;

$total = db_fetch_one("SELECT COUNT(*) as count FROM expenses e {$whereClause}", $types, $params)['count'];
$totalPages = ceil($total / $perPage);

$expenses = db_fetch_all("SELECT e.*, p.name as project_name, c.name as category_name, c.color as category_color, c.icon as category_icon
    FROM expenses e
    LEFT JOIN projects p ON e.project_id = p.id
    LEFT JOIN expense_categories c ON e.category_id = c.id
    {$whereClause}
    ORDER BY e.expense_date DESC, e.created_at DESC
    LIMIT {$perPage} OFFSET {$offset}", $types, $params);

// Get projects for filter dropdown
$projects = db_fetch_all("SELECT id, name FROM projects WHERE user_id = ? ORDER BY name", 'i', [$userId]);

// Get totals for summary
$totalAmount = db_fetch_one("SELECT COALESCE(SUM(amount), 0) as total FROM expenses e {$whereClause}", $types, $params)['total'];

// Get dynamic categories from database
$categoriesData = db_fetch_all("SELECT * FROM expense_categories WHERE user_id = ? AND is_active = 1 ORDER BY sort_order, name", 'i', [$userId]);

// Build category lookup arrays
$categoryLabels = [];
$categoryColors = [];
$categoryIcons = [];
foreach ($categoriesData as $cat) {
    $categoryLabels[$cat['id']] = $cat['name'];
    $categoryColors[$cat['id']] = $cat['color'];
    $categoryIcons[$cat['id']] = $cat['icon'];
}

// Fallback for old enum-based categories (for backwards compatibility)
$legacyCategoryLabels = [
    'survey' => 'Survey', 'marketing' => 'Marketing', 'legal' => 'Legal',
    'infrastructure' => 'Infrastructure', 'utilities' => 'Utilities', 'staff' => 'Staff',
    'commission' => 'Commission', 'tax' => 'Tax', 'office' => 'Office',
    'transport' => 'Transport', 'other' => 'Other'
];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Expenses - <?php echo APP_NAME; ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="<?php echo SITE_URL; ?>/assets/font-awesome/css/all.min.css">
</head>
<body>
    <?php include '../includes/sidebar.php'; ?>

    <div class="main-content">
        <?php
        $pageTitle = 'Expenses';
        $headerActions = '';
        if (canManage('expenses')) {
            $headerActions = '<a href="categories.php" class="btn btn-outline"><i class="fas fa-tags"></i> Categories</a>
                <a href="create.php" class="btn btn-primary"><i class="fas fa-plus"></i> Add Expense</a>';
        }
        include '../includes/header.php';
        ?>

        <div class="content-wrapper">
            <!-- Summary Card -->
            <div class="summary-card">
                <div class="summary-stat">
                    <span class="stat-label">Total Expenses</span>
                    <span class="stat-value">TZS <?php echo number_format($totalAmount); ?></span>
                </div>
                <div class="summary-stat">
                    <span class="stat-label">Records</span>
                    <span class="stat-value"><?php echo number_format($total); ?></span>
                </div>
            </div>

            <!-- Filters -->
            <div class="filters-card">
                <form class="search-form" method="GET">
                    <div class="search-input">
                        <i class="fas fa-search"></i>
                        <input type="text" name="search" placeholder="Search description, vendor..."
                               value="<?php echo htmlspecialchars($search); ?>">
                    </div>
                    <select name="category" class="form-control-sm">
                        <option value="">All Categories</option>
                        <?php foreach ($categoriesData as $cat): ?>
                        <option value="<?php echo $cat['id']; ?>" <?php echo $category == $cat['id'] ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($cat['name']); ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                    <select name="project_id" class="form-control-sm">
                        <option value="">All Projects</option>
                        <?php foreach ($projects as $proj): ?>
                        <option value="<?php echo $proj['id']; ?>" <?php echo $projectId == $proj['id'] ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($proj['name']); ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                    <input type="date" name="date_from" class="form-control-sm" value="<?php echo $dateFrom; ?>" placeholder="From">
                    <input type="date" name="date_to" class="form-control-sm" value="<?php echo $dateTo; ?>" placeholder="To">
                    <button type="submit" class="btn btn-primary">Filter</button>
                    <?php if ($search || $category || $projectId || $dateFrom || $dateTo): ?>
                    <a href="index.php" class="btn btn-outline">Clear</a>
                    <?php endif; ?>
                </form>
            </div>

            <!-- Table -->
            <div class="card">
                <div class="table-responsive">
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th>Date</th>
                                <th>Description</th>
                                <th>Category</th>
                                <th>Project</th>
                                <th>Vendor</th>
                                <th>Amount</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($expenses)): ?>
                            <tr>
                                <td colspan="7" class="empty-row">
                                    <div class="empty-state">
                                        <i class="fas fa-receipt"></i>
                                        <p>No expenses found</p>
                                        <?php if (canManage('expenses')): ?>
                                        <a href="create.php" class="btn btn-primary btn-sm">Add First Expense</a>
                                        <?php endif; ?>
                                    </div>
                                </td>
                            </tr>
                            <?php else: ?>
                            <?php foreach ($expenses as $expense): ?>
                            <tr>
                                <td>
                                    <span class="date-cell"><?php echo date('M j, Y', strtotime($expense['expense_date'])); ?></span>
                                </td>
                                <td>
                                    <div class="description-cell">
                                        <span class="description-text"><?php echo htmlspecialchars($expense['description']); ?></span>
                                        <?php if ($expense['reference_number']): ?>
                                        <span class="ref-number">Ref: <?php echo htmlspecialchars($expense['reference_number']); ?></span>
                                        <?php endif; ?>
                                    </div>
                                </td>
                                <td>
                                    <?php if ($expense['category_name']): ?>
                                    <span class="category-badge" style="background-color: <?php echo $expense['category_color'] ?? '#64748b'; ?>20; color: <?php echo $expense['category_color'] ?? '#64748b'; ?>;">
                                        <i class="fas <?php echo $expense['category_icon'] ?? 'fa-tag'; ?>"></i>
                                        <?php echo htmlspecialchars($expense['category_name']); ?>
                                    </span>
                                    <?php elseif ($expense['category']): ?>
                                    <span class="category-badge category-<?php echo $expense['category']; ?>">
                                        <?php echo $legacyCategoryLabels[$expense['category']] ?? ucfirst($expense['category']); ?>
                                    </span>
                                    <?php else: ?>
                                    <span class="text-muted">-</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?php if ($expense['project_name']): ?>
                                    <span class="project-name"><?php echo htmlspecialchars($expense['project_name']); ?></span>
                                    <?php else: ?>
                                    <span class="text-muted">General</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?php if ($expense['vendor_name']): ?>
                                    <div class="vendor-cell">
                                        <span class="vendor-name"><?php echo htmlspecialchars($expense['vendor_name']); ?></span>
                                        <?php if ($expense['vendor_phone']): ?>
                                        <span class="vendor-phone"><?php echo htmlspecialchars($expense['vendor_phone']); ?></span>
                                        <?php endif; ?>
                                    </div>
                                    <?php else: ?>
                                    <span class="text-muted">-</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <span class="amount-cell">TZS <?php echo number_format($expense['amount']); ?></span>
                                </td>
                                <td>
                                    <div class="action-buttons">
                                        <a href="view.php?id=<?php echo $expense['id']; ?>" class="btn-icon" title="View">
                                            <i class="fas fa-eye"></i>
                                        </a>
                                        <?php if (canManage('expenses')): ?>
                                        <a href="edit.php?id=<?php echo $expense['id']; ?>" class="btn-icon" title="Edit">
                                            <i class="fas fa-edit"></i>
                                        </a>
                                        <?php endif; ?>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>

                <?php if ($totalPages > 1): ?>
                <div class="pagination-wrapper">
                    <div class="pagination">
                        <?php if ($page > 1): ?>
                        <a href="?page=<?php echo $page - 1; ?>&search=<?php echo urlencode($search); ?>&category=<?php echo urlencode($category); ?>&project_id=<?php echo urlencode($projectId); ?>&date_from=<?php echo urlencode($dateFrom); ?>&date_to=<?php echo urlencode($dateTo); ?>" class="page-link">
                            <i class="fas fa-chevron-left"></i>
                        </a>
                        <?php endif; ?>

                        <?php for ($i = max(1, $page - 2); $i <= min($totalPages, $page + 2); $i++): ?>
                        <a href="?page=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>&category=<?php echo urlencode($category); ?>&project_id=<?php echo urlencode($projectId); ?>&date_from=<?php echo urlencode($dateFrom); ?>&date_to=<?php echo urlencode($dateTo); ?>"
                           class="page-link <?php echo $i === $page ? 'active' : ''; ?>">
                            <?php echo $i; ?>
                        </a>
                        <?php endfor; ?>

                        <?php if ($page < $totalPages): ?>
                        <a href="?page=<?php echo $page + 1; ?>&search=<?php echo urlencode($search); ?>&category=<?php echo urlencode($category); ?>&project_id=<?php echo urlencode($projectId); ?>&date_from=<?php echo urlencode($dateFrom); ?>&date_to=<?php echo urlencode($dateTo); ?>" class="page-link">
                            <i class="fas fa-chevron-right"></i>
                        </a>
                        <?php endif; ?>
                    </div>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <style>
        body { font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif; margin: 0; background: #f1f5f9; }
        .header-actions { display: flex; gap: 0.75rem; }
        .btn { padding: 0.625rem 1.25rem; border-radius: 8px; font-weight: 500; text-decoration: none; display: inline-flex; align-items: center; gap: 0.5rem; transition: all 0.2s; border: none; cursor: pointer; font-size: 0.875rem; }
        .btn-sm { padding: 0.5rem 0.875rem; font-size: 0.8rem; }
        .btn-primary { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; }
        .btn-outline { border: 1px solid #e2e8f0; background: white; color: #64748b; }

        .summary-card { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 12px; padding: 1.5rem; margin-bottom: 1.5rem; display: flex; gap: 2rem; color: white; }
        .summary-stat { display: flex; flex-direction: column; }
        .stat-label { font-size: 0.875rem; opacity: 0.9; }
        .stat-value { font-size: 1.5rem; font-weight: 700; }

        .filters-card { background: white; border-radius: 10px; padding: 1rem; margin-bottom: 1.5rem; box-shadow: 0 2px 8px rgba(0,0,0,0.05); }
        .search-form { display: flex; gap: 0.75rem; flex-wrap: wrap; align-items: center; }
        .search-input { position: relative; flex: 1; min-width: 200px; box-sizing: border-box; }
        .search-input i { position: absolute; left: 1rem; top: 50%; transform: translateY(-50%); color: #94a3b8; }
        .search-input input { width: 100%; padding: 0.625rem 1rem 0.625rem 2.5rem; border: 1px solid #e2e8f0; border-radius: 8px; font-size: 0.875rem; box-sizing: border-box; }
        .search-input input:focus { outline: none; border-color: #667eea; }
        .form-control-sm { padding: 0.625rem 1rem; border: 1px solid #e2e8f0; border-radius: 8px; font-size: 0.875rem; min-width: 130px; }

        .card { background: white; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.05); overflow: hidden; }
        .table-responsive { overflow-x: auto; }
        .data-table { width: 100%; border-collapse: collapse; }
        .data-table th, .data-table td { padding: 1rem; text-align: left; border-bottom: 1px solid #f1f5f9; }
        .data-table th { background: #f8fafc; font-weight: 600; font-size: 0.75rem; text-transform: uppercase; letter-spacing: 0.5px; color: #64748b; }
        .data-table tbody tr:hover { background: #f8fafc; }

        .date-cell { color: #1e293b; font-weight: 500; }
        .description-cell { display: flex; flex-direction: column; gap: 0.25rem; }
        .description-text { color: #1e293b; font-weight: 500; }
        .ref-number { font-size: 0.75rem; color: #94a3b8; }

        .category-badge { padding: 0.25rem 0.625rem; border-radius: 20px; font-size: 0.75rem; font-weight: 500; }
        .category-survey { background: #dbeafe; color: #1e40af; }
        .category-marketing { background: #fce7f3; color: #9d174d; }
        .category-legal { background: #e0e7ff; color: #4338ca; }
        .category-infrastructure { background: #fef3c7; color: #92400e; }
        .category-utilities { background: #ccfbf1; color: #0f766e; }
        .category-staff { background: #f3e8ff; color: #7c3aed; }
        .category-commission { background: #d1fae5; color: #059669; }
        .category-tax { background: #fee2e2; color: #991b1b; }
        .category-office { background: #e2e8f0; color: #475569; }
        .category-transport { background: #fed7aa; color: #c2410c; }
        .category-other { background: #f1f5f9; color: #64748b; }

        .project-name { color: #1e293b; font-weight: 500; }
        .vendor-cell { display: flex; flex-direction: column; gap: 0.125rem; }
        .vendor-name { color: #1e293b; }
        .vendor-phone { font-size: 0.75rem; color: #94a3b8; }
        .amount-cell { color: #dc2626; font-weight: 600; }
        .text-muted { color: #94a3b8; }

        .action-buttons { display: flex; gap: 0.5rem; }
        .btn-icon { width: 32px; height: 32px; border-radius: 8px; display: flex; align-items: center; justify-content: center; color: #64748b; background: #f1f5f9; text-decoration: none; transition: all 0.2s; }
        .btn-icon:hover { background: #667eea; color: white; }

        .empty-row td { padding: 3rem; }
        .empty-state { text-align: center; color: #94a3b8; }
        .empty-state i { font-size: 2rem; margin-bottom: 0.5rem; }

        .pagination-wrapper { padding: 1rem; border-top: 1px solid #f1f5f9; display: flex; justify-content: center; }
        .pagination { display: flex; gap: 0.25rem; }
        .page-link { padding: 0.5rem 0.75rem; border-radius: 6px; text-decoration: none; color: #64748b; font-weight: 500; }
        .page-link:hover { background: #f1f5f9; }
        .page-link.active { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; }

        @media (max-width: 768px) {
            .summary-card { flex-direction: column; gap: 1rem; }
            .search-form { flex-direction: column; }
            .search-input, .form-control-sm { width: 100%; min-width: auto; }
        }
    </style>
</body>
</html>
