<?php
session_start();

// Encode the IP to avoid IPv6 formatting issues
$encoded_ip = base64_encode($_SERVER['REMOTE_ADDR']);

$current_date = date('dmY');
$file = "ip_lead_limit_$current_date.txt";

// Initialize IP data array
$ip_data = [];
if (file_exists($file)) {
    $content = file_get_contents($file);
    if (!empty($content)) {
        $ip_data = unserialize($content);
    }
}

// Clean old records (older than 5 days)
$five_days_ago = strtotime('-5 days');
foreach (glob("ip_lead_limit_*.txt") as $old_file) {
    if (file_exists($old_file)) {
        $file_base = basename($old_file, '.txt');
        $date_str = str_replace('ip_lead_limit_', '', $file_base);
        $date_obj = DateTime::createFromFormat('dmY', $date_str);
        if ($date_obj !== false && $date_obj->getTimestamp() < $five_days_ago) {
            unlink($old_file); // Delete the old file
        }
    }
}

// Check and update IP data
if (isset($ip_data[$encoded_ip])) {
    $ip_data[$encoded_ip]['count']++; // Increment the count for the IP

    if ($ip_data[$encoded_ip]['count'] > 2) { // If more than 2 submissions from the same IP
        echo json_encode([
            'status' => false,
            'message' => 'You have reached the maximum number of lead submissions allowed from your IP.'
        ]);
        exit;
    }
} else {
    // Record the first submission for this IP on the current day
    $ip_data[$encoded_ip] = ['count' => 1];
}

// Save the updated IP data back to the file
file_put_contents($file, serialize($ip_data), LOCK_EX);

echo json_encode([
    'status' => true,
    'message' => 'Success'
]);
?>
