<?php
/**
 * Follow/Unfollow API
 * OBGYN Research Platform
 */

require_once '../config/config.php';

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, DELETE');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if (!isLoggedIn()) {
    http_response_code(401);
    echo json_encode(['error' => 'Authentication required']);
    exit;
}

$userId = getCurrentUserId();
$method = $_SERVER['REQUEST_METHOD'];
$db = getDB();

try {
    switch ($method) {
        case 'GET':
            // Get followers/following
            $type = $_GET['type'] ?? 'following'; // followers or following
            $targetUserId = isset($_GET['user_id']) ? (int)$_GET['user_id'] : $userId;

            if ($type === 'followers') {
                $stmt = $db->prepare("
                    SELECT u.id, u.first_name, u.last_name, u.email, u.profile_picture,
                           f.created_at as followed_at
                    FROM followers f
                    JOIN users u ON f.follower_id = u.id
                    WHERE f.following_id = ?
                    ORDER BY f.created_at DESC
                ");
                $stmt->execute([$targetUserId]);
            } else {
                $stmt = $db->prepare("
                    SELECT u.id, u.first_name, u.last_name, u.email, u.profile_picture,
                           f.created_at as followed_at
                    FROM followers f
                    JOIN users u ON f.following_id = u.id
                    WHERE f.follower_id = ?
                    ORDER BY f.created_at DESC
                ");
                $stmt->execute([$targetUserId]);
            }

            $users = $stmt->fetchAll();
            echo json_encode(['success' => true, 'data' => $users]);
            break;

        case 'POST':
            // Follow a user
            $targetUserId = isset($_POST['user_id']) ? (int)$_POST['user_id'] : 0;

            if (!$targetUserId) {
                throw new Exception('Target user ID required');
            }

            if ($targetUserId === $userId) {
                throw new Exception('Cannot follow yourself');
            }

            // Check if already following
            $stmt = $db->prepare("SELECT id FROM followers WHERE follower_id = ? AND following_id = ?");
            $stmt->execute([$userId, $targetUserId]);
            if ($stmt->fetch()) {
                throw new Exception('Already following this user');
            }

            // Add follow relationship
            $stmt = $db->prepare("INSERT INTO followers (follower_id, following_id) VALUES (?, ?)");
            $stmt->execute([$userId, $targetUserId]);

            // Log activity
            logActivity('user_followed', 'users', $targetUserId);

            // Create notification for the followed user
            $stmt = $db->prepare("SELECT first_name, last_name FROM users WHERE id = ?");
            $stmt->execute([$userId]);
            $follower = $stmt->fetch();
            
            if ($follower) {
                $followerName = $follower['first_name'] . ' ' . $follower['last_name'];
                createNotification(
                    $targetUserId,
                    'follow',
                    'New Follower',
                    $followerName . ' started following you.',
                    SITE_URL . '/public/researcher-profile.php?id=' . $userId
                );
            }

            echo json_encode(['success' => true, 'message' => 'User followed successfully']);
            break;

        case 'DELETE':
            // Unfollow a user
            $targetUserId = isset($_GET['user_id']) ? (int)$_GET['user_id'] : 0;

            if (!$targetUserId) {
                throw new Exception('Target user ID required');
            }

            // Remove follow relationship
            $stmt = $db->prepare("DELETE FROM followers WHERE follower_id = ? AND following_id = ?");
            $stmt->execute([$userId, $targetUserId]);

            if ($stmt->rowCount() === 0) {
                throw new Exception('Not following this user');
            }

            // Log activity
            logActivity('user_unfollowed', 'users', $targetUserId);

            echo json_encode(['success' => true, 'message' => 'User unfollowed successfully']);
            break;

        default:
            http_response_code(405);
            echo json_encode(['error' => 'Method not allowed']);
            break;
    }

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