<?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['reported_id'])) {
require_once 'db/config.php'; // should set $con (PDO)

    $user_id     = trim($_POST['user_id']);     // reporter
    $auth        = trim($_POST['auth']);        // reporter auth
    $reported_id = trim($_POST['reported_id']); // user being reported

    // ✅ 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
        $stmt2 = $con->prepare("INSERT INTO reports (user_id, reported_id) VALUES (?, ?)");
        $stmt2->bind_param("ss", $user_id, $reported_id);

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

            // ✅ If 5 or more reports, block the user
            if($totalReports >= 5) {
                $stmt4 = $con->prepare("UPDATE users SET status = 'Blocked' WHERE user_id = ?");
                $stmt4->bind_param("s", $reported_id);
                $stmt4->execute();
                $stmt4->close();

                $output = ['status' => true, 'success' => 'Report submitted. User has been blocked.'];
            } else {
                $output = ['status' => true, 'success' => 'Report submitted successfully.'];
            }

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

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

echo json_encode($output);
?>
