
<?php

class SpamProtection
{

    /*
    Block duplicate phone within X minutes
    */

    public static function duplicateLead($phone,$minutes = 30)
    {

        $db = new Database();
        $conn = $db->connect();

        $stmt = $conn->prepare("

        SELECT id

        FROM customer_leads

        WHERE phone = :phone
        AND created_at >= DATE_SUB(NOW(), INTERVAL :minutes MINUTE)

        LIMIT 1

        ");

        $stmt->execute([
            ':phone' => $phone,
            ':minutes' => $minutes
        ]);

        if($stmt->fetch()){
            Response::error("You already submitted a request recently. Please wait.");
        }

    }



    /*
    Block excessive leads from same IP
    */

    public static function rateLimit($ip,$limit = 5,$minutes = 10)
    {

        $db = new Database();
        $conn = $db->connect();

        $stmt = $conn->prepare("

        SELECT COUNT(*)

        FROM customer_leads

        WHERE user_ip = :ip
        AND created_at >= DATE_SUB(NOW(), INTERVAL :minutes MINUTE)

        ");

        $stmt->execute([
            ':ip' => $ip,
            ':minutes' => $minutes
        ]);

        $count = $stmt->fetchColumn();

        if($count >= $limit){

            Response::error("Too many requests. Please try again later.");

        }

    }



    /*
    Basic phone validation
    */

    public static function validatePhone($phone)
    {

        if(!preg_match('/^[6-9][0-9]{9}$/',$phone)){
            Response::error("Invalid phone number");
        }

    }



    /*
    Detect bots via user agent
    */

    public static function botCheck()
    {

        $agent = $_SERVER['HTTP_USER_AGENT'] ?? '';

        $bots = [
            'bot',
            'crawl',
            'spider',
            'curl',
            'wget'
        ];

        foreach($bots as $bot){

            if(stripos($agent,$bot) !== false){

                Response::error("Bot traffic detected");

            }

        }

    }

}