<?php
include '../config.php';

header('Content-Type: application/json');
$tv_id = (int)($_GET['tv_id'] ?? 0);
if (!$tv_id) { echo json_encode(['error' => 'no tv_id']); exit; }

$stmt = $conn->prepare("
    SELECT 
        t.status as tv_status,
        t.nama_tv,
        trx.id as trx_id,
        trx.jenis_paket,
        trx.status as trx_status,
        UNIX_TIMESTAMP(trx.target_selesai) as target_unix,
        UNIX_TIMESTAMP(trx.start_time) as start_unix,
        trx.remaining_seconds,
        m.nama_member
    FROM tvs t
    LEFT JOIN transactions trx ON t.current_trx_id = trx.id
    LEFT JOIN members m ON trx.member_id = m.id
    WHERE t.id = ?
");
$stmt->bind_param("i", $tv_id);
$stmt->execute();
$row = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$row) { echo json_encode(['error' => 'tv not found']); exit; }

$server_time = time();

echo json_encode([
    'server_time'    => $server_time,
    'tv_status'      => $row['tv_status'],
    'nama_tv'        => $row['nama_tv'],
    'trx_id'         => $row['trx_id'],
    'jenis_paket'    => $row['jenis_paket'],
    'trx_status'     => $row['trx_status'],
    'target_unix'    => (int)$row['target_unix'],
    'start_unix'     => (int)$row['start_unix'],
    'remaining_secs' => (int)$row['remaining_seconds'],
    'customer'       => $row['nama_member'] ?: 'Tamu',
    // Hitung sisa di server agar Android tinggal pakai
    'sisa_detik'     => ($row['jenis_paket'] === 'fixed' && $row['trx_status'] === 'ongoing')
                            ? max(0, (int)$row['target_unix'] - $server_time)
                            : 0,
    'elapsed_detik'  => ($row['jenis_paket'] === 'open' && $row['trx_status'] === 'ongoing')
                            ? max(0, $server_time - (int)$row['start_unix'])
                            : 0,
]);