<?php
include 'db.php';
$id = intval($_GET['id']);
$exp = $conn->query("SELECT * FROM expenses WHERE id=$id")->fetch_assoc();

// Handle update
if (isset($_POST['update'])) {
    $expense_date = $_POST['expense_date'];
    $project_id = $_POST['project_id'];
    $type_id = $_POST['expense_type_id'];
    $details = $_POST['details'];
    $amount = $_POST['amount'];
    $bill_file = $exp['bill_file']; // keep old file if no new one uploaded

    // Handle file upload if new file is selected
    if (!empty($_FILES['bill_file']['name'])) {
        $uploadDir = __DIR__ . "/uploads/expenses/";
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }

        $fileName = "bill_" . uniqid() . "_" . basename($_FILES['bill_file']['name']);
        $targetPath = $uploadDir . $fileName;

        if (move_uploaded_file($_FILES['bill_file']['tmp_name'], $targetPath)) {
            $bill_file = $fileName; // save just filename
        } else {
            echo "<script>alert('❌ Failed to upload file');</script>";
        }
    }

    $stmt = $conn->prepare("
        UPDATE expenses 
        SET expense_date=?, project_id=?, type_id=?, details=?, amount=?, bill_file=? 
        WHERE id=?
    ");
    $stmt->bind_param(
        "siisdsi",
        $expense_date,
        $project_id,
        $type_id,
        $details,
        $amount,
        $bill_file,
        $id
    );
    $stmt->execute();
    echo "<script>alert('✅ Expense updated successfully'); window.location='expenses_list.php';</script>";
    exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Edit 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">✏️ Edit Expense</h2>
    <form method="post" enctype="multipart/form-data" class="card p-4 shadow-sm">
        <!-- Date -->
        <div class="mb-3">
            <label class="form-label">Expense Date</label>
            <input type="date" class="form-control" name="expense_date" 
                   value="<?= htmlspecialchars($exp['expense_date']) ?>" required>
        </div>

        <!-- Project -->
        <div class="mb-3">
            <label class="form-label">Project</label>
            <select class="form-select" name="project_id" required>
                <?php
                $projects = $conn->query("SELECT id, project_name FROM projects");
                while ($p = $projects->fetch_assoc()) {
                    $sel = $exp['project_id'] == $p['id'] ? "selected" : "";
                    echo "<option value='{$p['id']}' $sel>" . htmlspecialchars($p['project_name']) . "</option>";
                }
                ?>
            </select>
        </div>

        <!-- Expense Type -->
        <div class="mb-3">
            <label class="form-label">Expense Type</label>
            <select class="form-select" name="expense_type_id" required>
                <?php
                $types = $conn->query("SELECT id, type_name FROM expense_types");
                while ($t = $types->fetch_assoc()) {
                    $sel = $exp['type_id'] == $t['id'] ? "selected" : "";
                    echo "<option value='{$t['id']}' $sel>" . htmlspecialchars($t['type_name']) . "</option>";
                }
                ?>
            </select>
        </div>

        <!-- Details -->
        <div class="mb-3">
            <label class="form-label">Details</label>
            <input type="text" class="form-control" name="details" 
                   value="<?= htmlspecialchars($exp['details']) ?>">
        </div>

        <!-- Amount -->
        <div class="mb-3">
            <label class="form-label">Amount (RM)</label>
            <input type="number" step="0.01" class="form-control" name="amount" 
                   value="<?= htmlspecialchars($exp['amount']) ?>" required>
        </div>

        <!-- Current Bill File -->
        <?php if (!empty($exp['bill_file'])): ?>
        <div class="mb-3">
            <label class="form-label">Current Bill File</label><br>
            <a href="/employee_system/uploads/expenses/<?= htmlspecialchars($exp['bill_file']) ?>" 
               target="_blank">📎 View Current File</a>
        </div>
        <?php endif; ?>

        <!-- Upload New Bill File -->
        <div class="mb-3">
            <label class="form-label">Replace Bill File</label>
            <input type="file" class="form-control" name="bill_file" accept=".jpg,.jpeg,.png,.pdf">
            <small class="text-muted">Leave blank if you don’t want to replace the file.</small>
        </div>

        <!-- Buttons -->
        <div class="d-flex justify-content-between">
            <a href="expenses_list.php" class="btn btn-secondary">⬅ Back</a>
            <button type="submit" name="update" class="btn btn-success">💾 Save Changes</button>
        </div>
    </form>
</body>
</html>
