<?php
include '../db.php';
include '../auth.php';
require_right('Access POS');

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

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

if (!isset($input['item_id']) || !isset($input['prep_time'])) {
    echo json_encode(['success' => false, 'message' => 'Missing required parameters']);
    exit;
}

$item_id = intval($input['item_id']);
$prep_time = $input['prep_time'] === '' ? null : intval($input['prep_time']);

try {
    // Check if item exists
    $stmt = $conn->prepare("SELECT id FROM items WHERE id = ?");
    $stmt->bind_param("i", $item_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 0) {
        echo json_encode(['success' => false, 'message' => 'Item not found']);
        exit;
    }
    
    // Update preparation time
    $stmt = $conn->prepare("UPDATE items SET prep_time = ? WHERE id = ?");
    $stmt->bind_param("ii", $prep_time, $item_id);
    $stmt->execute();
    
    echo json_encode(['success' => true, 'message' => 'Preparation time updated successfully']);
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}
?>
