<?php
session_start();

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Allow-Headers: Content-Type");
header("Content-Type: application/json");

if (
    isset($_POST['user_id']) &&
    isset($_POST['auth']) &&
    isset($_POST['blocked_user_id'])
) {

    require_once 'db/config.php';

    $user_id         = trim($_POST['user_id']);
    $auth            = trim($_POST['auth']);
    $blocked_user_id = trim($_POST['blocked_user_id']);

    // Verify user
    $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->num_rows > 0) {

        // Check if already blocked
        $check = $con->prepare("
            SELECT id 
            FROM blocked_users 
            WHERE user_id = ? AND blocked_user_id = ?
            LIMIT 1
        ");
        $check->bind_param("ss", $user_id, $blocked_user_id);
        $check->execute();
        $checkResult = $check->get_result();

        if ($checkResult->num_rows > 0) {

            $output = [
                'status' => false,
                'success' => 'User already blocked'
            ];

        } else {

            // Block user
            $insert = $con->prepare("
                INSERT INTO blocked_users (user_id, blocked_user_id)
                VALUES (?, ?)
            ");
            $insert->bind_param("ss", $user_id, $blocked_user_id);

            if ($insert->execute()) {

                $output = [
                    'status' => true,
                    'success' => 'User blocked successfully'
                ];

            } else {

                $output = [
                    'status' => false,
                    'success' => 'Failed to block user'
                ];
            }

            $insert->close();
        }

        $check->close();

    } else {

        $output = [
            'status' => false,
            'success' => 'Invalid credentials'
        ];
    }

    $stmt->close();
    $con->close();

} else {

    $output = [
        'status' => false,
        'success' => 'user_id, auth and blocked_user_id are required'
    ];
}

echo json_encode($output);
?>