<?php
/**
 * Contact Requests 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, PUT, 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 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, u.profile_picture
                    FROM contact_requests cr
                    JOIN users u ON cr.target_id = u.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, u.profile_picture
                    FROM contact_requests cr
                    JOIN users u ON cr.requester_id = u.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['user_id']) ? (int)$_POST['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);

            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) {
    http_response_code(400);
    echo json_encode(['error' => $e->getMessage()]);
}
?>
