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

$paths = [__DIR__.'/../includes/db.php', __DIR__.'/../../includes/db.php'];
foreach ($paths 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);

// Require valid auth token
require_once __DIR__ . '/../includes/auth.php';
requireAuth();

function colExists(PDO $pdo, string $table, string $column): bool {
  $db = $pdo->query('SELECT DATABASE()')->fetchColumn();
  $st = $pdo->prepare("SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
                       WHERE TABLE_SCHEMA=:db AND TABLE_NAME=:t AND COLUMN_NAME=:c");
  $st->execute([':db'=>$db, ':t'=>$table, ':c'=>$column]);
  return (bool)$st->fetchColumn();
}

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

$hasDesired = colExists($pdo, 'devices', 'desired_forward_state');

$sql = "SELECT 
          CAST(call_forwarding AS UNSIGNED)  AS call_forwarding,
          CAST(trigger_status  AS UNSIGNED)  AS trigger_status,
          ack_message, ack_time, preferred_sim_slot" 
        . ($hasDesired ? ", CAST(desired_forward_state AS UNSIGNED) AS desired_forward_state" : "") .
       " FROM devices WHERE device_id = :id LIMIT 1";


$st = $pdo->prepare($sql);
$st->execute([':id'=>$deviceId]);
$row = $st->fetch(PDO::FETCH_ASSOC);
if (!$row) { echo json_encode(['success'=>false,'message'=>'Device not found']); exit; }

$trigger = (int)($row['trigger_status'] ?? 0);
if ($trigger === 0 && $hasDesired) {
  // Neutralize: when idle, desired == actual to avoid any client-side mismatch logic
  $row['desired_forward_state'] = (int)($row['call_forwarding'] ?? 0);
}

$out = [
  'success'              => true,
  'ack_message'          => $row['ack_message'] ?? null,
  'ack_time'             => $row['ack_time'] ?? null,
  'call_forwarding'      => isset($row['call_forwarding']) ? (int)$row['call_forwarding'] : 0,
  'trigger_status'       => isset($row['trigger_status'])  ? (int)$row['trigger_status']  : 0,
  'preferred_sim_slot'   => $row['preferred_sim_slot'] ?? 'sim1',
  'desired_forward_state'=> $hasDesired && isset($row['desired_forward_state']) ? (int)$row['desired_forward_state'] : null,
];
echo json_encode($out);

