<?php
include "db.php";

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

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

if(isset($_POST['submit'])){
    $date = $_POST['date'];
    $description = $_POST['description'];
    $amount = $_POST['amount'];
    $type = $_POST['type'];
    $reference_id = $_POST['reference_id'] ?: NULL;

    $sql = "UPDATE cash SET date='$date', description='$description', amount='$amount', type='$type', reference_id='$reference_id' WHERE id=$id";
    if($conn->query($sql)){
        $success = "Cash transaction updated!";
        $cash = $conn->query("SELECT * FROM cash WHERE id=$id")->fetch_assoc();
    } else { $error = $conn->error; }
}
?>

<h2>Edit Cash Transaction</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>Date:</label><br>
    <input type="date" name="date" value="<?php echo $cash['date']; ?>" required><br><br>
    <label>Description:</label><br>
    <textarea name="description"><?php echo $cash['description']; ?></textarea><br><br>
    <label>Amount:</label><br>
    <input type="number" step="0.01" name="amount" value="<?php echo $cash['amount']; ?>" required><br><br>
    <label>Type:</label><br>
    <select name="type" required>
        <option value="DEBIT" <?php if($cash['type']=='DEBIT') echo 'selected'; ?>>DEBIT</option>
        <option value="CREDIT" <?php if($cash['type']=='CREDIT') echo 'selected'; ?>>CREDIT</option>
    </select><br><br>
    <label>Reference ID:</label><br>
    <input type="number" name="reference_id" value="<?php echo $cash['reference_id']; ?>"><br><br>
    <input type="submit" name="submit" value="Update Transaction">
</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>
