<?php
// core.php

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

$config = require __DIR__ . '/config.php';

// ================= HELPERS =================
function respond(array $data): void {
    echo json_encode($data, JSON_UNESCAPED_UNICODE);
    exit;
}

function error_response(string $msg, int $code = 400): void {
    http_response_code($code);
    respond(['success' => false, 'error' => $msg]);
}

// ================= DB =================
$db = $config['db'];

$conn = new mysqli($db['host'], $db['user'], $db['pass'], $db['name']);
if ($conn->connect_error) {
    error_response('Database connection failed', 500);
}

$conn->set_charset($db['charset']);

// ================= SCHEMA =================
$conn->query("
    CREATE TABLE IF NOT EXISTS accounts (
        id INT AUTO_INCREMENT PRIMARY KEY,
        username VARCHAR(255) NOT NULL UNIQUE,
        href VARCHAR(500),
        timestamp BIGINT DEFAULT 0,
        is_following TINYINT(1) NOT NULL DEFAULT 0,
        is_followed_by TINYINT(1) NOT NULL DEFAULT 0,
        imported_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        INDEX idx_following (is_following),
        INDEX idx_followed_by (is_followed_by),
        INDEX idx_combo (is_following, is_followed_by)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
");

// ================= INPUT =================
$action = $_GET['action'] ?? '';
$limit  = isset($_GET['limit']) ? max(0, (int)$_GET['limit']) : 0;

$maxLimit = (int)($config['limits']['max_results'] ?? 500);
if ($limit > $maxLimit) {
    $limit = $maxLimit;
}

// ================= STATS =================
function getStats(mysqli $conn): array {
    $sql = "
        SELECT
            SUM(CASE WHEN is_following = 1 AND is_followed_by = 0 THEN 1 ELSE 0 END) AS non,
            SUM(CASE WHEN is_following = 1 AND is_followed_by = 1 THEN 1 ELSE 0 END) AS mutual,
            SUM(CASE WHEN is_following = 1 THEN 1 ELSE 0 END) AS following,
            SUM(CASE WHEN is_followed_by = 1 THEN 1 ELSE 0 END) AS followers
        FROM accounts
    ";

    $res = $conn->query($sql);
    if (!$res) return [];

    return $res->fetch_assoc() ?: [];
}

// ================= FETCH =================
function fetchAccounts(mysqli $conn, string $where = '', int $limit = 0): array {
    $sql = "SELECT username, href FROM accounts";
    if ($where) {
        $sql .= " WHERE {$where}";
    }
    $sql .= " ORDER BY username ASC";
    if ($limit > 0) {
        $sql .= " LIMIT {$limit}";
    }

    $res = $conn->query($sql);
    if (!$res) return [];

    $out = [];
    while ($row = $res->fetch_assoc()) {
        $out[] = $row;
    }
    return $out;
}

// ================= ROUTES =================
switch ($action) {

    case 'get_nonfollowers':
        respond([
            'success'  => true,
            'accounts' => fetchAccounts($conn, 'is_following = 1 AND is_followed_by = 0', $limit),
            'stats'    => getStats($conn)
        ]);
        break;

    case 'get_mutuals':
        respond([
            'success'  => true,
            'accounts' => fetchAccounts($conn, 'is_following = 1 AND is_followed_by = 1', $limit)
        ]);
        break;

    case 'get_following':
        respond([
            'success'  => true,
            'accounts' => fetchAccounts($conn, 'is_following = 1', $limit)
        ]);
        break;

    case 'get_followers':
        respond([
            'success'  => true,
            'accounts' => fetchAccounts($conn, 'is_followed_by = 1', $limit)
        ]);
        break;

    case 'ping':
        $countRes = $conn->query("SELECT COUNT(*) FROM accounts");
        $count = $countRes ? (int)$countRes->fetch_row()[0] : 0;

        respond([
            'success' => true,
            'message' => 'API alive',
            'count'   => $count
        ]);
        break;

    default:
        error_response('Invalid action');
}

$conn->close();