<?php
// File: /xu-ly-dang-robux/index.php hoặc /xu-ly-dang-robux.php
session_start();
require_once $_SERVER['DOCUMENT_ROOT'].'/hethong/config.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/hethong/function.php';

// Kiểm tra đăng nhập
if (!isset($user['id'])) {
    $_SESSION['error'] = 'Vui lòng đăng nhập để đăng bán Robux!';
    header('Location: /dang-nhap');
    exit;
}

// Kiểm tra phương thức POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: /dang-ban-robux');
    exit;
}

// Lấy dữ liệu từ form
$user_id        = $user['id'];
$robux_amount   = isset($_POST['robux_amount']) ? intval($_POST['robux_amount']) : 0;
$price          = isset($_POST['price']) ? intval($_POST['price']) : 0;
$original_price = isset($_POST['original_price']) ? intval($_POST['original_price']) : 0;
$total_stock    = isset($_POST['total_stock']) ? intval($_POST['total_stock']) : 0;
$description    = isset($_POST['description']) ? trim(mysqli_real_escape_string($ketnoi, $_POST['description'])) : '';
$is_hot         = isset($_POST['is_hot']) ? 1 : 0;

// Mảng lưu lỗi
$errors = [];

// Validate dữ liệu
if ($robux_amount < 10 || $robux_amount > 100000) {
    $errors[] = 'Số lượng Robux phải từ 10 đến 100.000!';
}

if ($price < 1000) {
    $errors[] = 'Giá bán tối thiểu là 1.000đ!';
}

if ($total_stock < 1 || $total_stock > 500) {
    $errors[] = 'Số lượng gói bán phải từ 1 đến 500!';
}

if ($original_price > 0 && $original_price <= $price) {
    $errors[] = 'Giá gốc phải lớn hơn giá bán nếu có khuyến mãi!';
}

// Kiểm tra tỷ giá (cảnh báo nếu quá thấp hoặc quá cao)
$rate = $price / $robux_amount;
if ($rate < 100) {
    $errors[] = 'Giá bán quá thấp so với thị trường (tối thiểu ~100đ/Robux)! Vui lòng kiểm tra lại.';
}
if ($rate > 500) {
    $errors[] = 'Giá bán quá cao so với thị trường (tối đa ~500đ/Robux)! Khách hàng sẽ khó mua.';
}

// Kiểm tra mô tả
if (strlen($description) > 200) {
    $errors[] = 'Mô tả không được vượt quá 200 ký tự!';
}

// Nếu có lỗi, quay lại form
if (!empty($errors)) {
    $_SESSION['error'] = implode('<br>', $errors);
    $_SESSION['form_data'] = $_POST; // Lưu lại dữ liệu đã nhập
    header('Location: /dang-ban-robux');
    exit;
}

// Tính phần trăm giảm giá
$discount_percent = 0;
if ($original_price > 0 && $original_price > $price) {
    $discount_percent = round((1 - $price / $original_price) * 100);
}

// Thêm vào database
$sql = "INSERT INTO robux_packages (
            user_id, 
            robux_amount, 
            price, 
            original_price, 
            discount_percent,
            seller_name, 
            stock, 
            total_stock, 
            description, 
            is_hot, 
            status, 
            created_at
        ) VALUES (
            $user_id,
            $robux_amount,
            $price,
            " . ($original_price > 0 ? $original_price : 'NULL') . ",
            $discount_percent,
            '" . mysqli_real_escape_string($ketnoi, $user['username']) . "',
            $total_stock,
            $total_stock,
            '$description',
            $is_hot,
            'pending', -- Chờ admin duyệt
            NOW()
        )";

if (mysqli_query($ketnoi, $sql)) {
    $package_id = mysqli_insert_id($ketnoi);
    
    // Ghi log
    $log_content = "Người dùng {$user['username']} (ID: $user_id) đã đăng gói Robux #$package_id: {$robux_amount} Robux với giá " . number_format($price) . "đ, tổng $total_stock gói";
    mysqli_query($ketnoi, "INSERT INTO logs (user_id, action, content, created_at) VALUES ($user_id, 'dang_robux', '" . mysqli_real_escape_string($ketnoi, $log_content) . "', NOW())");
    
    $_SESSION['success'] = "Đăng bán gói Robux thành công! Mã gói: #$package_id. Admin sẽ duyệt trong vòng 5-15 phút.";
    header('Location: /lich-su-ban-robux'); // Trang lịch sử bán của người dùng
} else {
    $_SESSION['error'] = 'Có lỗi xảy ra khi đăng bán. Vui lòng thử lại sau!';
    header('Location: /dang-ban-robux');
}
exit;