<?php include 'db.php'; 
$project_id = $_GET['id'];
$project = $conn->query("SELECT * FROM projects WHERE id=$project_id")->fetch_assoc();
?>
<!DOCTYPE html>
<html>
<head>
    <title>Project Expenses</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css">
</head>
<body class="p-4">

<div class="container">
    <h2>Expenses for: <?= $project['project_name'] ?> (PO: <?= $project['project_po'] ?>)</h2>
    <button class="btn btn-primary mb-3" data-bs-toggle="modal" data-bs-target="#addExpenseModal">Add Expense</button>
    <a href="report_project.php?id=<?= $project_id ?>" class="btn btn-danger mb-3">Export PDF</a>

    <table class="table table-bordered">
        <thead>
            <tr>
                <th>Expense Name</th>
                <th>Amount</th>
                <th>Date</th>
            </tr>
        </thead>
        <tbody>
        <?php
        $expenses = $conn->query("SELECT * FROM project_expenses WHERE project_id=$project_id");
        $total = 0;
        while($row = $expenses->fetch_assoc()){
            $total += $row['amount'];
            echo "<tr>
                <td>{$row['expense_name']}</td>
                <td>{$row['amount']}</td>
                <td>{$row['expense_date']}</td>
            </tr>";
        }
        ?>
        </tbody>
    </table>
    <h4>Total Spent: <?= $total ?> | Margin: <?= $project['project_po'] - $total ?></h4>
</div>

<!-- Add Expense Modal -->
<div class="modal fade" id="addExpenseModal" tabindex="-1">
  <div class="modal-dialog">
    <form method="POST" action="save_expense.php" class="modal-content">
      <input type="hidden" name="project_id" value="<?= $project_id ?>">
      <div class="modal-header">
        <h5 class="modal-title">Add Expense</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
          <input type="text" name="expense_name" class="form-control mb-2" placeholder="Expense Name" required>
          <input type="number" step="0.01" name="amount" class="form-control mb-2" placeholder="Amount" required>
          <input type="date" name="expense_date" class="form-control mb-2" required>
      </div>
      <div class="modal-footer">
        <button type="submit" class="btn btn-success">Save</button>
      </div>
    </form>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>