<?php
include 'config.php';

// Cari transaksi yang statusnya ongoing, tipe fixed, dan waktunya sudah lewat
$now = date('Y-m-d H:i:s');
$q = mysqli_query($conn, "SELECT t.id, t.tv_id, tv.ip_address 
    FROM transactions t 
    JOIN tvs tv ON t.tv_id = tv.id 
    WHERE t.status = 'ongoing' 
    AND t.jenis_paket = 'fixed' 
    AND t.target_selesai <= '$now'");

while ($row = mysqli_fetch_assoc($q)) {
    $trx_id = $row['id'];
    $tv_id = $row['tv_id'];
    $ip = $row['ip_address'];

    // 1. Matikan TV (Sleep)
    controlTV($ip, 'sleep');

    // 2. Update Database jadi Completed
    mysqli_query($conn, "UPDATE transactions SET end_time='$now', status='completed' WHERE id='$trx_id'");
    mysqli_query($conn, "UPDATE tvs SET status='available', current_trx_id=NULL WHERE id='$tv_id'");
    
    echo "TV ID $tv_id otomatis dihentikan karena waktu habis.\n";
}
?>