<?php
require_once 'db.php';

header('Content-Type: application/json');

$serial = $_GET['serial'] ?? '';
$status = $_GET['status'] ?? '';
$message = $_GET['message'] ?? null;

if (empty($serial) || empty($status)) {
    echo json_encode(['error' => 'Missing parameters']);
    exit;
}

if ($status !== 'active' && $status !== 'stopped') {
    echo json_encode(['error' => 'Invalid status']);
    exit;
}

try {
    if ($status === 'stopped' && $message !== null) {
        $stmt = $pdo->prepare("UPDATE `imators-systems-billboard` SET status = 'stopped', stop_message = ? WHERE serial = ?");
        $stmt->execute([$message, $serial]);
    } else if ($status === 'active') {
        $stmt = $pdo->prepare("UPDATE `imators-systems-billboard` SET status = 'active', stop_message = NULL WHERE serial = ?");
        $stmt->execute([$serial]);
    }
    
    echo json_encode([
        'success' => true,
        'status' => $status,
        'serial' => $serial,
        'message' => $message
    ]);
} catch (PDOException $e) {
    echo json_encode(['error' => 'Database error: ' . $e->getMessage()]);
}