<?php
require_once('../includes/init.php');

$res = (object) array();
$res->success = false;
$res->message = '';

// --- 1. Validate POST Method ---
if($_SERVER['REQUEST_METHOD'] !== "POST") {
    $res->message = "Connect VPN!";
    die(json_encode($res));
}

// --- 2. Validate Authorization ---
if(base64_decode($_SERVER['HTTP_AUTHORIZATION']) !== $_POST['user']) {
    $res->message = "Connect VPN!";
    die(json_encode($res));
}

// --- 3. Validate Device ID ---
if(empty($_POST['did'])) {
    $res->message = "Connect VPN!";
    die(json_encode($res));
}

// --- 4. Setup columns based on task ---
$col_todayTask = 'today_task';
$col_taskTime = 'task_time1';

if($_POST['task-app'] > 5){
    $res->message = "Connect VPN!";
    die(json_encode($res));
}

if($multi_task == 1){
    if($_POST['task-app'] > 0) {
        $col_todayTask = 'today_task' . $_POST['task-app'];
        $col_taskTime = 'task_time1' . $_POST['task-app'];
    }
}

if($spin == 1 || $spin_task == 1){ 
    if ($_POST['task-app'] == 5) {
        $task_limitmonetag = $spin_click;
        $col_todayTask = 'today_spin';
        $col_taskTime = 'spin_time';
    }
}

if($_POST['task-app'] != 5){
    if($task_enabled == 0 ) {
        $res->success = false;
        $res->message = 'Task closed';
        die(json_encode($res));
    }
} else {
    if($spin_enabled == 0 ) {
        $res->success = false;
        $res->message = 'Spin closed';
        die(json_encode($res));
    }
}

// --- 5. Get token ---
$token = compactify($conn, base64_decode($_POST['user']));
$token = preg_replace('/[^a-z0-9 ]/i', '', $token);

$res->balance = 0;

// --- 6. Fetch user data ---
$sql = "SELECT *, TIMESTAMPDIFF(MINUTE, $col_taskTime, NOW()) AS time_diff
        FROM users WHERE users.token = '{$token}'";
$result = mysqli_query($conn, $sql);

if (!mysqli_num_rows($result) == 1) {
    $res->success = false;
    $res->message = "User not found";
    die(json_encode($res));
}

$user_data = mysqli_fetch_assoc($result);
$res->balance = $user_data['balance'];

if ($user_data["$col_todayTask"] >= $task_limitmonetag) {
    $res->message = 'Daily limit reached';
    die(json_encode($res));
}

if ($user_data['i_click'] > $invalid_limit) {
    $res->message = 'Account blocked';
    die(json_encode($res));
}

// --- 7. Check device ID ---
if ($task_did == 1 && $_POST['did'] != $user_data['did']) {
    $res->message = "Connect VPN!";
    die(json_encode($res));
}

// --- 8. Check task timer ---
if($_POST['task-app'] != 5){
    if ($user_data['time_diff'] < $task_timerr) {
        $time_left = $task_timerr - $user_data['time_diff'];
        $res->success = false;
        $res->message = "Wait {$time_left} minute";
        die(json_encode($res));
    }
}

// --- 9. Log optional IP + country (for testing) ---
$user_ip = $_POST['ip'] ?? $_SERVER['REMOTE_ADDR'];
$country = $_POST['country'] ?? 'UNKNOWN';

// sanitize IP and country
$user_ip = filter_var($user_ip, FILTER_VALIDATE_IP) ? $user_ip : $_SERVER['REMOTE_ADDR'];
$country = preg_replace('/[^a-zA-Z0-9]/', '', $country);

// Append to text file
$log_line = date('Y-m-d H:i:s') . " | Token: {$token} | IP: {$user_ip} | Country: {$country}\n";
$log_file = __DIR__ . '/ip_test_log.txt'; // same folder as this PHP script
file_put_contents($log_file, $log_line, FILE_APPEND);


// --- 10. Process task reward ---
if($_POST['api-task'] == $user_data['api_task'] && $view_target <= $user_data['view_success']) {

    $ref = $user_data['ref'];
    $ref_comission = round($task_rewardmonetagsr * $ref_comission / 100);

    $number = $user_data['mobile'];
    $unique = uniqid();

    $sql = "UPDATE users SET 
                balance = balance + {$task_rewardmonetagsr}, 
                $col_todayTask = $col_todayTask + 1, 
                $col_taskTime = NOW(), 
                api_task = '$unique', 
                view_success = '0' 
            WHERE users.token = '{$token}';
            UPDATE users SET balance = balance + {$ref_comission} WHERE users.mobile = '{$ref}';
            INSERT INTO history (number, amount, status, ip, country)
VALUES ('$number', '$task_rewardmonetagsr', 'Task Added', '$user_ip', '$country')";

    if ($conn->multi_query($sql) === TRUE) {
        $res->balance = (int)$user_data['balance'] + $task_rewardmonetagsr;
        $res->success = true;
        $res->message = "{$task_rewardmonetagsr} Points added!";
        die(json_encode($res));
    } else {
        $res->message = 'Database error: ' . mysqli_error($conn);
        die(json_encode($res));
    }

} else {
    $conn->query("UPDATE users SET view_success = '0' WHERE users.token = '{$token}'");
    $res->success = false;
    $res->message = 'You Are Legend';
}

$conn->close();
echo json_encode($res);
?>
