<?php
// interactions.php - Handle Follows and Ratings
header('Content-Type: application/json');
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

// Data Path
$dataDir = __DIR__ . '/data';
$file = $dataDir . '/users.json';

function getUsers()
{
    global $file;
    if (file_exists($file)) return json_decode(file_get_contents($file), true) ?? [];
    return [];
}

function saveUsers($users)
{
    global $file;
    if (file_put_contents($file, json_encode($users, JSON_PRETTY_PRINT)) === false) {
        error_log("Interactions Write Error: Check permissions for " . $file);
    }
}

$input = json_decode(file_get_contents('php://input'), true);
$action = $input['action'] ?? '';
$token = $input['token'] ?? '';

if (!$token) {
    echo json_encode(['success' => false, 'error' => 'No token provided']);
    exit;
}

$users = getUsers();
$currentUserIndex = -1;

// 1. Authenticate User
foreach ($users as $i => $u) {
    if (isset($u['session_token']) && $u['session_token'] === $token) {
        $currentUserIndex = $i;
        break;
    }
}

if ($currentUserIndex === -1) {
    echo json_encode(['success' => false, 'error' => 'Invalid Session']);
    exit;
}

$currentUser = &$users[$currentUserIndex];
$currentUserId = $currentUser['id'];

// 2. Handle Actions
if ($action === 'follow') {
    $targetId = $input['targetId'] ?? '';
    if (!$targetId) {
        echo json_encode(['success' => false, 'error' => 'Target ID required']);
        exit;
    }

    if (!isset($currentUser['following'])) $currentUser['following'] = [];

    if (!in_array($targetId, $currentUser['following'])) {
        $currentUser['following'][] = $targetId;
        saveUsers($users);
        echo json_encode(['success' => true, 'message' => 'Followed', 'following' => $currentUser['following']]);
    } else {
        echo json_encode(['success' => true, 'message' => 'Already following', 'following' => $currentUser['following']]);
    }
} elseif ($action === 'unfollow') {
    $targetId = $input['targetId'] ?? '';
    if (!$targetId) {
        echo json_encode(['success' => false, 'error' => 'Target ID required']);
        exit;
    }

    if (isset($currentUser['following'])) {
        $key = array_search($targetId, $currentUser['following']);
        if ($key !== false) {
            array_splice($currentUser['following'], $key, 1);
            saveUsers($users);
        }
    }
    echo json_encode(['success' => true, 'message' => 'Unfollowed', 'following' => $currentUser['following'] ?? []]);
} elseif ($action === 'rate') {
    $targetId = $input['targetId'] ?? '';
    $score = intval($input['score'] ?? 0);

    if (!$targetId || $score < 1 || $score > 5) {
        echo json_encode(['success' => false, 'error' => 'Valid Target ID and Score (1-5) required']);
        exit;
    }

    // Find Target User
    $targetUserIndex = -1;
    foreach ($users as $i => $u) {
        if ($u['id'] == $targetId || (isset($u['email']) && $u['email'] == $targetId)) { // Allow rating by email reference if ID missing? Prefer ID.
            $targetUserIndex = $i;
            break;
        }
    }

    if ($targetUserIndex === -1) {
        echo json_encode(['success' => false, 'error' => 'Target user not found']);
        exit;
    }

    $targetUser = &$users[$targetUserIndex];

    if (!isset($targetUser['ratings'])) $targetUser['ratings'] = [];

    // Add Rating
    $targetUser['ratings'][] = [
        'raterId' => $currentUserId,
        'score' => $score,
        'timestamp' => time()
    ];

    // Recalculate Average
    $sum = 0;
    foreach ($targetUser['ratings'] as $r) $sum += $r['score'];
    $targetUser['rating_avg'] = round($sum / count($targetUser['ratings']), 1);
    $targetUser['rating_count'] = count($targetUser['ratings']);

    saveUsers($users);
    echo json_encode(['success' => true, 'message' => 'Rating submitted', 'new_avg' => $targetUser['rating_avg']]);
} else {
    echo json_encode(['success' => false, 'error' => 'Unknown Action']);
}
