<?php
// ============================================================
//  Telxio Channel Alert - PHP Backend API v2
//  Receives alerts from Chrome Extension
//  Serves alert status to Android App
//  Handles two-way stop command
// ============================================================

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

$dataFile    = __DIR__ . '/alert_data.json';
$stopFile    = __DIR__ . '/alert_stop.json';

// ─── POST: Save alert or stop command ────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = file_get_contents('php://input');
    $data  = json_decode($input, true);

    if ($data === null) {
        http_response_code(400);
        echo json_encode(['error' => 'Invalid JSON']);
        exit();
    }

    // Handle STOP command from Android app
    if (!empty($data['action']) && $data['action'] === 'stop') {
        $stopData = [
            'stopped'    => true,
            'stopped_at' => time() * 1000,
            'source'     => $data['source'] ?? 'android'
        ];
        file_put_contents($stopFile, json_encode($stopData));
        // Also clear alert
        if (file_exists($dataFile)) {
            $alert = json_decode(file_get_contents($dataFile), true);
            $alert['alerting'] = false;
            file_put_contents($dataFile, json_encode($alert, JSON_PRETTY_PRINT));
        }
        echo json_encode(['success' => true, 'action' => 'stopped']);
        exit();
    }

    // Handle RESUME command (clear stop flag)
    if (!empty($data['action']) && $data['action'] === 'resume') {
        if (file_exists($stopFile)) unlink($stopFile);
        echo json_encode(['success' => true, 'action' => 'resumed']);
        exit();
    }

    // Normal alert data from Chrome extension
    $data['received_at']           = time();
    $data['received_at_formatted'] = date('Y-m-d H:i:s');

    // Clear stop flag when new alert comes in
    if (!empty($data['alerting']) && file_exists($stopFile)) {
        unlink($stopFile);
    }

    file_put_contents($dataFile, json_encode($data, JSON_PRETTY_PRINT));
    echo json_encode(['success' => true, 'timestamp' => time()]);
    exit();
}

// ─── GET: Return current status to Android / Extension ───
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $response = [
        'alerting'  => false,
        'rows'      => [],
        'timestamp' => time() * 1000,
        'stopped'   => false
    ];

    if (file_exists($dataFile)) {
        $data = json_decode(file_get_contents($dataFile), true);
        if (is_array($data)) $response = array_merge($response, $data);
    }

    // Check stop flag
    if (file_exists($stopFile)) {
        $stop = json_decode(file_get_contents($stopFile), true);
        $response['stopped']   = true;
        $response['stop_source'] = $stop['source'] ?? 'unknown';

        // Auto-expire stop after 60 seconds
        $stopAge = (time() * 1000) - ($stop['stopped_at'] ?? 0);
        if ($stopAge > 60000) {
            unlink($stopFile);
            $response['stopped'] = false;
        }
    }

    // Auto-clear stale alerts (older than 30 seconds)
    if (!empty($response['timestamp'])) {
        $age = (time() * 1000) - $response['timestamp'];
        if ($age > 30000) {
            $response['alerting'] = false;
            $response['stale']    = true;
        }
    }

    echo json_encode($response);
    exit();
}

http_response_code(405);
echo json_encode(['error' => 'Method not allowed']);
