<?php
// ai_command_handler.php
header('Content-Type: application/json');
require_once('config.php'); // using your config file

$input = json_decode(file_get_contents('php://input'), true);

if (!isset($input['message'])) {
    echo json_encode(["reply" => "Invalid request."]);
    exit;
}

$message = strtolower(trim($input["message"]));
$reply = "Sorry, I didn't understand that.";

// Intent: How many work orders today
if (
    strpos($message, "how many") !== false &&
    strpos($message, "work order") !== false &&
    strpos($message, "today") !== false
) {
    $today = date('Y-m-d');
    $sql = "SELECT COUNT(*) as total FROM wko_mst WHERE wko_mst_create_date = '$today'";
    $result = sqlsrv_query($conn, $sql);

    if ($result && $row = sqlsrv_fetch_array($result)) {
        $count = $row["total"];
        $reply = "You have $count work order(s) scheduled for today.";
    } else {
        $reply = "Error fetching today's work orders.";
    }
}

// Intent: Pending work orders
if (
    strpos($message, "pending") !== false &&
    strpos($message, "work order") !== false
) {
    $sql = "SELECT COUNT(*) as total FROM wko_det WHERE wko_status = 'OPEN'";
    $result = sqlsrv_query($conn, $sql);

    if ($result && $row = mysqli_fetch_assoc($result)) {
        $count = $row["total"];
        $reply = "You have $count pending work order(s).";
    } else {
        $reply = "Error fetching pending work orders.";
    }
}

echo json_encode(["reply"=> $reply]);

?>