<?php

require_once 'databaseConnection.php';

if ($_SERVER["REQUEST_METHOD"] == "POST") {

     // Ensure ID is provided in URL (for update target)
    if (!isset($_GET['id'])) {
        echo "Category is missing.";
        exit;
    } else {
        $id = $_GET['id']; // get labourID from URL parameter
    }

    // Check if required fields are present and not empty
    if (!empty($_POST['category']) && !empty($_POST['description']) && isset($_POST['status'])) {

        // Assign variables after basic sanitization
        $category = htmlspecialchars(trim($_POST['category']));
        $description = htmlspecialchars(trim($_POST['description']));
        $status = !empty($_POST['status']) ? htmlspecialchars(trim($_POST['status'])) : 'Inactive';

        // Database connection
        $mysqli = db_connect();
        if (!$mysqli) {
            echo "Database connection failed: " . $mysqli->connect_error;
            exit;
        }

        // Prepare the SQL UPDATE statement
        $stmt = $mysqli->prepare("UPDATE `addCategory` SET `description` = ?, `status` = ? WHERE `category` = ?");
        if ($stmt === false) {
            echo "Error preparing statement: " . $mysqli->error;
            exit;
        }

        // Bind parameters and execute statement
        $stmt->bind_param("sss", $description, $status, $category);
        if ($stmt->execute()) {
            header("Location: ../expense-category.php");
            exit;
        } else {
            echo "Error updating record: " . $stmt->error;
        }

        // Close statement and database connection
        $stmt->close();
        $mysqli->close();

    } else {
        echo "All fields are required.";
    }

} else {
    echo "Invalid request method.";
}
?>
