<?php
include("../db/cn.php");
//session_start();

// Check if user is logged in
if(!isset($_SESSION['user_name'])){
    header("Location: expense.php");
    exit();
}

// Fetch record
if(isset($_GET['id'])){
    $id = intval($_GET['id']);
    $query = mysqli_query($connection, "SELECT * FROM incash WHERE id = $id");
    $expense = mysqli_fetch_assoc($query);

    if(!$expense){
        echo "Expense not found!";
        exit();
    }
} else {
    echo "Invalid request!";
    exit();
}

// Update record
if($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['update'])){
    $id = intval($_POST['id']);
    $name_detail = $_POST['name_detail'];
    $paid_by = $_POST['paid_by'];
    $amount = $_POST['amount'];

    $update_query = "UPDATE incash 
                     SET name_detail='$name_detail',
                         paid_by='$paid_by',
                         amount='$amount'
                     WHERE id=$id";

    if(mysqli_query($connection, $update_query)){
        echo '<script>alert("Expense updated successfully!"); window.location.href="expence.php";</script>';
        exit();
    } else {
        echo "Error updating record: " . mysqli_error($connection);
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Edit Expense</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light">
<div class="container mt-5">
    <div class="card p-4 shadow">
        <h3 class="mb-4">Edit Expense</h3>
        <form method="POST">
            <input type="hidden" name="id" value="<?php echo $expense['id']; ?>">

            <div class="mb-3">
                <label class="form-label">Expense</label>
                <input type="text" name="name_detail" class="form-control" 
                       value="<?php echo $expense['name_detail']; ?>" required>
            </div>

            <div class="mb-3">
                <label class="form-label">Paid By</label>
                <input type="text" name="paid_by" class="form-control" 
                       value="<?php echo $expense['paid_by']; ?>" required>
            </div>

            <div class="mb-3">
                <label class="form-label">Amount (Rs)</label>
                <input type="number" name="amount" class="form-control" 
                       value="<?php echo $expense['amount']; ?>" required>
            </div>

            <button type="submit" name="update" class="btn btn-success">Update</button>
            <a href="expence.php" class="btn btn-secondary">Cancel</a>
        </form>
    </div>
</div>
</body>
</html>
