<?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;
    }

    $column_map = [
        'wodka' => 'vodka_ml',
        'whisky' => 'whisky_ml',
        'nalewka' => 'liqueur_ml'
    ];

    if (isset($column_map[$drink])) {
        $column = $column_map[$drink];
        $sql = "UPDATE guests SET $column = COALESCE($column, 0) + 25 WHERE id = ?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$guest_id]);
    }

    // Map drinks to specific pump URLs
    $pump_map = [
        'wodka' => 'http://92.63.33.22:8088/pompka?id=1&czas=1000',
        'whisky' => 'http://92.63.33.22:8088/pompka?id=2&czas=1000',
        'nalewka' => 'http://92.63.33.22:8088/pompka?id=3&czas=1000'
    ];

    if (isset($pump_map[$drink])) {
        $target_url = $pump_map[$drink];
        $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()]);
}
?>