<?php
include "db.php";

if(!isset($_GET['id'])) { echo "<p>No ID provided.</p>"; exit; }
$id = intval($_GET['id']);

$result = $conn->query("SELECT * FROM expense WHERE id=$id");
if($result->num_rows == 0){ echo "<p>Expense not found.</p>"; exit; }
$expense = $result->fetch_assoc();

if(isset($_POST['submit'])){
    $name = $_POST['name'];
    $date = $_POST['date'];
    $amount = $_POST['amount'];
    $type = $_POST['type'];
    $amount_type = $_POST['amount_type'];
    $description = $_POST['description'];

    $sql = "UPDATE expense SET name='$name', date='$date', amount='$amount', type='$type', amount_type='$amount_type', description='$description' WHERE id=$id";

    if($conn->query($sql)){
        $success = "Expense updated!";
        $expense = $conn->query("SELECT * FROM expense WHERE id=$id")->fetch_assoc();
    } else { $error = $conn->error; }
}
?>

<h2>Edit Expense</h2>
<?php if(isset($success)) echo "<p style='color:green;'>$success</p>"; ?>
<?php if(isset($error)) echo "<p style='color:red;'>$error</p>"; ?>

<form method="POST">
    <label>Expense Name:</label><br>
    <input type="text" name="name" value="<?php echo $expense['name']; ?>" required><br><br>
    
    <label>Date:</label><br>
    <input type="date" name="date" value="<?php echo $expense['date']; ?>" required><br><br>
    
    <label>Amount:</label><br>
    <input type="number" step="0.01" name="amount" value="<?php echo $expense['amount']; ?>" required><br><br>
    
    <label>Type:</label><br>
    <input type="text" name="type" value="<?php echo $expense['type']; ?>"><br><br>
    
    <label>Amount Type:</label><br>
    <select name="amount_type">
        <option value="CASH" <?php if($expense['amount_type']=='CASH') echo 'selected'; ?>>CASH</option>
        <option value="BANK" <?php if($expense['amount_type']=='BANK') echo 'selected'; ?>>BANK</option>
    </select><br><br>
    
    <label>Description:</label><br>
    <textarea name="description"><?php echo $expense['description']; ?></textarea><br><br>
    
    <input type="submit" name="submit" value="Update Expense">
</form>

<style>
form{max-width:600px;background:#fff;padding:20px;border-radius:8px;box-shadow:0 2px 5px rgba(0,0,0,0.2);}
input,textarea,select{width:100%;padding:8px;margin:4px 0;box-sizing:border-box;}
input[type="submit"]{width:auto;background:#333;color:#fff;cursor:pointer;}
input[type="submit"]:hover{background:#555;}
@media screen and (max-width:768px){form{width:100%;padding:10px;}}
</style>
