<?php
$config = require __DIR__ . '/../config.php';
$pdo = new PDO(
    "mysql:host={$config['host']};dbname={$config['name']};charset=utf8mb4",
    $config['user'],
    $config['pass'],
    [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
);

$where = [];
$params = [];

if (isset($_GET['mutual'])) {
    $where[] = 'is_mutual = :mutual';
    $params[':mutual'] = (int)$_GET['mutual'];
}

if (isset($_GET['first'])) {
    $where[] = 'first_action = :first';
    $params[':first'] = $_GET['first'];
}

$sql = "SELECT * FROM relationships";
if ($where) {
    $sql .= " WHERE " . implode(' AND ', $where);
}
$sql .= " ORDER BY COALESCE(you_followed_at, they_followed_at) DESC";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);

header('Content-Type: application/json');
echo json_encode($stmt->fetchAll());