<?php
session_start();
require_once 'db.php';

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

if (!isset($_SERVER['HTTP_X_REQUESTED_WITH']) || $_SERVER['HTTP_X_REQUESTED_WITH'] !== 'XMLHttpRequest') {
    echo json_encode(['error' => 'Invalid request']);
    exit;
}

if (!isset($_SESSION['admin']) || $_SESSION['admin'] !== true) {
    echo json_encode(['error' => 'Unauthorized']);
    exit;
}

$action = $_GET['action'] ?? '';

switch ($action) {
    case 'get_billboards':
        getBillboards();
        break;
    
    case 'stop_billboard':
        stopBillboard();
        break;
    
    case 'restart_billboard':
        restartBillboard();
        break;
    
    default:
        echo json_encode(['error' => 'Invalid action']);
}

function getBillboards() {
    global $pdo;
    
    try {
        $stmt = $pdo->query("SELECT * FROM `imators-systems-billboard` ORDER BY last_seen DESC");
        $billboards = $stmt->fetchAll();
        
        foreach ($billboards as &$billboard) {
            $config = json_decode($billboard['config'], true);
            $billboard['latitude'] = $config['location']['latitude'] ?? 0;
            $billboard['longitude'] = $config['location']['longitude'] ?? 0;
            
            $lastSeen = new DateTime($billboard['last_seen']);
            $now = new DateTime();
            $diff = $now->diff($lastSeen);
            
            if ($diff->days > 0) {
                $billboard['connection_status'] = 'offline';
            } elseif ($diff->h > 0) {
                $billboard['connection_status'] = 'inactive';
            } else {
                $billboard['connection_status'] = 'online';
            }
        }
        
        $totalBillboards = count($billboards);
        
        $onlineBillboards = 0;
        $stoppedBillboards = 0;
        
        foreach ($billboards as $billboard) {
            if ($billboard['connection_status'] === 'online') {
                $onlineBillboards++;
            }
            
            if ($billboard['status'] === 'stopped') {
                $stoppedBillboards++;
            }
        }
        
        $stats = [
            'total_billboards' => $totalBillboards,
            'online_billboards' => $onlineBillboards,
            'stopped_billboards' => $stoppedBillboards
        ];
        
        echo json_encode([
            'success' => true,
            'billboards' => $billboards,
            'stats' => $stats
        ]);
    } catch (PDOException $e) {
        echo json_encode(['error' => 'Database error: ' . $e->getMessage()]);
    }
}

function stopBillboard() {
    global $pdo;
    
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!isset($input['serial']) || !isset($input['message'])) {
        echo json_encode(['error' => 'Missing parameters']);
        exit;
    }
    
    $serial = $input['serial'];
    $message = $input['message'];
    
    try {
        $stmt = $pdo->prepare("UPDATE `imators-systems-billboard` SET status = 'stopped', stop_message = ? WHERE serial = ?");
        $result = $stmt->execute([$message, $serial]);
        
        if ($result) {
            file_get_contents("https://imators.systems/video/inter/broadcast.php?serial=$serial&status=stopped&message=" . urlencode($message));
            
            echo json_encode(['success' => true]);
        } else {
            echo json_encode(['error' => 'Failed to stop billboard']);
        }
    } catch (PDOException $e) {
        echo json_encode(['error' => 'Database error: ' . $e->getMessage()]);
    }
}

function restartBillboard() {
    global $pdo;
    
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!isset($input['serial'])) {
        echo json_encode(['error' => 'Missing serial parameter']);
        exit;
    }
    
    $serial = $input['serial'];
    
    try {
        $stmt = $pdo->prepare("UPDATE `imators-systems-billboard` SET status = 'active', stop_message = NULL WHERE serial = ?");
        $result = $stmt->execute([$serial]);
        
        if ($result) {
            file_get_contents("https://imators.systems/video/inter/broadcast.php?serial=$serial&status=active");
            
            echo json_encode(['success' => true]);
        } else {
            echo json_encode(['error' => 'Failed to restart billboard']);
        }
    } catch (PDOException $e) {
        echo json_encode(['error' => 'Database error: ' . $e->getMessage()]);
    }
}