<?php
session_start();
include 'layouts/dbconn.php';

// Set timezone to East Africa Time
date_default_timezone_set('Africa/Nairobi');

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Fetch user details
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT u.*, ur.role_name FROM users u 
                     INNER JOIN user_roles ur ON u.role_id = ur.role_id 
                     WHERE u.user_id = ?";
$stmt_user = $conn->prepare($sql_user_details);
$stmt_user->bind_param("i", $user_id);
$stmt_user->execute();
$user_details = $stmt_user->get_result()->fetch_assoc();

if ($user_details) {
    $username = $user_details['username'];
    $role_name = $user_details['role_name'];
    $full_name = $user_details['full_name'];
    $email = $user_details['email'];
}

// Get search parameters
$search = $_GET['search'] ?? '';
$shop_filter = $_GET['shop_filter'] ?? '';
$status_filter = $_GET['status_filter'] ?? '';
$date_from = $_GET['date_from'] ?? '';
$date_to = $_GET['date_to'] ?? '';
$page = $_GET['page'] ?? 1;
$limit = 20;
$offset = ($page - 1) * $limit;

// Build query with filters for SHOP category type only
$where_conditions = array("ec.category_type = 'SHOP'");
$params = array();
$param_types = "";

if (!empty($search)) {
    $where_conditions[] = "(e.expense_title LIKE ? OR e.description LIKE ? OR e.expense_number LIKE ? OR e.vendor_name LIKE ?)";
    $search_param = "%$search%";
    $params = array_merge($params, [$search_param, $search_param, $search_param, $search_param]);
    $param_types .= "ssss";
}

if (!empty($shop_filter)) {
    $where_conditions[] = "e.category_id = ?";
    $params[] = $shop_filter;
    $param_types .= "i";
}

if (!empty($status_filter)) {
    $where_conditions[] = "e.status = ?";
    $params[] = $status_filter;
    $param_types .= "s";
}

if (!empty($date_from)) {
    $where_conditions[] = "e.expense_date >= ?";
    $params[] = $date_from;
    $param_types .= "s";
}

if (!empty($date_to)) {
    $where_conditions[] = "e.expense_date <= ?";
    $params[] = $date_to;
    $param_types .= "s";
}

$where_clause = implode(" AND ", $where_conditions);

// Get total count for pagination
$count_query = "SELECT COUNT(*) as total FROM expenses e 
                LEFT JOIN expense_categories ec ON e.category_id = ec.category_id 
                WHERE $where_clause";
$count_stmt = $conn->prepare($count_query);
if (!empty($params)) {
    $count_stmt->bind_param($param_types, ...$params);
}
$count_stmt->execute();
$total_expenses = $count_stmt->get_result()->fetch_assoc()['total'];
$total_pages = ceil($total_expenses / $limit);

// Get shop expenses with pagination
$query = "SELECT e.*, ec.category_name, ec.category_type, ec.color_code,
                 u_created.full_name as created_by_name,
                 u_approved.full_name as approved_by_name
          FROM expenses e 
          LEFT JOIN expense_categories ec ON e.category_id = ec.category_id 
          LEFT JOIN users u_created ON e.created_by = u_created.user_id 
          LEFT JOIN users u_approved ON e.approved_by = u_approved.user_id 
          WHERE $where_clause
          ORDER BY e.expense_date DESC, e.created_at DESC 
          LIMIT ? OFFSET ?";

$stmt = $conn->prepare($query);
$params[] = $limit;
$params[] = $offset;
$param_types .= "ii";

if (!empty($params)) {
    $stmt->bind_param($param_types, ...$params);
}
$stmt->execute();
$expenses = $stmt->get_result();

// Get shop categories for filter dropdown
$shop_categories_query = "SELECT * FROM expense_categories WHERE category_type = 'SHOP' AND is_active = 1 ORDER BY category_name";
$shop_categories_result = $conn->query($shop_categories_query);

