<?php

define("IN_SITE", true);
require_once(__DIR__."/../../libs/db.php");
require_once(__DIR__."/../../libs/lang.php");
require_once(__DIR__."/../../libs/helper.php");
$CMSNT = new DB();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (empty($_POST['amount'])) {
        die(format_currency(0));
    }
    
    // Validate token input
    $token = validate_alphanumeric($_POST['token'], 255);
    if ($token === false) {
        die(__('Vui lòng đăng nhập'));
    }
    
    // Use prepared statement for user lookup
    if (!$getUser = $CMSNT->get_row_safe("SELECT * FROM `users` WHERE `token` = ?", [$token])) {
        die(__('Vui lòng đăng nhập'));
    }
    
    // Validate amount as float
    $received = validate_float($_POST['amount'], 0.01);
    if ($received === false) {
        die(format_currency(0));
    }
    
    // Use prepared statement for promotions query
    foreach($CMSNT->get_list_safe("SELECT * FROM `promotions` WHERE `amount` <= ? AND `status` = 1 ORDER BY `amount` DESC", [$received]) as $promotion){
        // $received là thực nhận sau khi thanh toán đủ $amount
        $received = $received + $received * $promotion['discount'] / 100;
        break;
    } 
    die(format_currency($received));
    
}
die(format_currency(0));
