<?php
// batch_follow_status.php - Optimized batch endpoint for follow status
session_start();

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Content-Type: application/json');
    echo json_encode(['error' => 'Not authenticated']);
    exit;
}

$user_id = $_SESSION['user_id'];

// Database configuration
$host = 'localhost';
$db = 'digupdog_FEED';
$user = 'digupdog_FEEDadmin';
$pass = 'Raimundinho1';
$charset = 'utf8mb4';

try {
    $conn = new PDO("mysql:host=$host;dbname=$db;charset=$charset", $user, $pass);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    header('Content-Type: application/json');
    echo json_encode(['error' => 'Database connection failed']);
    exit;
}

// Get request data
$follow_type = $_POST['follow_type'] ?? '';
$follow_values = $_POST['follow_values'] ?? [];

if (empty($follow_type) || empty($follow_values)) {
    header('Content-Type: application/json');
    echo json_encode(['error' => 'Invalid parameters']);
    exit;
}

// Prepare response
$response = [];

// Build query based on follow type
$placeholders = implode(',', array_fill(0, count($follow_values), '?'));
$query = "SELECT follow_value FROM follows 
          WHERE user_id = ? 
          AND follow_type = ? 
          AND follow_value IN ($placeholders)";

try {
    $stmt = $conn->prepare($query);
    
    // Bind parameters
    $params = [$user_id, $follow_type];
    foreach ($follow_values as $value) {
        $params[] = $value;
    }
    
    $stmt->execute($params);
    $following = $stmt->fetchAll(PDO::FETCH_COLUMN);
    
    // Build response
    foreach ($follow_values as $value) {
        $response[$value] = in_array($value, $following) ? 'following' : 'not_following';
    }
    
} catch (PDOException $e) {
    header('Content-Type: application/json');
    echo json_encode(['error' => 'Query failed']);
    exit;
}

// Return response
header('Content-Type: application/json');
header('Cache-Control: max-age=60'); // Cache for 1 minute
echo json_encode($response);
?>