// Get shop expense statistics
$stats_query = "SELECT 
    COUNT(*) as total_count,
    SUM(CASE WHEN status = 'PAID' THEN amount ELSE 0 END) as total_paid,
    SUM(CASE WHEN status = 'PENDING' THEN amount ELSE 0 END) as total_pending,
    SUM(CASE WHEN DATE(expense_date) = CURDATE() THEN amount ELSE 0 END) as today_total,
    SUM(CASE WHEN YEAR(expense_date) = YEAR(CURDATE()) AND MONTH(expense_date) = MONTH(CURDATE()) AND status = 'PAID' THEN amount ELSE 0 END) as month_total,
    COUNT(CASE WHEN status = 'PENDING' THEN 1 END) as pending_count
    FROM expenses e 
    LEFT JOIN expense_categories ec ON e.category_id = ec.category_id
    WHERE ec.category_type = 'SHOP'";
$stats = $conn->query($stats_query)->fetch_assoc();

// Get individual shop totals
$shop_totals_query = "SELECT 
    ec.category_name,
    COUNT(e.expense_id) as count,
    SUM(CASE WHEN e.status = 'PAID' THEN e.amount ELSE 0 END) as total_amount,
    SUM(CASE WHEN YEAR(e.expense_date) = YEAR(CURDATE()) AND MONTH(e.expense_date) = MONTH(CURDATE()) AND e.status = 'PAID' THEN e.amount ELSE 0 END) as month_amount
    FROM expense_categories ec
    LEFT JOIN expenses e ON ec.category_id = e.category_id
    WHERE ec.category_type = 'SHOP' AND ec.is_active = 1
    GROUP BY ec.category_id, ec.category_name
    ORDER BY total_amount DESC";
