<?php

define("IN_SITE", true);

require_once(__DIR__."/../../libs/db.php");
require_once(__DIR__."/../../libs/helper.php");
require_once(__DIR__.'/../../models/is_ctv.php');

$CMSNT = new DB();
$data = [];
$i = 0;

// Validate user ID để đảm bảo an toàn
$user_id = validate_int($getUser['id'], 1);
if ($user_id === false) {
    echo json_encode(['data' => [], 'error' => 'Invalid user ID'], JSON_PRETTY_PRINT);
    exit();
}

// Sử dụng prepared statement để tránh SQL injection
$orders = $CMSNT->get_list_safe("SELECT * FROM `orders` WHERE `seller` = ? ORDER BY id DESC", [$user_id]);

foreach ($orders as $row) {
    $trans_id = $row['trans_id'];
    
    // Validate trans_id để đảm bảo an toàn khi hiển thị
    $safe_trans_id = validate_alphanumeric($trans_id);
    if ($safe_trans_id === false) {
        $safe_trans_id = 'INVALID';
    }
    
    $data[] = [
        'stt'           => $i++,
        'buyer'         => '<a href="#">'.htmlspecialchars(getUser($row['buyer'], 'username'), ENT_QUOTES, 'UTF-8').'</a>',
        'trans_id'      => htmlspecialchars($row['trans_id'], ENT_QUOTES, 'UTF-8'),
        'product_id'    => '<b>'.htmlspecialchars(getRowRealtime("products", $row['product_id'], 'name'), ENT_QUOTES, 'UTF-8').'</b>',
        'amount'        => '<b style="color:blue;">'.format_cash($row['amount']).'</b>',
        'pay'           => '<b style="color:red;">'.format_currency($row['pay']).'</b>',
        'create_date'   => htmlspecialchars($row['create_date'], ENT_QUOTES, 'UTF-8'),
        'action'        => '<button type="button" onclick="showAccounts(`'.htmlspecialchars($safe_trans_id, ENT_QUOTES, 'UTF-8').'`)" class="btn btn-primary btn-sm showAccounts">Xem Thêm</button>'
    ];
}

echo json_encode(['data' => $data], JSON_PRETTY_PRINT);
exit();
