<?php
/**
 * ============================================================================
 * chat/ajax/report-user.php - Report User Endpoint
 * ============================================================================
 */
define('AIMS_ACCESS', true);
require_once __DIR__ . '/../../config/config.php';

header('Content-Type: application/json');

if (!isLoggedIn()) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Not authenticated']);
    exit;
}

try {
    $userId = getUserId();
    $reportedUserId = isset($_POST['user_id']) ? (int)$_POST['user_id'] : 0;
    $chatId = isset($_POST['chat_id']) ? (int)$_POST['chat_id'] : null;
    $reportType = isset($_POST['report_type']) ? $_POST['report_type'] : '';
    $description = isset($_POST['description']) ? trim($_POST['description']) : '';
    
    if (!$reportedUserId) {
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'message' => 'User ID is required'
        ]);
        exit;
    }
    
    if ($reportedUserId == $userId) {
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'message' => 'You cannot report yourself'
        ]);
        exit;
    }
    
    $validTypes = ['spam', 'harassment', 'fake_profile', 'inappropriate_content', 'scam', 'other'];
    if (!in_array($reportType, $validTypes)) {
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'message' => 'Invalid report type'
        ]);
        exit;
    }
    
    $database = \App\Database::getInstance();
    $db = $database->getConnection();
    
    // Insert report
    $insertQuery = "INSERT INTO user_reports 
                    (reporter_id, reported_user_id, chat_id, report_type, description, status, created_at) 
                    VALUES (?, ?, ?, ?, ?, 'pending', NOW())";
    
    $stmt = $db->prepare($insertQuery);
    $success = $stmt->execute([$userId, $reportedUserId, $chatId, $reportType, $description]);
    
    if ($success) {
        $reportId = $db->lastInsertId();
        
        // Notify admins
        $notifyQuery = "INSERT INTO notifications (user_id, title, message, type, icon, link, created_at)
                       SELECT id, 'New User Report', 
                              CONCAT('User reported for: ', ?),
                              'warning', 'flag', '/admin/reports.php', NOW()
                       FROM users WHERE user_type = 'admin'";
        $stmt = $db->prepare($notifyQuery);
        $stmt->execute([$reportType]);
        
        // Log the action
        $logQuery = "INSERT INTO activity_log (user_id, action, description, created_at)
                     VALUES (?, 'report_user', ?, NOW())";
        $stmt = $db->prepare($logQuery);
        $stmt->execute([$userId, "Reported user ID: $reportedUserId for $reportType"]);
        
        echo json_encode([
            'success' => true,
            'message' => 'Report submitted successfully. Our team will review it.',
            'report_id' => $reportId
        ]);
    } else {
        throw new \Exception('Failed to submit report');
    }
    
} catch (\Exception $e) {
    error_log('Report user error: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Failed to submit report: ' . $e->getMessage()
    ]);
}