<?php
include 'db.php';
$id = intval($_GET['id'] ?? 0);

$sql = "
    SELECT 
        e.id, 
        e.expense_date, 
        e.details, 
        e.amount,
        et.type_name AS expense_type, 
        p.project_name AS project,
        e.bill_file
    FROM expenses e
    JOIN expense_types et ON e.type_id = et.id
    JOIN projects p ON e.project_id = p.id
    WHERE e.id = $id
";
$result = $conn->query($sql);
$exp = $result ? $result->fetch_assoc() : null;
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>View Expense</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="container py-4">
    <h2 class="mb-4">📄 View Expense</h2>
    <?php if($exp): ?>
    <table class="table table-bordered">
        <tr><th>ID</th><td><?= htmlspecialchars($exp['id']) ?></td></tr>
        <tr><th>Date</th><td><?= htmlspecialchars($exp['expense_date']) ?></td></tr>
        <tr><th>Project</th><td><?= htmlspecialchars($exp['project']) ?></td></tr>
        <tr><th>Type</th><td><?= htmlspecialchars($exp['expense_type']) ?></td></tr>
        <tr><th>Details</th><td><?= nl2br(htmlspecialchars($exp['details'])) ?></td></tr>
        <tr><th>Amount</th><td><strong>RM <?= number_format($exp['amount'],2) ?></strong></td></tr>

        <?php if (!empty($exp['bill_file'])): ?>
            <?php 
                // Always use the correct base path
                $fileName = basename($exp['bill_file']); 
                $fileUrl = "/employee_system/uploads/expenses/" . $fileName;
            ?>
            <tr>
                <th>Bill File</th>
                <td>
                    <a href="<?= htmlspecialchars($fileUrl) ?>" target="_blank" rel="noopener noreferrer">📎 View Attachment</a>
                </td>
            </tr>
        <?php endif; ?>
    </table>
    <a href="expenses_list.php" class="btn btn-secondary">⬅ Back</a>
    <?php else: ?>
        <div class="alert alert-danger">❌ Expense not found</div>
    <?php endif; ?>
</body>
</html>
