<?php
// import.php - Handles ZIP upload, extraction to assets/, and DB population
header('Content-Type: application/json; charset=utf-8');

// ================== SAME DB CREDENTIALS AS core.php ==================
$host     = 'localhost';
$db_user  = 'tasmoybb_grammie';
$db_pass  = '3XT3RN4l!337';
$db_name  = 'tasmoybb_grammie';
// =====================================================================

$conn = new mysqli($host, $db_user, $db_pass);
if ($conn->connect_error) {
    die(json_encode(['success' => false, 'message' => 'Database connection failed']));
}
$conn->select_db($db_name);

if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_FILES['data_zip'])) {
    echo json_encode(['success' => false, 'message' => 'No file uploaded']);
    exit;
}

$file = $_FILES['data_zip'];

if ($file['error'] !== 0 || $file['type'] !== 'application/zip') {
    echo json_encode(['success' => false, 'message' => 'Invalid ZIP file']);
    exit;
}

// Create assets folder
$assetsDir = 'assets/';
if (!is_dir($assetsDir)) mkdir($assetsDir, 0755, true);

// Recursive delete old assets (clean re-import)
function rrmdir($directory) {
    if (is_dir($directory)) {
        $objects = scandir($directory);
        foreach ($objects as $object) {
            if ($object !== '.' && $object !== '..') {
                $path = $directory . DIRECTORY_SEPARATOR . $object;
                is_dir($path) ? rrmdir($path) : unlink($path);
            }
        }
        rmdir($directory);
    }
}
if (is_dir($assetsDir)) rrmdir($assetsDir);
mkdir($assetsDir, 0755, true);

// Extract entire ZIP (preserves full folder structure + highest-quality media)
$zip = new ZipArchive();
if ($zip->open($file['tmp_name']) === TRUE) {
    $zip->extractTo($assetsDir);
    $zip->close();
} else {
    echo json_encode(['success' => false, 'message' => 'Failed to extract ZIP']);
    exit;
}

// Now parse connections folder (new 2025+ structure)
$connDir = $assetsDir . 'connections/followers_and_following/';
$followingFiles = is_dir($connDir) ? glob($connDir . '*following*.json') : [];
$followersFiles = is_dir($connDir) ? glob($connDir . '*followers*.json') : [];

// Clear old data for clean import
$conn->query("TRUNCATE TABLE accounts");

// Collect following
$followingData = [];
foreach ($followingFiles as $filePath) {
    $json = json_decode(file_get_contents($filePath), true);
    if (isset($json['relationships_following']) && is_array($json['relationships_following'])) {
        foreach ($json['relationships_following'] as $entry) {
            if (isset($entry['string_list_data'][0])) {
                $sld = $entry['string_list_data'][0];
                $username = $sld['value'] ?? '';
                if ($username) {
                    $followingData[$username] = [
                        'href' => $sld['href'] ?? '',
                        'ts'   => $sld['timestamp'] ?? 0
                    ];
                }
            }
        }
    }
}

// Collect followers (array root)
$followersData = [];
foreach ($followersFiles as $filePath) {
    $json = json_decode(file_get_contents($filePath), true);
    if (is_array($json)) {
        foreach ($json as $entry) {
            if (isset($entry['string_list_data'][0])) {
                $sld = $entry['string_list_data'][0];
                $username = $sld['value'] ?? '';
                if ($username) {
                    $followersData[$username] = [
                        'href' => $sld['href'] ?? '',
                        'ts'   => $sld['timestamp'] ?? 0
                    ];
                }
            }
        }
    }
}

// Merge and insert
$stmt = $conn->prepare("
    INSERT INTO accounts 
    (username, href, timestamp, is_following, is_followed_by) 
    VALUES (?, ?, ?, ?, ?)
");

foreach (array_unique(array_merge(array_keys($followingData), array_keys($followersData))) as $username) {
    $isFollowing = isset($followingData[$username]) ? 1 : 0;
    $isFollowedBy = isset($followersData[$username]) ? 1 : 0;
    $href = $followingData[$username]['href'] ?? ($followersData[$username]['href'] ?? '');
    $ts   = $followingData[$username]['ts'] ?? ($followersData[$username]['ts'] ?? 0);

    $stmt->bind_param('ssiii', $username, $href, $ts, $isFollowing, $isFollowedBy);
    $stmt->execute();
}

$stmt->close();
$conn->close();

echo json_encode([
    'success' => true,
    'message' => '✅ Full backup imported!<br>Media + JSONs in <b>assets/</b><br>Connections loaded into MySQL.<br>Refresh the page to see your non-followers.'
]);
?>