<?php

/* 🔥 DATABASE CONFIG */
$pdo = new PDO("mysql:host=localhost;dbname=wjqxfnzn_swiftbothai;charset=utf8mb4", "wjqxfnzn_swiftbothai", "wjqxfnzn_swiftbothai");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

if (isset($_POST['upload'])) {

    if (!isset($_FILES['zip'])) {
        die("No file");
    }

    $zipFile = $_FILES['zip'];

    if ($zipFile['error'] != 0) {
        die("Upload error");
    }

    $zipPath = __DIR__ . "/temp.zip";
    move_uploaded_file($zipFile['tmp_name'], $zipPath);

    $zip = new ZipArchive;

    if ($zip->open($zipPath) === TRUE) {

        /* ✅ IMPORTANT FIX */
        $extractPath = __DIR__ . "/unzipped/";

        if (!is_dir($extractPath)) {
            mkdir($extractPath, 0777, true);
        }

        $zip->extractTo($extractPath);
        $zip->close();

        $sessionFolder = __DIR__ . "/sessions/";

        if (!is_dir($sessionFolder)) {
            mkdir($sessionFolder, 0777, true);
        }

        foreach (scandir($extractPath) as $file) {

            if ($file == '.' || $file == '..') continue;

            $fullPath = $extractPath . $file;

            if (is_file($fullPath)) {

                $newPath = $sessionFolder . $file;

                /* ✅ SAFER MOVE */
                if (copy($fullPath, $newPath)) {

                    unlink($fullPath);

                    /* ✅ SQL INSERT */
                    $stmt = $pdo->prepare("
                        INSERT INTO session_stock
                        (server_id, file_path, is_used, used_at, created_at, used_by)
                        VALUES
                        (1, ?, 0, NULL, NOW(), NULL)
                    ");

                    $stmt->execute(["sessions/" . $file]);
                }
                else {
                    echo "❌ Move failed: " . $file . "<br>";
                }
            }
        }

        unlink($zipPath);

        echo "<h2>✅ Sessions Upload Ho Gaye 😎🔥</h2>";

    } else {
        die("Zip open failed");
    }
}

?>

<!DOCTYPE html>
<html>
<head>
    <title>Uploader 😎🔥</title>
</head>
<body>

<h2>📦 Telegram Session Upload</h2>

<form method="post" enctype="multipart/form-data">
    <input type="file" name="zip" required>
    <button type="submit" name="upload">Upload 🚀</button>
</form>

</body>
</html>
