<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once($_SERVER['DOCUMENT_ROOT'] . "/session.php");
header("Content-Type: application/json");

require_once($_SERVER['DOCUMENT_ROOT'] . "/lib/mydb.php");
$pdo = db_connect();  

try {
    $num = isset($_REQUEST['num']) ? $_REQUEST['num'] : '';
    $mode = isset($_REQUEST['mode']) ? $_REQUEST['mode'] : '';
    $tablename = isset($_REQUEST['tablename']) ? $_REQUEST['tablename'] : '';
    $motor_state = isset($_REQUEST['motor_state']) ? $_REQUEST['motor_state'] : ''; // Make sure this is being passed

    include $_SERVER['DOCUMENT_ROOT'] . "/output/_request.php";

    $update_log = date("Y-m-d H:i:s") . " - " . $_SESSION["name"] . " " . $update_log . "&#10";
    $pdo->beginTransaction();
    $sql = "UPDATE $DB.$tablename SET motor_state=?, update_log=? WHERE num=? LIMIT 1";

    $stmh = $pdo->prepare($sql);
    $stmh->bindValue(1, $motor_state, PDO::PARAM_STR);        
    $stmh->bindValue(2, $update_log, PDO::PARAM_STR);        
    $stmh->bindValue(3, $num, PDO::PARAM_STR);

    $stmh->execute();
    $pdo->commit();

    $data = [
        'num' => $num,
        'mode' => $mode
    ];

    echo json_encode($data, JSON_UNESCAPED_UNICODE);
} catch (PDOException $Exception) {
    $pdo->rollBack();
    error_log("Database error: " . $Exception->getMessage()); // Log the error
    echo json_encode(['error' => 'Database error: ' . $Exception->getMessage()], JSON_UNESCAPED_UNICODE);
} catch (Exception $e) {
    error_log("General error: " . $e->getMessage()); // Log general errors
    echo json_encode(['error' => 'General error: ' . $e->getMessage()], JSON_UNESCAPED_UNICODE);
}
?>
