<?php
session_start();
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header("Access-Control-Allow-Headers: X-Requested-With");

if(isset($_POST['user_id']) && isset($_POST['auth']) && isset($_POST['message_id']) && isset($_POST['reported_user_id'])) {
require_once 'db/config.php'; // should set $con (PDO)

    $user_id         = trim($_POST['user_id']);        // reporter
    $auth            = trim($_POST['auth']);           // reporter auth
    $message_id      = trim($_POST['message_id']);     // reported message
    $reported_user_id= trim($_POST['reported_user_id']); // user who sent the message

    // ✅ Verify reporter
    $stmt = $con->prepare("SELECT user_id FROM users WHERE user_id = ? AND auth = ? LIMIT 1");
    $stmt->bind_param("ss", $user_id, $auth);
    $stmt->execute();
    $result = $stmt->get_result();

    if($result && $result->num_rows === 1) {
        // ✅ Insert report into reported_messages table
        $stmt2 = $con->prepare("INSERT INTO reported_messages (reporter_id, auth, message_id, reported_user_id) VALUES (?, ?, ?, ?)");
        $stmt2->bind_param("ssss", $user_id, $auth, $message_id, $reported_user_id);

        if($stmt2->execute()) {
            // ✅ Count total reports for that message
            $stmt3 = $con->prepare("SELECT COUNT(*) as total FROM reported_messages WHERE message_id = ?");
            $stmt3->bind_param("s", $message_id);
            $stmt3->execute();
            $countResult = $stmt3->get_result()->fetch_assoc();
            $totalReports = $countResult['total'];

            // ✅ If a message has been reported 5+ times, block the user who posted it
            if($totalReports >= 5) {
                $stmt4 = $con->prepare("UPDATE users SET status = 'Blocked' WHERE user_id = ?");
                $stmt4->bind_param("s", $reported_user_id);
                $stmt4->execute();
                $stmt4->close();

                $output = ['status' => true, 'message' => 'Message reported. User has been blocked.'];
            } else {
                $output = ['status' => true, 'message' => 'Message reported successfully.'];
            }

            $stmt3->close();
        } else {
            $output = ['status' => false, 'message' => 'Failed to submit message report'];
        }
        $stmt2->close();
    } else {
        $output = ['status' => false, 'message' => 'Invalid reporter credentials'];
    }

    $stmt->close();
    $con->close();
} else {
    $output = ['status' => false, 'message' => 'user_id, auth, message_id, and reported_user_id required'];
}

echo json_encode($output);
?>
