<?php include 'db.php'; ?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Manage Expenses</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light">
<div class="container py-5">

    <!-- ADD EXPENSE CARD -->
    <div class="card shadow-lg mb-4">
        <div class="card-header bg-primary text-white d-flex justify-content-between">
            <h4 class="mb-0">💰 Add Expense</h4>
            <div>
                <button class="btn btn-sm btn-light" data-bs-toggle="modal" data-bs-target="#addProject">+ Project</button>
                <button class="btn btn-sm btn-light" data-bs-toggle="modal" data-bs-target="#addType">+ Expense Type</button>
            </div>
        </div>
        <div class="card-body">
            <form method="post" enctype="multipart/form-data">
                <!-- Project -->
                <div class="mb-3">
                    <label class="form-label">Project</label>
                    <select name="project_id" class="form-select" required>
                        <option value="">-- Select Project --</option>
                        <?php
                        $proj = $conn->query("SELECT * FROM projects ORDER BY project_name");
                        while($p = $proj->fetch_assoc()){
                            echo "<option value='{$p['id']}'>{$p['project_name']}</option>";
                        }
                        ?>
                    </select>
                </div>

                <!-- Expense Type -->
                <div class="mb-3">
                    <label class="form-label">Expense Type</label>
                    <select name="type_id" class="form-select" required>
                        <option value="">-- Select Type --</option>
                        <?php
                        $types = $conn->query("SELECT * FROM expense_types ORDER BY type_name");
                        while($t = $types->fetch_assoc()){
                            echo "<option value='{$t['id']}'>{$t['type_name']}</option>";
                        }
                        ?>
                    </select>
                </div>

                <!-- Date -->
                <div class="mb-3">
                    <label class="form-label">Date</label>
                    <input type="date" name="expense_date" class="form-control" value="<?=date('Y-m-d')?>" required>
                </div>

                <!-- Details -->
                <div class="mb-3">
                    <label class="form-label">Details</label>
                    <textarea name="details" class="form-control" rows="2" required></textarea>
                </div>

                <!-- Amount -->
                <div class="mb-3">
                    <label class="form-label">Amount (RM)</label>
                    <input type="number" step="0.01" name="amount" class="form-control" required>
                </div>

                <!-- Bill Upload -->
                <div class="mb-3">
                    <label class="form-label">Upload Bill (Image/PDF)</label>
                    <input type="file" name="bill_file" class="form-control" accept=".jpg,.jpeg,.png,.pdf">
                </div>

                <!-- Save -->
                <button type="submit" name="save" class="btn btn-primary">💾 Save Expense</button>
            </form>
        </div>
    </div>

    <!-- EXPENSES LIST -->
    <div class="card shadow-lg">
        <div class="card-header bg-dark text-white">
            <h5 class="mb-0">📋 Expenses List</h5>
        </div>
        <div class="card-body">
            <table class="table table-bordered table-striped">
                <thead class="table-secondary">
                    <tr>
                        <th>Date</th>
                        <th>Project</th>
                        <th>Type</th>
                        <th>Details</th>
                        <th>Amount (RM)</th>
                        <th>Bill</th>
                    </tr>
                </thead>
                <tbody>
                <?php
                $sql = "SELECT e.*, p.project_name, t.type_name 
                        FROM expenses e 
                        JOIN projects p ON e.project_id = p.id
                        JOIN expense_types t ON e.type_id = t.id
                        ORDER BY e.expense_date DESC, e.id DESC";
                $res = $conn->query($sql);
                if($res && $res->num_rows > 0){
                    while($row = $res->fetch_assoc()){
                        echo "<tr>
                            <td>{$row['expense_date']}</td>
                            <td>{$row['project_name']}</td>
                            <td>{$row['type_name']}</td>
                            <td>{$row['details']}</td>
                            <td>".number_format($row['amount'],2)."</td>
                            <td>";
                        if($row['bill_file']){
                            echo "<a href='{$row['bill_file']}' target='_blank'>View Bill</a>";
                        } else {
                            echo "-";
                        }
                        echo "</td></tr>";
                    }
                } else {
                    echo "<tr><td colspan='6' class='text-center'>No expenses found</td></tr>";
                }
                ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Add Project Modal -->
<div class="modal fade" id="addProject" tabindex="-1">
  <div class="modal-dialog">
    <form class="modal-content" method="post">
      <div class="modal-header bg-secondary text-white">
        <h5 class="modal-title">Add Project</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <input type="text" name="project_name" class="form-control" placeholder="Project Name" required>
      </div>
      <div class="modal-footer">
        <button type="submit" name="addProject" class="btn btn-success">Save</button>
      </div>
    </form>
  </div>
</div>

<!-- Add Expense Type Modal -->
<div class="modal fade" id="addType" tabindex="-1">
  <div class="modal-dialog">
    <form class="modal-content" method="post">
      <div class="modal-header bg-secondary text-white">
        <h5 class="modal-title">Add Expense Type</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <input type="text" name="type_name" class="form-control" placeholder="Expense Type" required><br>
        <input type="number" step="0.01" name="monthly_target" class="form-control" placeholder="Monthly Target (optional)">
      </div>
      <div class="modal-footer">
        <button type="submit" name="addType" class="btn btn-success">Save</button>
      </div>
    </form>
  </div>
</div>

<?php
// Save Expense
if(isset($_POST['save'])){
    $bill_file = null;

    if(isset($_FILES['bill_file']) && $_FILES['bill_file']['error'] == 0){
        $uploadDir = "uploads/expenses/";
        if(!is_dir($uploadDir)) mkdir($uploadDir, 0777, true);

        $ext = pathinfo($_FILES['bill_file']['name'], PATHINFO_EXTENSION);
        $newName = uniqid("bill_").".".$ext;
        $targetPath = $uploadDir.$newName;

        if(move_uploaded_file($_FILES['bill_file']['tmp_name'], $targetPath)){
            $bill_file = $targetPath;
        }
    }

    $stmt = $conn->prepare("INSERT INTO expenses (project_id, type_id, expense_date, details, amount, bill_file) VALUES (?,?,?,?,?,?)");
    $stmt->bind_param("iissds", $_POST['project_id'], $_POST['type_id'], $_POST['expense_date'], $_POST['details'], $_POST['amount'], $bill_file);
    $stmt->execute();

    echo "<script>alert('Expense saved successfully');window.location='expenses.php';</script>";
    exit();
}

// Add Project
if(isset($_POST['addProject'])){
    $stmt = $conn->prepare("INSERT INTO projects (project_name) VALUES (?)");
    $stmt->bind_param("s", $_POST['project_name']);
    $stmt->execute();
    echo "<script>alert('Project added');window.location='expenses.php';</script>";
}

// Add Expense Type
if(isset($_POST['addType'])){
    $stmt = $conn->prepare("INSERT INTO expense_types (type_name, monthly_target) VALUES (?,?)");
    $stmt->bind_param("sd", $_POST['type_name'], $_POST['monthly_target']);
    $stmt->execute();
    echo "<script>alert('Expense type added');window.location='expenses.php';</script>";
}
?>

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