<?php
require __DIR__ . '/../../app/bootstrap.php';
require __DIR__ . '/../../app/database.php';
require_login();

header('Content-Type: application/json; charset=utf-8');

$runtimeDir = __DIR__ . '/../../runtime';
$stateFile = $runtimeDir . '/seo-backlinks-state.json';

$state = null;
if (is_file($stateFile)) {
    $json = @file_get_contents($stateFile);
    if ($json) {
        $data = json_decode($json, true);
        if (is_array($data)) $state = $data;
    }
}

if (!$state) {
    echo json_encode(array(
        'code' => 0,
        'status' => 'idle',
        'domains' => array(),
        'current_domain_idx' => 0,
        'current_page' => 0,
        'batch_size' => 15,
        'total_links' => 0,
        'total_sent' => 0,
        'started_at' => null,
        'last_run_at' => null,
        'logs' => array()
    ), JSON_UNESCAPED_UNICODE);
    exit;
}

// Return last 20 logs for UI display
$logs = isset($state['logs']) && is_array($state['logs']) ? array_slice($state['logs'], -20) : array();
$state['logs'] = $logs;

echo json_encode(array_merge(array('code' => 0), $state), JSON_UNESCAPED_UNICODE);
