<?php
include 'conn.php';
// print_r($_FILES);
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['file'])) {
    if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
        die("No file uploaded or file upload error.");
    }

    $file = $_FILES['file']['tmp_name'];
    if (!file_exists($file)) {
        die("Uploaded file is missing or invalid.");
    }

    $numbers = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    $numbers = array_map(fn($n) => preg_replace('/\D+/', '', trim($n)), $numbers);
    $numbers = array_filter($numbers); // remove blanks
    $numbers = array_unique($numbers);
    $totalUploaded = count($numbers);

    if ($totalUploaded === 0) {
        die("No valid phone numbers in uploaded file.");
    }

    // ✅ Create a temporary table for staging
    $conn->set_charset("utf8mb4"); // ensure connection uses correct charset
    $conn->query("
        CREATE TEMPORARY TABLE temp_numbers (
            phone_number VARCHAR(20) 
            CHARACTER SET utf8mb4 
            COLLATE utf8mb4_general_ci 
            PRIMARY KEY
        )
    ");


    // ✅ Bulk insert into temp table
    $values = implode("'),('", $numbers);
    $SQL = "";
    foreach ($numbers as $num) {
        $SQL = "INSERT INTO temp_numbers (phone_number) VALUES ('$num');";
        if (!$conn->query($SQL)) {
            echo "<pre>❌ SQL Error: " . $conn->error . "</pre>";
            echo "<pre>📝 Query: " . htmlspecialchars($SQL) . "</pre>";
            exit;
        }
    }
    // $conn->query($SQL);

    // ✅ Fetch numbers not already present
    $sql = "
        SELECT t.phone_number 
        FROM temp_numbers t
        LEFT JOIN phone_numbers p ON t.phone_number = p.phone_number
        WHERE p.phone_number IS NULL
    ";
    $newResult = $conn->query($sql);

    $unique_numbers = [];
    while ($row = $newResult->fetch_assoc()) {
        $unique_numbers[] = $row['phone_number'];
    }

    $newAdded = count($unique_numbers);

    // ✅ Insert unique numbers into main table in ONE query
    if ($newAdded > 0) {
        $values = implode("'),('", $unique_numbers);
        $conn->query("INSERT IGNORE INTO phone_numbers (phone_number) VALUES ('$values')");
    }

    $duplicates = $totalUploaded - $newAdded;

    // ✅ Logging
    $ip = $_SERVER['REMOTE_ADDR'];
    $logDate = date("Y-m-d H:i:s");

    if (!is_dir(__DIR__ . "/logs")) mkdir(__DIR__ . "/logs", 0777, true);

    $logMessage = "[$logDate] IP: $ip | Uploaded: $totalUploaded | New: $newAdded | Duplicates: $duplicates\n";
    file_put_contents(__DIR__ . "/logs/upload_log_" . date("Y-m") . ".log", $logMessage, FILE_APPEND);

    // ✅ Output Result
    if ($newAdded > 0) {
        $downloadFile = tempnam(sys_get_temp_dir(), 'unique_') . ".txt";
        file_put_contents($downloadFile, implode("\n", $unique_numbers));

        header('Content-Type: text/plain');
        header('Content-Disposition: attachment; filename="unique_numbers.txt"');
        readfile($downloadFile);
        unlink($downloadFile);
        exit;
    } else {
        echo "<p style='color:red;'>No new unique numbers found.</p>";
    }
}
?>
<!DOCTYPE html>
<html>

<head>
    <title>Upload Phone Numbers</title>
    <style>
    body {
        font-family: Arial, sans-serif;
        margin: 40px;
        background: #f9f9f9;
    }

    .container {
        border: 1px solid #ccc;
        background: #fff;
        padding: 25px;
        width: 400px;
        margin: auto;
        border-radius: 8px;
        box-shadow: 0 0 8px rgba(0, 0, 0, 0.1);
    }

    button {
        background: #007bff;
        color: #fff;
        border: none;
        padding: 10px 15px;
        border-radius: 5px;
        cursor: pointer;
    }

    button:hover {
        background: #0056b3;
    }

    .link {
        margin-top: 10px;
        display: block;
        text-align: center;
    }
    </style>
</head>

<body>
    <div class="container">
        <h2>📁 Upload Phone Numbers</h2>
        <form method="POST" enctype="multipart/form-data">
            <input type="file" name="file" accept=".txt" required><br><br>
            <button type="submit">Upload & Check</button>
        </form>
        <a href="index.php" class="link">📊 View Upload Logs</a>
    </div>
</body>

</html>