<?php
// Định nghĩa đầu số theo nhà mạng
$prefixes = [
    'viettel' => ['032', '033', '034', '035', '036', '037', '038', '039'],
    'vinaphone' => ['081', '082', '083', '084', '085', '088'],
    'mobifone' => ['070', '076', '077', '078', '079', '089'],
    'vietnamobile' => ['056', '058'],
    'gmobile' => ['059']
];

// Nhận dữ liệu từ form
$carriers = $_POST['carriers'] ?? [];
$amount = intval($_POST['amount'] ?? 1000);
$chunks = intval($_POST['chunks'] ?? 1);

// Kiểm tra đầu vào
if (empty($carriers) || $amount < 1 || $chunks < 1) {
    die("Vui lòng chọn nhà mạng và số lượng hợp lệ.");
}

// Tạo danh sách đầu số được chọn
$allPrefixes = [];
foreach ($carriers as $carrier) {
    if (isset($prefixes[$carrier])) {
        $allPrefixes = array_merge($allPrefixes, $prefixes[$carrier]);
    }
}

// Tính số mỗi file
$perFile = ceil($amount / $chunks);

// Hàm tạo số điện thoại không trùng
function generateUniquePhones($prefixes, $count) {
    $numbers = [];
    $totalDigits = 10;
    while (count($numbers) < $count) {
        $prefix = $prefixes[array_rand($prefixes)];
        $suffix = str_pad(strval(mt_rand(0, 9999999)), 7, '0', STR_PAD_LEFT);
        $number = $prefix . $suffix;
        $numbers[$number] = true;
    }
    return array_keys($numbers);
}

// Tạo thư mục nếu chưa có
$outputDir = __DIR__ . '/downloads/';
if (!is_dir($outputDir)) {
    mkdir($outputDir, 0777, true);
}

// Tạo các file danh sách
$fileLinks = [];
$totalCreated = 0;

for ($i = 1; $i <= $chunks; $i++) {
    $countThisChunk = min($perFile, $amount - $totalCreated);
    if ($countThisChunk <= 0) break;

    $phones = generateUniquePhones($allPrefixes, $countThisChunk);
    $filename = "phones_" . time() . "_part{$i}.txt";
    $filePath = $outputDir . $filename;

    file_put_contents($filePath, implode(PHP_EOL, $phones));

    $fileLinks[] = $filename;
    $totalCreated += $countThisChunk;
}

// Hiển thị link tải
echo "<h3>Đã tạo thành công!</h3>";
foreach ($fileLinks as $file) {
    echo "<a href='downloads/{$file}' download>{$file}</a><br>";
}
?>