<?php
declare(strict_types=1);

ini_set('display_errors', '0');
header('Content-Type: application/json; charset=utf-8');

session_start();
require_once __DIR__ . '/../../core/db_connect.php';

function json_out(array $payload, int $code = 200): void {
  http_response_code($code);
  echo json_encode($payload);
  exit;
}

function read_json_body(): array {
  $raw = file_get_contents('php://input');
  $data = json_decode($raw ?: '[]', true);
  return is_array($data) ? $data : [];
}

function safe_str($v): string {
  return trim((string)$v);
}

try {
  if (!isset($_SESSION['user_id'])) {
    json_out(['success' => false, 'error' => 'Not authenticated'], 401);
  }

  $landlord_id = (int)$_SESSION['user_id'];

  $data = read_json_body();
  $serial  = safe_str($data['serial'] ?? '');
  $command = strtolower(safe_str($data['command'] ?? ''));

  $allowed = ['status', 'connect', 'disconnect', 'relayclose', 'relayopen'];
  if ($serial === '' || $command === '' || !in_array($command, $allowed, true)) {
    json_out(['success' => false, 'error' => 'Invalid request'], 400);
  }

  // Ownership check: landlord must own the tenant that owns this flecto meter.
  $chk = $conn_rbe->prepare("
    SELECT 1
    FROM flecto_meters fm
    JOIN tenant_landlord_map tlm ON tlm.tenant_id = fm.tenant_id
    WHERE tlm.landlord_id = ?
      AND fm.serial_number = ?
    LIMIT 1
  ");
  $chk->execute([$landlord_id, $serial]);
  if (!$chk->fetchColumn()) {
    json_out(['success' => false, 'error' => 'Meter not found for this landlord'], 403);
  }

  // Token and URL should never live in JS.
  $token = getenv('FLECTO_BEARER_TOKEN') ?: '';
  $url   = getenv('FLECTO_API_URL') ?: 'https://api.flecto.xyz/meter_api.php';

  if ($token === '') {
    json_out(['success' => false, 'error' => 'Flecto token not configured'], 500);
  }

  $payload = json_encode([
    'serial'  => $serial,
    'command' => $command
  ]);

  $ch = curl_init($url);
  curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => $payload,
    CURLOPT_HTTPHEADER => [
      'Content-Type: application/json',
      'Authorization: Bearer ' . $token,
    ],
    CURLOPT_TIMEOUT => 20,
    CURLOPT_CONNECTTIMEOUT => 10,
  ]);

  $respBody = curl_exec($ch);
  $curlErr  = curl_error($ch);
  $httpCode = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
  curl_close($ch);

  if ($respBody === false || $respBody === null) {
    json_out(['success' => false, 'error' => 'Request failed', 'detail' => $curlErr], 502);
  }

  $respJson = json_decode($respBody, true);

  // If Flecto returns non-JSON (or junk), still pass back something useful.
  if (!is_array($respJson)) {
    json_out([
      'success' => false,
      'error' => 'Invalid response from Flecto',
      'http_code' => $httpCode,
      'raw' => (string)$respBody
    ], 502);
  }

  // Optional: you can log command attempts here later if you want.
  // For now we just return the Flecto payload, plus http_code.

  json_out([
    'success' => true,
    'http_code' => $httpCode,
    'flecto' => $respJson
  ], 200);

} catch (Throwable $e) {
  json_out(['success' => false, 'error' => 'Server error'], 500);
}