$shop_totals = $conn->query($shop_totals_query);
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Shop Expenses - Personal Fund Management System')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <style>
        /* Use the same styling as list_expenses.php with shop-specific colors */
        body {
            background-color: #f8fafc;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        }
        
        .page-content {
            padding: 1.5rem;
        }
        
        /* Page Header - Shop themed */
        .page-header {
            background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%);
            color: white;
            border-radius: 12px;
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .page-title {
            font-size: 1.75rem;
            font-weight: 600;
            margin-bottom: 0.5rem;
        }
        
        .page-subtitle {
            opacity: 0.9;
            margin: 0;
        }
        
        /* Filter Card */
        .filter-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            margin-bottom: 2rem;
        }
        
        /* Stats Cards */
        .stats-row {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1.5rem;
            margin-bottom: 2rem;
        }
        
        .stat-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            text-align: center;
        }
        
        .stat-value {
            font-size: 2rem;
            font-weight: 700;
            color: #1e293b;
            margin-bottom: 0.5rem;
        }
        
        .stat-label {
            font-size: 0.875rem;
            color: #64748b;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }
        
        /* Shop Breakdown */
        .shop-breakdown {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            margin-bottom: 2rem;
        }
        
        .shop-item {
            display: flex;
            justify-content: between;
            align-items: center;
            padding: 1rem;
            border-bottom: 1px solid #f1f5f9;
        }
        
        .shop-item:last-child {
            border-bottom: none;
        }
        
        .shop-name {
            font-weight: 600;
            color: #1e293b;
        }
        
        .shop-stats {
            display: flex;
            gap: 1rem;
            font-size: 0.875rem;
            color: #64748b;
        }
        
        .shop-amount {
            font-weight: 600;
            color: #e74c3c;
        }
        
        /* Table Card */
        .table-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            overflow: hidden;
            margin-bottom: 2rem;
        }
        
        .table-header {
            padding: 1.5rem;
            border-bottom: 1px solid #e2e8f0;
            background: #f8fafc;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .table-title {
            font-size: 1.125rem;
            font-weight: 600;
            color: #1e293b;
            margin: 0;
        }
        
        .data-table {
            width: 100%;
            border-collapse: collapse;
            margin: 0;
        }
        
        .data-table th {
            background: #f8fafc;
            padding: 1rem;
            text-align: left;
            font-weight: 600;
            font-size: 0.875rem;
            color: #64748b;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .data-table td {
            padding: 1rem;
            border-bottom: 1px solid #f1f5f9;
            font-size: 0.875rem;
        }
        
        .data-table tbody tr:hover {
            background: #f8fafc;
        }
        
        /* Status Badges */
        .status-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }
        
        .status-draft { background: #f1f5f9; color: #64748b; }
        .status-pending { background: #fef3c7; color: #92400e; }
        .status-approved { background: #dcfce7; color: #166534; }
        .status-paid { background: #dcfce7; color: #166534; }
        .status-rejected { background: #fee2e2; color: #991b1b; }
        .status-cancelled { background: #fee2e2; color: #991b1b; }
        
        /* Payment Method Badges */
        .payment-badge {
            padding: 0.25rem 0.5rem;
            border-radius: 4px;
            font-size: 0.75rem;
            font-weight: 500;
        }
        
        .payment-cash { background: #dcfce7; color: #166534; }
        .payment-card { background: #ddd6fe; color: #5b21b6; }
        .payment-bank-transfer { background: #e0e7ff; color: #3730a3; }
        .payment-mpesa { background: #fef3c7; color: #92400e; }
        .payment-mobile-money { background: #fef3c7; color: #92400e; }
        .payment-cheque { background: #f3e8ff; color: #7c3aed; }
        
        /* Action Buttons */
        .btn-action {
            padding: 0.375rem 0.75rem;
            border-radius: 6px;
            font-size: 0.75rem;
            font-weight: 600;
            text-decoration: none;
            display: inline-block;
            margin: 0 0.25rem;
            transition: all 0.2s ease;
        }
        
        .btn-primary { background: #3b82f6; color: white; }
        .btn-primary:hover { background: #1d4ed8; color: white; }
        
        .btn-success { background: #059669; color: white; }
        .btn-success:hover { background: #047857; color: white; }
        
        .btn-warning { background: #d97706; color: white; }
        .btn-warning:hover { background: #b45309; color: white; }
        
        .btn-danger { background: #dc2626; color: white; }
        .btn-danger:hover { background: #b91c1c; color: white; }
        
        .btn-shop { background: #e74c3c; color: white; }
        .btn-shop:hover { background: #c0392b; color: white; }
        
        /* Pagination */
        .pagination-wrapper {
            padding: 1.5rem;
            background: #f8fafc;
            border-top: 1px solid #e2e8f0;
            display: flex;
            justify-content: between;
            align-items: center;
            flex-wrap: wrap;
            gap: 1rem;
        }
        
        .pagination-info {
            color: #64748b;
            font-size: 0.875rem;
        }
        
        .pagination {
            display: flex;
            gap: 0.5rem;
            margin: 0;
        }
        
        .page-link {
            padding: 0.5rem 0.75rem;
            background: white;
            border: 1px solid #e2e8f0;
            color: #374151;
            text-decoration: none;
            border-radius: 6px;
            font-size: 0.875rem;
        }
        
        .page-link:hover {
            background: #f8fafc;
            border-color: #3b82f6;
            color: #3b82f6;
        }
        
        .page-link.active {
            background: #3b82f6;
            border-color: #3b82f6;
            color: white;
        }
        
        /* Form Controls */
        .form-control, .form-select {
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 0.75rem;
            font-size: 0.875rem;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: #e74c3c;
            box-shadow: 0 0 0 3px rgba(231, 76, 60, 0.1);
        }
        
        .btn {
            padding: 0.75rem 1.5rem;
            border-radius: 8px;
            font-weight: 600;
            font-size: 0.875rem;
            border: none;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .btn-primary {
            background: #3b82f6;
            color: white;
        }
        
        .btn-primary:hover {
            background: #1d4ed8;
        }
        
        .btn-outline-secondary {
            background: transparent;
            border: 1px solid #e2e8f0;
            color: #64748b;
        }
        
        .btn-outline-secondary:hover {
            background: #f8fafc;
            border-color: #64748b;
        }
        
        /* Expense Avatar */
        .expense-avatar {
            width: 40px;
            height: 40px;
            border-radius: 8px;
            background: #e74c3c;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            font-size: 0.875rem;
        }
        
        /* Responsive */
        @media (max-width: 768px) {
            .page-content {
                padding: 1rem;
            }
            
            .stats-row {
                grid-template-columns: 1fr;
            }
            
            .table-header {
                flex-direction: column;
                gap: 1rem;
                align-items: stretch;
            }
            
            .data-table {
                font-size: 0.75rem;
            }
            
            .data-table th,
            .data-table td {
                padding: 0.5rem;
            }
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <!-- Page Header -->
                    <div class="page-header">
                        <h1 class="page-title">Shop Expenses</h1>
                        <p class="page-subtitle">Track and manage expenses for Shop 1 and Shop 2 operations</p>
                    </div>

                    <!-- Stats Row -->
                    <div class="stats-row">
                        <div class="stat-card">
                            <div class="stat-value"><?php echo $stats['total_count'] ?? 0; ?></div>
                            <div class="stat-label">Total Shop Expenses</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value">KES <?php echo number_format($stats['total_paid'] ?? 0); ?></div>
                            <div class="stat-label">Total Paid</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value">KES <?php echo number_format($stats['month_total'] ?? 0); ?></div>
                            <div class="stat-label">This Month</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value"><?php echo $stats['pending_count'] ?? 0; ?></div>
                            <div class="stat-label">Pending</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value">KES <?php echo number_format($stats['today_total'] ?? 0); ?></div>
                            <div class="stat-label">Today</div>
                        </div>
                    </div>

                    <!-- Shop Breakdown -->
                    <div class="shop-breakdown">
                        <h3 style="margin-bottom: 1.5rem; color: #1e293b; font-weight: 600;">Shop Expense Breakdown</h3>
                        <?php while ($shop = $shop_totals->fetch_assoc()): ?>
                        <div class="shop-item">
                            <div>
                                <div class="shop-name"><?php echo htmlspecialchars($shop['category_name']); ?></div>
                                <div class="shop-stats">
                                    <span><?php echo $shop['count']; ?> expenses</span>
                                    <span>This month: KES <?php echo number_format($shop['month_amount']); ?></span>
                                </div>
                            </div>
                            <div class="shop-amount">
                                KES <?php echo number_format($shop['total_amount']); ?>
                            </div>
                        </div>
                        <?php endwhile; ?>
                    </div>

                    <!-- Filter Card -->
                    <div class="filter-card">
                        <form method="GET" class="row g-3">
                            <div class="col-md-3">
                                <label class="form-label">Search</label>
                                <input type="text" class="form-control" name="search" value="<?php echo htmlspecialchars($search); ?>" placeholder="Search shop expenses...">
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">Shop Category</label>
                                <select class="form-select" name="shop_filter">
                                    <option value="">All Shops</option>
                                    <?php 
                                    $shop_categories_result->data_seek(0);
                                    while ($shop = $shop_categories_result->fetch_assoc()): 
                                    ?>
                                        <option value="<?php echo $shop['category_id']; ?>" <?php echo $shop_filter == $shop['category_id'] ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($shop['category_name']); ?>
                                        </option>
                                    <?php endwhile; ?>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label class="form-label">Status</label>
                                <select class="form-select" name="status_filter">
                                    <option value="">All Status</option>
                                    <option value="DRAFT" <?php echo $status_filter == 'DRAFT' ? 'selected' : ''; ?>>Draft</option>
                                    <option value="PENDING" <?php echo $status_filter == 'PENDING' ? 'selected' : ''; ?>>Pending</option>
                                    <option value="APPROVED" <?php echo $status_filter == 'APPROVED' ? 'selected' : ''; ?>>Approved</option>
                                    <option value="PAID" <?php echo $status_filter == 'PAID' ? 'selected' : ''; ?>>Paid</option>
                                    <option value="REJECTED" <?php echo $status_filter == 'REJECTED' ? 'selected' : ''; ?>>Rejected</option>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label class="form-label">From Date</label>
                                <input type="date" class="form-control" name="date_from" value="<?php echo htmlspecialchars($date_from); ?>">
                            </div>
                            <div class="col-md-2">
                                <label class="form-label">To Date</label>
                                <input type="date" class="form-control" name="date_to" value="<?php echo htmlspecialchars($date_to); ?>">
                            </div>
                            <div class="col-md-12">
                                <div class="d-flex gap-2">
                                    <button type="submit" class="btn btn-primary">Filter</button>
                                    <a href="shop_expenses.php" class="btn btn-outline-secondary">Clear</a>
                                </div>
                            </div>
                        </form>
                    </div>

                    <!-- Shop Expenses Table -->
                    <div class="table-card">
                        <div class="table-header">
                            <h3 class="table-title">Shop Expenses (<?php echo $total_expenses; ?> total)</h3>
                            <div class="d-flex gap-2">
                                <a href="add_expense.php?type=SHOP" class="btn btn-shop">
                                    <i class="ph-plus me-1"></i> Add Shop Expense
                                </a>
                                <a href="expense_reports.php?type=SHOP" class="btn btn-primary">
                                    <i class="ph-chart-bar me-1"></i> Shop Reports
                                </a>
                            </div>
                        </div>
                        
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>Expense Details</th>
                                    <th>Shop Category</th>
                                    <th>Amount</th>
                                    <th>Payment Method</th>
                                    <th>Status</th>
                                    <th>Date</th>
                                    <th>Created By</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php while ($expense = $expenses->fetch_assoc()): ?>
                                <tr>
                                    <td>
                                        <div class="d-flex align-items-center">
                                            <div class="expense-avatar me-3">
                                                SH
                                            </div>
                                            <div>
                                                <div style="font-weight: 600; color: #1e293b;">
                                                    <?php echo htmlspecialchars($expense['expense_title']); ?>
                                                </div>
                                                <div style="color: #64748b; font-size: 0.75rem;">
                                                    #<?php echo htmlspecialchars($expense['expense_number']); ?>
                                                </div>
                                                <?php if ($expense['vendor_name']): ?>
                                                    <div style="color: #e74c3c; font-size: 0.75rem;">
                                                        Vendor: <?php echo htmlspecialchars($expense['vendor_name']); ?>
                                                    </div>
                                                <?php endif; ?>
                                                <?php if ($expense['description'] && strlen($expense['description']) > 0): ?>
                                                    <div style="color: #64748b; font-size: 0.75rem;">
                                                        <?php echo htmlspecialchars(substr($expense['description'], 0, 50)) . (strlen($expense['description']) > 50 ? '...' : ''); ?>
                                                    </div>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </td>
                                    <td>
                                        <div>
                                            <span style="font-weight: 500; color: #1e293b;">
                                                <?php echo htmlspecialchars($expense['category_name']); ?>
                                            </span>
                                        </div>
                                        <span class="type-badge" style="background: #fee2e2; color: #991b1b; padding: 0.25rem 0.5rem; border-radius: 4px; font-size: 0.75rem;">
                                            Shop Expense
                                        </span>
                                    </td>
                                    <td>
                                        <span style="font-weight: 600; color: #1e293b; font-size: 1rem;">
                                            KES <?php echo number_format($expense['amount'], 2); ?>
                                        </span>
                                        <?php if ($expense['receipt_number']): ?>
                                            <div style="color: #64748b; font-size: 0.75rem;">
                                                Receipt: <?php echo htmlspecialchars($expense['receipt_number']); ?>
                                            </div>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php 
                                        $payment_class = match($expense['payment_method']) {
                                            'CASH' => 'payment-cash',
                                            'CARD' => 'payment-card',
                                            'BANK_TRANSFER' => 'payment-bank-transfer',
                                            'MPESA' => 'payment-mpesa',
                                            'MOBILE_MONEY' => 'payment-mobile-money',
                                            'CHEQUE' => 'payment-cheque',
                                            default => 'payment-cash'
                                        };
                                        ?>
                                        <span class="payment-badge <?php echo $payment_class; ?>">
                                            <?php echo ucfirst(str_replace('_', ' ', strtolower($expense['payment_method']))); ?>
                                        </span>
                                        <?php if ($expense['payment_reference']): ?>
                                            <div style="color: #64748b; font-size: 0.75rem;">
                                                Ref: <?php echo htmlspecialchars($expense['payment_reference']); ?>
                                            </div>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php 
                                        $status_class = match($expense['status']) {
                                            'DRAFT' => 'status-draft',
                                            'PENDING' => 'status-pending',
                                            'APPROVED' => 'status-approved',
                                            'PAID' => 'status-paid',
                                            'REJECTED' => 'status-rejected',
                                            'CANCELLED' => 'status-cancelled',
                                            default => 'status-draft'
                                        };
                                        ?>
                                        <span class="status-badge <?php echo $status_class; ?>">
                                            <?php echo ucfirst(str_replace('_', ' ', strtolower($expense['status']))); ?>
                                        </span>
                                        <?php if ($expense['requires_approval'] && $expense['status'] == 'PENDING'): ?>
                                            <div style="color: #d97706; font-size: 0.75rem;">
                                                <i class="ph-warning"></i> Needs Approval
                                            </div>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <div style="font-weight: 500; color: #1e293b;">
                                            <?php echo date('M j, Y', strtotime($expense['expense_date'])); ?>
                                        </div>
                                        <div style="color: #64748b; font-size: 0.75rem;">
                                            Added: <?php echo date('M j, g:i A', strtotime($expense['created_at'])); ?>
                                        </div>
                                        <?php if ($expense['approved_at']): ?>
                                            <div style="color: #059669; font-size: 0.75rem;">
                                                Approved: <?php echo date('M j, g:i A', strtotime($expense['approved_at'])); ?>
                                            </div>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <div style="font-weight: 500; color: #1e293b;">
                                            <?php echo htmlspecialchars($expense['created_by_name']); ?>
                                        </div>
                                        <?php if ($expense['approved_by_name']): ?>
                                            <div style="color: #059669; font-size: 0.75rem;">
                                                Approved by: <?php echo htmlspecialchars($expense['approved_by_name']); ?>
                                            </div>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <div class="d-flex gap-1">
                                            <a href="view_expense.php?id=<?php echo $expense['expense_id']; ?>" class="btn-action btn-primary" title="View Details">
                                                <i class="ph-eye"></i>
                                            </a>
                                            <?php if (in_array($expense['status'], ['DRAFT', 'PENDING'])): ?>
                                                <a href="edit_expense.php?id=<?php echo $expense['expense_id']; ?>" class="btn-action btn-warning" title="Edit Expense">
                                                    <i class="ph-pencil"></i>
                                                </a>
                                            <?php endif; ?>
                                            <?php if ($expense['status'] == 'PENDING' && $role_name == 'Administrator'): ?>
                                                <a href="approve_expense.php?id=<?php echo $expense['expense_id']; ?>" class="btn-action btn-success" title="Approve">
                                                    <i class="ph-check"></i>
                                                </a>
                                            <?php endif; ?>
                                            <?php if ($expense['status'] == 'PAID'): ?>
                                                <a href="print_expense.php?id=<?php echo $expense['expense_id']; ?>" class="btn-action btn-shop" title="Print Receipt" target="_blank">
                                                    <i class="ph-printer"></i>
                                                </a>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                </tr>
                                <?php endwhile; ?>
                            </tbody>
                        </table>

                        <!-- Pagination -->
                        <div class="pagination-wrapper">
                            <div class="pagination-info">
                                Showing <?php echo $offset + 1; ?> to <?php echo min($offset + $limit, $total_expenses); ?> of <?php echo $total_expenses; ?> entries
                            </div>
                            
                            <?php if ($total_pages > 1): ?>
                                <div class="pagination">
                                    <?php if ($page > 1): ?>
                                        <a href="?page=<?php echo $page - 1; ?>&search=<?php echo urlencode($search); ?>&shop_filter=<?php echo $shop_filter; ?>&status_filter=<?php echo $status_filter; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>" class="page-link">
                                            <i class="ph-caret-left"></i>
                                        </a>
                                    <?php endif; ?>
                                    
                                    <?php 
                                    $start = max(1, $page - 2);
                                    $end = min($total_pages, $page + 2);
                                    
                                    for ($i = $start; $i <= $end; $i++): 
                                    ?>
                                        <a href="?page=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>&shop_filter=<?php echo $shop_filter; ?>&status_filter=<?php echo $status_filter; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>" 
                                           class="page-link <?php echo $i == $page ? 'active' : ''; ?>">
                                            <?php echo $i; ?>
                                        </a>
                                    <?php endfor; ?>
                                    
                                    <?php if ($page < $total_pages): ?>
                                        <a href="?page=<?php echo $page + 1; ?>&search=<?php echo urlencode($search); ?>&shop_filter=<?php echo $shop_filter; ?>&status_filter=<?php echo $status_filter; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>" class="page-link">
                                            <i class="ph-caret-right"></i>
                                        </a>
                                    <?php endif; ?>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    
    <script>
        // Auto-submit form on filter change
        $(document).ready(function() {
            $('.form-select').on('change', function() {
                $(this).closest('form').submit();
            });
        });
    </script>

    <!-- App js -->
    <script src="assets/js/app.js"></script>
</body>
</html>

<?php $conn->close(); ?>