<?php
ini_set("max_execution_time", 0);
error_reporting(E_ALL);
ini_set('display_errors', 1);
header("Content-Type: application/json");

include '../connection.php'; 

$response = array();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Get user ID from POST
    $referrer_id = isset($_POST['referrer_id']) ? intval($_POST['referrer_id']) : 0;

    if ($referrer_id > 0) {
        try {
            
            $sqlQuery = "SELECT COUNT(*) AS referral_count 
                         FROM tbl_referrals 
                         WHERE referrer_id = ? AND is_used = 0";

            $stmt = $conn->prepare($sqlQuery);
            $stmt->bind_param("i", $referrer_id);
            $stmt->execute();
            $result = $stmt->get_result()->fetch_assoc();

            $response['success'] = true;
            $response['referral_count'] = $result['referral_count'] ?? 0;
        } catch (Exception $e) {
            $response['success'] = false;
            $response['message'] = "Error: " . $e->getMessage();
        }
    } else {
        $response['success'] = false;
        $response['message'] = "Invalid referrer_id";
    }
} else {
    $response['success'] = false;
    $response['message'] = "Invalid request method";
}

echo json_encode($response);
