<?php
require_once('ketnoi.php');
session_start();

// Set response header
header('Content-Type: application/json');

if(!isset($_SESSION['session'])) {
    echo json_encode(['status' => 'error', 'message' => 'Vui lòng đăng nhập']);
    exit();
}

$session = $_SESSION['session'];
$user_result = $ketnoi->query("SELECT * FROM `users` WHERE `session` = '$session'");
if(!$user_result || $user_result->num_rows == 0) {
    echo json_encode(['status' => 'error', 'message' => 'Phiên đăng nhập không hợp lệ']);
    exit();
}
$user = $user_result->fetch_array();

$plan_id = isset($_POST['plan_id']) ? (int)$_POST['plan_id'] : 0;
$domain = isset($_POST['domain']) ? trim($_POST['domain']) : '';
$duration = isset($_POST['duration']) ? (int)$_POST['duration'] : 0;
$voucher = isset($_POST['voucher']) ? trim($_POST['voucher']) : '';

if(!$plan_id || !$domain || !$duration) {
    echo json_encode(['status' => 'error', 'message' => 'Thiếu thông tin đặt hàng']);
    exit();
}

// Lấy thông tin gói hosting
$plan_result = $ketnoi->query("SELECT * FROM `hosting_plans` WHERE `id` = $plan_id AND `status` = 1");
if(!$plan_result || $plan_result->num_rows == 0) {
    echo json_encode(['status' => 'error', 'message' => 'Gói hosting không tồn tại']);
    exit();
}
$plan = $plan_result->fetch_array();

// Tính giá
$price = !empty($plan['sale_price']) ? $plan['sale_price'] : $plan['price'];
$base_total = $price * $duration;

$discount = 0;
if($duration == 3) $discount = 0.05;
elseif($duration == 6) $discount = 0.1;
elseif($duration == 12) $discount = 0.2;
elseif($duration == 24) $discount = 0.25;

$duration_discount = $base_total * $discount;
$total = $base_total - $duration_discount;

// Áp dụng voucher
if($voucher === 'KHANH20') {
    $voucher_discount = $total * 0.2;
    $total -= $voucher_discount;
} elseif($voucher === 'HOSTING10') {
    $voucher_discount = $total * 0.1;
    $total -= $voucher_discount;
}

$total = max(0, (int)$total);

// Kiểm tra số dư
if($user['money'] < $total) {
    echo json_encode(['status' => 'error', 'message' => 'Số dư không đủ. Cần ' . number_format($total) . 'đ']);
    exit();
}

// Tạo thông tin hosting
$hosting_username = strtolower(substr(preg_replace('/[^a-zA-Z0-9]/', '', $domain), 0, 15)) . rand(100, 999);
$hosting_password = substr(str_shuffle('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'), 0, 12);

// Tạo bảng lịch sử mua hosting nếu chưa có
$ketnoi->query("CREATE TABLE IF NOT EXISTS `lich_su_mua_host` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `username` varchar(100) NOT NULL,
    `plan_id` int(11) NOT NULL,
    `plan_name` varchar(100) NOT NULL,
    `domain` varchar(255) NOT NULL,
    `hosting_username` varchar(100) NOT NULL,
    `hosting_password` varchar(100) NOT NULL,
    `duration` int(11) NOT NULL,
    `price` int(11) NOT NULL,
    `total` int(11) NOT NULL,
    `status` varchar(20) DEFAULT 'active',
    `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    `expired_at` timestamp NULL DEFAULT NULL,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

// Tạo bảng lịch sử giao dịch nếu chưa có
$ketnoi->query("CREATE TABLE IF NOT EXISTS `lich_su_giao_dich` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `username` varchar(100) NOT NULL,
    `noi_dung` text NOT NULL,
    `so_tien` int(11) NOT NULL,
    `type` enum('nap','chi','refund') NOT NULL,
    `time` datetime NOT NULL,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

// Lưu lịch sử
$expired = date('Y-m-d H:i:s', strtotime("+{$duration} months"));
$stmt = $ketnoi->prepare("INSERT INTO `lich_su_mua_host` 
    (`username`, `plan_id`, `plan_name`, `domain`, `hosting_username`, `hosting_password`, `duration`, `price`, `total`, `expired_at`) 
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param("sissssiiis", $user['username'], $plan_id, $plan['name'], $domain, $hosting_username, $hosting_password, $duration, $price, $total, $expired);
$stmt->execute();

// Trừ tiền
$ketnoi->query("UPDATE `users` SET `money` = `money` - $total WHERE `id` = " . $user['id']);

// Ghi log
$noi_dung = "Mua hosting " . addslashes($plan['name']) . " - $domain";
$time = date('Y-m-d H:i:s');
$ketnoi->query("INSERT INTO `lich_su_giao_dich` (`username`, `noi_dung`, `so_tien`, `type`, `time`) 
    VALUES ('{$user['username']}', '$noi_dung', '$total', 'chi', '$time')");

echo json_encode([
    'status' => 'success',
    'message' => 'Mua hosting thành công!',
    'domain' => $domain,
    'username' => $hosting_username,
    'password' => $hosting_password
]);
?>