<?php

require_once 'databaseConnection.php';

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

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

    // Check if required fields are present
    if (!empty($_POST['spareID']) && !empty($_POST['spareType']) && !empty($_POST['spareCharge']) && isset($_POST['spareStatus'])) {

        // Assign variables after basic sanitization
        $spareID = htmlspecialchars(trim($_POST['spareID']));
        $spareType = htmlspecialchars(trim($_POST['spareType']));
        $spareCharge = htmlspecialchars(trim($_POST['spareCharge']));
        $spareStatus = !empty($_POST['spareStatus']) ? htmlspecialchars(trim($_POST['spareStatus'])) : 'Inactive';

        // Validate spareType (letters, Nepali chars, numbers, spaces, brackets)
        if (!preg_match("/^[\p{Devanagari}a-zA-Z0-9\s\(\)]+$/u", $spareType)) {
            echo "Spare Parts Type can only contain letters (including Nepali), numbers, and spaces.";
            exit;
        }

        // Validate spareCharge (valid decimal numbers)
        if (!preg_match("/^\d+(\.\d{1,2})?$/", $spareCharge)) {
            echo "Spare Parts Charge must be a valid numeric value.";
            exit;
        }

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

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

        // Bind parameters and execute statement
        $stmt->bind_param("ssss", $spareType, $spareCharge, $spareStatus, $spareID,);
        if ($stmt->execute()) {
            header("Location: ../spare-parts.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.";
}
