<?php
require_once '../../config/db.php';
require_once '../../core/Auth.php';

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit;
}

try {
    $user_id = Auth::check(); // The "Follower"
    
    $data = json_decode(file_get_contents("php://input"));
    
    if (!isset($data->target_id) || !isset($data->action)) {
        http_response_code(400);
        echo json_encode(['error' => 'Missing target_id or action']);
        exit;
    }

    $target_id = (int)$data->target_id;
    $action = $data->action; // 'follow' or 'unfollow'

    if ($user_id === $target_id) {
        http_response_code(400);
        echo json_encode(['error' => 'Cannot follow yourself']);
        exit;
    }

    if ($action === 'follow') {
        // Insert if not exists
        $stmt = $pdo->prepare("INSERT IGNORE INTO follows (follower_id, following_id) VALUES (?, ?)");
        $stmt->execute([$user_id, $target_id]);
        
        // Notification Logic (Mock)
        // addNotification($target_id, 'new_follower', "Alguien te ha seguido");

        echo json_encode(['status' => 'followed', 'target_id' => $target_id]);

    } elseif ($action === 'unfollow') {
        $stmt = $pdo->prepare("DELETE FROM follows WHERE follower_id = ? AND following_id = ?");
        $stmt->execute([$user_id, $target_id]);

        echo json_encode(['status' => 'unfollowed', 'target_id' => $target_id]);
        
    } else {
        http_response_code(400);
        echo json_encode(['error' => 'Invalid action']);
    }

} catch (Exception $e) {
    http_response_code(401);
    echo json_encode(['error' => $e->getMessage()]);
}
?>
