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

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

$linksFile = BASE_PATH . '/data/seo-links.txt';
if (!is_file($linksFile)) {
    echo json_encode(array('code' => 1, 'msg' => '外链数据文件不存在'), JSON_UNESCAPED_UNICODE);
    exit;
}

$urls = file($linksFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
if (!is_array($urls)) {
    $urls = array();
}
$count = count($urls);

$page = isset($_GET['p']) && is_numeric($_GET['p']) ? max(0, (int)$_GET['p']) : 0;
$num = isset($_GET['num']) && is_numeric($_GET['num']) ? min(30, max(1, (int)$_GET['num'])) : 15;

$maxPage = $count > 0 ? ceil($count / $num) : 0;

if ($page >= $maxPage) {
    echo json_encode(array('code' => 1, 'msg' => '已完成！', 'count' => $count), JSON_UNESCAPED_UNICODE);
    exit;
}

$slice = array_slice($urls, $page * $num, $num);
$data = array();
foreach ($slice as $v) {
    $v = trim($v);
    if ($v !== '') {
        $data[] = $v;
    }
}

echo json_encode(array('code' => 0, 'data' => $data, 'count' => $count, 'page' => $page, 'maxPage' => (int)$maxPage), JSON_UNESCAPED_UNICODE);
