<?php
/**
 * Contact Requests API
 * OBGYN Research Platform
 */

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

// Set proper headers for same-origin API requests
header('Content-Type: application/json');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

// Handle preflight requests
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

// Debugging: Log session and authentication status
error_log('API Request - Session ID: ' . session_id());
error_log('API Request - Session contents: ' . print_r($_SESSION, true));
error_log('API Request - isLoggedIn: ' . (isLoggedIn() ? 'true' : 'false'));
error_log('API Request - User ID: ' . (getCurrentUserId() ?: 'none'));

// Check authentication
if (!isLoggedIn()) {
    http_response_code(401);
    echo json_encode([
        'success' => false,
        'error' => 'Authentication required',
        'message' => 'Please log in to access this resource.'
    ]);
    exit;
}

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

// Double-check userId is valid
if (!$userId) {
    http_response_code(401);
    echo json_encode([
        'success' => false,
        'error' => 'User not authenticated',
        'message' => 'Invalid user session. Please log in again.'
    ]);
    exit;
}

try {
    switch ($method) {
        case 'GET':
            // Get contact requests (sent or received)
            $type = $_GET['type'] ?? 'received'; // sent or received

            if ($type === 'sent') {
                $stmt = $db->prepare("
                    SELECT cr.*, u.first_name, u.last_name, u.email, rp.photo,
                           rp.specialization, rp.institution_id, i.name as institution_name
                    FROM contact_requests cr
                    JOIN users u ON cr.target_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 cr.requester_id = ?
                    ORDER BY cr.created_at DESC
                ");
                $stmt->execute([$userId]);
            } else {
                $stmt = $db->prepare("
                    SELECT cr.*, u.first_name, u.last_name, u.email, rp.photo,
                           rp.specialization, rp.institution_id, i.name as institution_name
                    FROM contact_requests cr
                    JOIN users u ON cr.requester_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 cr.target_id = ?
                    ORDER BY cr.created_at DESC
                ");
                $stmt->execute([$userId]);
            }

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

        case 'POST':
            // Send contact request
            $targetUserId = isset($_POST['target_user_id']) ? (int)$_POST['target_user_id'] : 0;
            $message = sanitize($_POST['message'] ?? '');

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

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

            // Check if request already exists
            $stmt = $db->prepare("
                SELECT id FROM contact_requests
                WHERE (requester_id = ? AND target_id = ?) OR (requester_id = ? AND target_id = ?)
            ");
            $stmt->execute([$userId, $targetUserId, $targetUserId, $userId]);
            if ($stmt->fetch()) {
                throw new Exception('Contact request already exists');
            }

            // Create contact request
            $stmt = $db->prepare("
                INSERT INTO contact_requests (requester_id, target_id, message)
                VALUES (?, ?, ?)
            ");
            $stmt->execute([$userId, $targetUserId, $message]);

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

            // Create notification for the target user
            $stmt = $db->prepare("SELECT first_name, last_name FROM users WHERE id = ?");
            $stmt->execute([$userId]);
            $requester = $stmt->fetch();

            if ($requester) {
                $requesterName = $requester['first_name'] . ' ' . $requester['last_name'];
                createNotification(
                    $targetUserId,
                    'contact_request',
                    'New Contact Request',
                    $requesterName . ' has requested to view your contact information.',
                    SITE_URL . '/researcher/contact-requests.php'
                );
            }

            echo json_encode(['success' => true, 'message' => 'Contact request sent successfully']);
            break;

        case 'PUT':
            // Respond to contact request
            $requestId = isset($_POST['request_id']) ? (int)$_POST['request_id'] : 0;
            $action = $_POST['action'] ?? ''; // approve or reject
            $responseMessage = sanitize($_POST['response_message'] ?? '');

            if (!$requestId || !in_array($action, ['approve', 'reject'])) {
                throw new Exception('Invalid request parameters');
            }

            // Get request and verify ownership
            $stmt = $db->prepare("SELECT * FROM contact_requests WHERE id = ? AND target_id = ?");
            $stmt->execute([$requestId, $userId]);
            $request = $stmt->fetch();

            if (!$request) {
                throw new Exception('Contact request not found');
            }

            if ($request['status'] !== 'pending') {
                throw new Exception('Request has already been responded to');
            }

            // Update request
            $status = $action === 'approve' ? 'approved' : 'rejected';
            $stmt = $db->prepare("
                UPDATE contact_requests
                SET status = ?, response_message = ?, responded_at = NOW(), responded_by = ?
                WHERE id = ?
            ");
            $stmt->execute([$status, $responseMessage, $userId, $requestId]);

            // Log activity
            logActivity('contact_request_' . $action . 'd', 'users', $request['requester_id']);

            echo json_encode(['success' => true, 'message' => 'Contact request ' . $action . 'd successfully']);
            break;

        case 'DELETE':
            // Delete contact request
            $requestId = isset($_GET['request_id']) ? (int)$_GET['request_id'] : 0;

            if (!$requestId) {
                throw new Exception('Request ID required');
            }

            // Delete request (only if user is involved)
            $stmt = $db->prepare("
                DELETE FROM contact_requests
                WHERE id = ? AND (requester_id = ? OR target_id = ?)
            ");
            $stmt->execute([$requestId, $userId, $userId]);

            if ($stmt->rowCount() === 0) {
                throw new Exception('Contact request not found or access denied');
            }

            echo json_encode(['success' => true, 'message' => 'Contact request deleted successfully']);
            break;

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

} catch (Exception $e) {
    error_log('API Error in contact-requests.php: ' . $e->getMessage());
    error_log('Stack trace: ' . $e->getTraceAsString());
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage(),
        'message' => 'An error occurred while processing your request.'
    ]);
}
?>
