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

// Load DB
$pdo = null;
foreach ([__DIR__ . '/../includes/db.php', __DIR__ . '/../../includes/db.php'] as $p) {
    if (file_exists($p)) { require_once $p; break; }
}
if (!isset($pdo) || !$pdo) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'DB not loaded']);
    exit;
}
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// Cache helper
require_once __DIR__ . '/../includes/micro_cache.php';

// Input
$deviceId = trim($_GET['device_id'] ?? $_POST['device_id'] ?? '');
if ($deviceId === '') {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'device_id required']);
    exit;
}

$TTL = 1;
$cacheKey = "trigger:get:" . $deviceId;

$cached = mc_get($cacheKey);
if ($cached !== null && mc_age($cacheKey) < $TTL) {
    echo $cached;
    exit;
}

echo mc_lock($cacheKey, function() use ($pdo, $deviceId, $cacheKey, $TTL) {

    $cached2 = mc_get($cacheKey);
    if ($cached2 !== null && mc_age($cacheKey) < $TTL) {
        return $cached2;
    }

    $stmt = $pdo->prepare("
        SELECT trigger_status, call_forwarding
        FROM devices
        WHERE device_id = :id
        LIMIT 1
    ");
    $stmt->execute([':id' => $deviceId]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$row) {
        $json = json_encode(['success' => false, 'message' => 'Device not found']);
        mc_set($cacheKey, $json, $TTL);
        return $json;
    }

    $ts = (int)($row['trigger_status'] ?? 0);
    $cf = (int)($row['call_forwarding'] ?? 0);

    $out = [
        'success'         => true,
        'trigger_status'  => $ts,
        'call_forwarding' => $cf,
    ];

    $json = json_encode($out + ['data' => $out]);

    header("Cache-Control: private, max-age=1");

    mc_set($cacheKey, $json, $TTL);
    return $json;
});
