<?php
include "../db_connect.php";

$follower_id = $_POST['follower_id'];
$following_id = $_POST['following_id'];

$con = dbConnect();

if ($follower_id == $following_id) {
    echo json_encode(["success" => false, "message" => "Cannot follow yourself"]);
    exit;
}

// Check if already following
$check = $con->prepare("SELECT * FROM followers WHERE follower_id=? AND following_id=?");
$check->bind_param("ii", $follower_id, $following_id);
$check->execute();
$result = $check->get_result();

if ($result->num_rows > 0) {
    // Unfollow
    $delete = $con->prepare("DELETE FROM followers WHERE follower_id=? AND following_id=?");
    $delete->bind_param("ii", $follower_id, $following_id);
    $delete->execute();
    echo json_encode(["success" => true, "action" => "unfollow", "message" => "Unfollowed successfully"]);
} else {
    // Follow
    $insert = $con->prepare("INSERT INTO followers (follower_id, following_id) VALUES (?, ?)");
    $insert->bind_param("ii", $follower_id, $following_id);
    $insert->execute();
    echo json_encode(["success" => true, "action" => "follow", "message" => "Followed successfully"]);
}
?>
