<?php

require_once 'databaseConnection.php';

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

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

    // Check if required fields are present
    if (!empty($_POST['labourID']) && !empty($_POST['labourCode']) && !empty($_POST['labourCharge']) && isset($_POST['codeStatus'])) {

        // Assign variables after basic sanitization
        $labourID = htmlspecialchars(trim($_POST['labourID']));
        $labourCode = htmlspecialchars(trim($_POST['labourCode']));
        $labourCharge = htmlspecialchars(trim($_POST['labourCharge']));
        $codeStatus = !empty($_POST['codeStatus']) ? htmlspecialchars(trim($_POST['codeStatus'])) : 'Inactive';

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

        // Validate labourCharge (valid decimal numbers)
        if (!preg_match("/^\d+(\.\d{1,2})?$/", $labourCharge)) {
            echo "Labour 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 `labourCode` SET `labourCode` = ?, `labourCharge` = ?, `status` = ? WHERE `labourID` = ?");
        if ($stmt === false) {
            echo "Error preparing statement: " . $mysqli->error;
            exit;
        }

        // Bind parameters and execute statement
        $stmt->bind_param("ssss", $labourCode, $labourCharge, $codeStatus, $labourID);
        if ($stmt->execute()) {
            header("Location: ../labour-code-details.php");
            exit;
        } else {
            echo "Error updating record: " . $stmt->error;
        }

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

    } else {
        echo "All fields are required.";
    }
} else {
    echo "Invalid request method.";
}
