<?php
require_once '../config.php';
$conn = require_once '../db.php';

$data = json_decode(file_get_contents("php://input"), true);
$user_id = intval($data['user_id']);

// settings থেকে ad_reward_amount খোঁজা
$reward_stmt = $conn->prepare("SELECT setting_value FROM settings WHERE setting_name = 'ad_reward_amount'");
$reward_stmt->execute();
$reward_result = $reward_stmt->get_result();
$reward_data = $reward_result->fetch_assoc();
$earning = isset($reward_data['setting_value']) ? floatval($reward_data['setting_value']) : 0.008;

// ইউজার চেক
$stmt = $conn->prepare("SELECT total_balance FROM users WHERE chat_id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows === 0) {
    echo json_encode(["success" => false, "message" => "User not found."]);
    exit;
}

// ব্যালেন্স ও বিজ্ঞাপন সংখ্যা আপডেট
$update = $conn->prepare("UPDATE users SET total_balance = total_balance + ?, total_ads_watched = total_ads_watched + 1 WHERE chat_id = ?");
$update->bind_param("di", $earning, $user_id);
$update->execute();

echo json_encode(["success" => true, "amount" => $earning]);