<?php
// trigger_pour.php
// Production version

require 'db.php';

error_reporting(0);
ini_set('display_errors', 0);
header('Content-Type: application/json');

try {
    $input = json_decode(file_get_contents('php://input'), true);
    $guest_id = $input['guest_id'] ?? null;
    $drink = $input['drink'] ?? null;

    if (!$guest_id || !$drink) {
        echo json_encode(['status' => 'error', 'message' => 'Missing parameters']);
        exit;
    }

    $config = require 'config_dispenser.php';
    $drink_config = $config['drinks'][$drink] ?? null;

    if (!$drink_config) {
        echo json_encode(['status' => 'error', 'message' => 'Invalid drink']);
        exit;
    }

    // Update DB
    $column = $drink_config['db_column'];
    $sql = "UPDATE guests SET $column = COALESCE($column, 0) + 25 WHERE id = ?";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$guest_id]);

    // Trigger Pump
    $device_ip = $config['device_ip'];
    $pump_id = $drink_config['id'];
    $duration = $drink_config['pump_time'];

    $target_url = "http://$device_ip:8088/pompka?id=$pump_id&czas=$duration";

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $target_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 2);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 1);
    curl_exec($ch);
    curl_close($ch);

    echo json_encode(['status' => 'success']);

} catch (Exception $e) {
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
?>