<?php
/**
 * Connections API
 * Handles researcher connections (follow/unfollow, connection requests)
 */

header('Content-Type: application/json');
require_once '../config/config.php';

// Check if user is logged in
if (!isLoggedIn()) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

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

try {
    $db = getDB();
    
    switch ($method) {
        case 'GET':
            // Get connections or connection requests
            $type = isset($_GET['type']) ? sanitize($_GET['type']) : 'connections'; // connections, pending, sent
            
            if ($type === 'connections') {
                // Get accepted connections
                $stmt = $db->prepare("
                    SELECT u.id, u.first_name, u.last_name, rp.specialization, rp.institution_id,
                           i.name as institution_name, c.created_at as connected_at
                    FROM connections c
                    JOIN users u ON (c.user_id = u.id OR c.connected_user_id = u.id) AND u.id != ?
                    LEFT JOIN researcher_profiles rp ON u.id = rp.user_id
                    LEFT JOIN institutions i ON rp.institution_id = i.id
                    WHERE (c.user_id = ? OR c.connected_user_id = ?)
                    AND c.status = 'accepted'
                    ORDER BY c.created_at DESC
                ");
                $stmt->execute([$userId, $userId, $userId]);
                $connections = $stmt->fetchAll();
                
                echo json_encode([
                    'success' => true,
                    'connections' => $connections,
                    'total' => count($connections)
                ]);
                
            } elseif ($type === 'pending') {
                // Get pending connection requests (received)
                $stmt = $db->prepare("
                    SELECT c.id as request_id, u.id, u.first_name, u.last_name, 
                           rp.specialization, i.name as institution_name, c.created_at
                    FROM connections c
                    JOIN users u ON c.user_id = u.id
                    LEFT JOIN researcher_profiles rp ON u.id = rp.user_id
                    LEFT JOIN institutions i ON rp.institution_id = i.id
                    WHERE c.connected_user_id = ? AND c.status = 'pending'
                    ORDER BY c.created_at DESC
                ");
                $stmt->execute([$userId]);
                $requests = $stmt->fetchAll();
                
                echo json_encode([
                    'success' => true,
                    'requests' => $requests,
                    'total' => count($requests)
                ]);
                
            } elseif ($type === 'sent') {
                // Get sent connection requests
                $stmt = $db->prepare("
                    SELECT c.id as request_id, u.id, u.first_name, u.last_name, 
                           rp.specialization, i.name as institution_name, c.created_at, c.status
                    FROM connections c
                    JOIN users u ON c.connected_user_id = u.id
                    LEFT JOIN researcher_profiles rp ON u.id = rp.user_id
                    LEFT JOIN institutions i ON rp.institution_id = i.id
                    WHERE c.user_id = ? AND c.status IN ('pending', 'rejected')
                    ORDER BY c.created_at DESC
                ");
                $stmt->execute([$userId]);
                $sent = $stmt->fetchAll();
                
                echo json_encode([
                    'success' => true,
                    'sent_requests' => $sent,
                    'total' => count($sent)
                ]);
            }
            break;
            
        case 'POST':
            // Send connection request
            $data = json_decode(file_get_contents('php://input'), true);
            
            if (!isset($data['user_id'])) {
                http_response_code(400);
                echo json_encode(['success' => false, 'message' => 'User ID required']);
                exit;
            }
            
            $targetUserId = (int)$data['user_id'];
            
            // Check if trying to connect with self
            if ($targetUserId === $userId) {
                http_response_code(400);
                echo json_encode(['success' => false, 'message' => 'Cannot connect with yourself']);
                exit;
            }
            
            // Check if connection already exists
            $stmt = $db->prepare("
                SELECT id, status FROM connections 
                WHERE ((user_id = ? AND connected_user_id = ?) OR (user_id = ? AND connected_user_id = ?))
            ");
            $stmt->execute([$userId, $targetUserId, $targetUserId, $userId]);
            $existing = $stmt->fetch();
            
            if ($existing) {
                if ($existing['status'] === 'accepted') {
                    echo json_encode(['success' => false, 'message' => 'Already connected']);
                } else {
                    echo json_encode(['success' => false, 'message' => 'Connection request already sent']);
                }
                exit;
            }
            
            // Create connection request
            $stmt = $db->prepare("
                INSERT INTO connections (user_id, connected_user_id, status)
                VALUES (?, ?, 'pending')
            ");
            $stmt->execute([$userId, $targetUserId]);
            $connectionId = $db->lastInsertId();
            
            // Create notification
            $stmt = $db->prepare("
                INSERT INTO notifications (user_id, type, title, message, related_id)
                VALUES (?, 'connection_request', 'New Connection Request', 'Someone wants to connect with you', ?)
            ");
            $stmt->execute([$targetUserId, $connectionId]);
            
            // Log activity
            logActivity('connection_request_sent', 'connections', $connectionId);
            
            echo json_encode([
                'success' => true,
                'message' => 'Connection request sent',
                'connection_id' => $connectionId
            ]);
            break;
            
        case 'PUT':
            // Accept or reject connection request
            $data = json_decode(file_get_contents('php://input'), true);
            
            if (!isset($data['request_id']) || !isset($data['action'])) {
                http_response_code(400);
                echo json_encode(['success' => false, 'message' => 'Request ID and action required']);
                exit;
            }
            
            $requestId = (int)$data['request_id'];
            $action = sanitize($data['action']); // accept or reject
            
            // Verify request belongs to user
            $stmt = $db->prepare("
                SELECT id, user_id FROM connections 
                WHERE id = ? AND connected_user_id = ? AND status = 'pending'
            ");
            $stmt->execute([$requestId, $userId]);
            $request = $stmt->fetch();
            
            if (!$request) {
                http_response_code(404);
                echo json_encode(['success' => false, 'message' => 'Connection request not found']);
                exit;
            }
            
            if ($action === 'accept') {
                // Accept connection
                $stmt = $db->prepare("UPDATE connections SET status = 'accepted' WHERE id = ?");
                $stmt->execute([$requestId]);
                
                // Create notification for requester
                $stmt = $db->prepare("
                    INSERT INTO notifications (user_id, type, title, message, related_id)
                    VALUES (?, 'connection_accepted', 'Connection Accepted', 'Your connection request was accepted', ?)
                ");
                $stmt->execute([$request['user_id'], $requestId]);
                
                logActivity('connection_accepted', 'connections', $requestId);
                
                echo json_encode(['success' => true, 'message' => 'Connection accepted']);
                
            } elseif ($action === 'reject') {
                // Reject connection
                $stmt = $db->prepare("UPDATE connections SET status = 'rejected' WHERE id = ?");
                $stmt->execute([$requestId]);
                
                logActivity('connection_rejected', 'connections', $requestId);
                
                echo json_encode(['success' => true, 'message' => 'Connection rejected']);
            } else {
                http_response_code(400);
                echo json_encode(['success' => false, 'message' => 'Invalid action']);
            }
            break;
            
        case 'DELETE':
            // Remove connection
            $data = json_decode(file_get_contents('php://input'), true);
            
            if (!isset($data['user_id'])) {
                http_response_code(400);
                echo json_encode(['success' => false, 'message' => 'User ID required']);
                exit;
            }
            
            $targetUserId = (int)$data['user_id'];
            
            // Delete connection
            $stmt = $db->prepare("
                DELETE FROM connections 
                WHERE ((user_id = ? AND connected_user_id = ?) OR (user_id = ? AND connected_user_id = ?))
                AND status = 'accepted'
            ");
            $stmt->execute([$userId, $targetUserId, $targetUserId, $userId]);
            
            if ($stmt->rowCount() > 0) {
                echo json_encode(['success' => true, 'message' => 'Connection removed']);
            } else {
                http_response_code(404);
                echo json_encode(['success' => false, 'message' => 'Connection not found']);
            }
            break;
            
        default:
            http_response_code(405);
            echo json_encode(['success' => false, 'message' => 'Method not allowed']);
            break;
    }
    
} catch (Exception $e) {
    error_log("Connections API error: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Internal server error']);
}
?>
