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

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

$runtimeDir = __DIR__ . '/../../runtime';
if (!is_dir($runtimeDir)) {
    @mkdir($runtimeDir, 0755, true);
}
$stateFile = $runtimeDir . '/seo-backlinks-state.json';

function bl_read_state_api() {
    global $stateFile;
    if (!is_file($stateFile)) return null;
    $json = @file_get_contents($stateFile);
    if (!$json) return null;
    $data = json_decode($json, true);
    return is_array($data) ? $data : null;
}

function bl_save_state_api($state) {
    global $stateFile;
    @file_put_contents($stateFile, json_encode($state, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT), LOCK_EX);
}

$action = isset($_POST['action']) ? trim((string)$_POST['action']) : '';

if ($action === 'start') {
    $batchSize = isset($_POST['batch_size']) ? max(1, min(30, (int)$_POST['batch_size'])) : 15;

    // Get all enabled domains with published content
    $pdo = db_connection();
    $allDomains = $pdo->query("SELECT id, domain, site_name FROM domains WHERE status = 'enabled' ORDER BY id DESC")->fetchAll(PDO::FETCH_ASSOC);
    $publishedIds = $pdo->query("SELECT DISTINCT domain_id FROM contents WHERE status = 'published'")->fetchAll(PDO::FETCH_COLUMN);
    $publishedMap = array_flip($publishedIds);

    $domains = array();
    foreach ($allDomains as $d) {
        if (!isset($publishedMap[$d['id']])) continue;
        $raw = trim($d['domain']);
        if ($raw === '') continue;
        $raw = preg_replace('#^https?://#i', '', $raw);
        $raw = rtrim($raw, '/');
        if ($raw !== '') $domains[] = $raw;
    }

    if (empty($domains)) {
        echo json_encode(array('code' => 1, 'msg' => '没有找到已发布内容的域名'), JSON_UNESCAPED_UNICODE);
        exit;
    }

    $linksFile = BASE_PATH . '/data/seo-links.txt';
    $totalLinks = is_file($linksFile) ? count(file($linksFile, FILE_SKIP_EMPTY_LINES)) : 0;

    $state = array(
        'status' => 'running',
        'domains' => $domains,
        'current_domain_idx' => 0,
        'current_page' => 0,
        'batch_size' => $batchSize,
        'total_links' => $totalLinks,
        'total_sent' => 0,
        'started_at' => date('Y-m-d H:i:s'),
        'last_run_at' => null,
        'finished_at' => null,
        'logs' => array()
    );
    bl_save_state_api($state);

    echo json_encode(array('code' => 0, 'msg' => '任务已启动，共 ' . count($domains) . ' 个域名待处理', 'domains' => count($domains)), JSON_UNESCAPED_UNICODE);
    exit;
}

if ($action === 'stop') {
    $state = bl_read_state_api();
    if ($state && $state['status'] === 'running') {
        $state['status'] = 'stopped';
        $state['stopped_at'] = date('Y-m-d H:i:s');
        bl_save_state_api($state);
    }
    echo json_encode(array('code' => 0, 'msg' => '任务已停止'), JSON_UNESCAPED_UNICODE);
    exit;
}

if ($action === 'resume') {
    $state = bl_read_state_api();
    if ($state && ($state['status'] === 'stopped' || $state['status'] === 'completed')) {
        if ($state['status'] === 'completed') {
            $state['current_domain_idx'] = 0;
            $state['current_page'] = 0;
            $state['total_sent'] = 0;
            $state['logs'] = array();
        }
        $state['status'] = 'running';
        $state['resumed_at'] = date('Y-m-d H:i:s');
        bl_save_state_api($state);
    }
    echo json_encode(array('code' => 0, 'msg' => '任务已恢复'), JSON_UNESCAPED_UNICODE);
    exit;
}

echo json_encode(array('code' => 1, 'msg' => '未知操作: ' . $action), JSON_UNESCAPED_UNICODE);
