<?php
include 'db.php';

$message = "";
$repaired_count = 0;

if (isset($_POST['repair'])) {
    $dir = "../../uploads/";
    if (is_dir($dir)) {
        $files = scandir($dir);
        $apks = array_filter($files, function ($f) {
            return pathinfo($f, PATHINFO_EXTENSION) === 'apk';
        });

        foreach ($apks as $apk) {
            // Try to match the APK to a game
            // Heuristic 1: Exact match of filename (minus.apk) to game_name
            // Heuristic 2: Filename with dashes match to game_name
            $baseName = pathinfo($apk, PATHINFO_FILENAME);
            $searchName_dashes = str_replace('-', ' ', $baseName);
            $searchName_underscores = str_replace('_', ' ', $baseName);

            $stmt = $conn->prepare("SELECT game_id FROM games WHERE (game_name = ? OR game_name = ? OR game_name = ?) AND (download_link = '' OR download_link IS NULL)");
            $stmt->bind_param("sss", $baseName, $searchName_dashes, $searchName_underscores);
            $stmt->execute();
            $result = $stmt->get_result();

            if ($row = $result->fetch_assoc()) {
                $game_id = $row['game_id'];
                $update = $conn->prepare("UPDATE games SET download_link = ? WHERE game_id = ?");
                $update->bind_param("si", $apk, $game_id);
                if ($update->execute()) {
                    $repaired_count++;
                }
                $update->close();
            }
            $stmt->close();
        }
        $message = "<div class='alert alert-success'>Repair complete! Found $repaired_count games with missing links and updated them.</div>";
    } else {
        $message = "<div class='alert alert-danger'>Error: 'uploads/' directory not found at $dir</div>";
    }
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Repair Game Links</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
</head>

<body class="bg-light">
    <div class="container py-5">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card shadow">
                    <div class="card-header bg-primary text-white">
                        <h4 class="mb-0">Automatic Link Repair Tool</h4>
                    </div>
                    <div class="card-body">
                        <?php echo $message; ?>
                        <p>This tool scans the <code>/uploads/</code> folder for APK files and attempts to match them to
                            games in your database that are missing their download links.</p>
                        <p>It matches by comparing the filename (e.g., <code>Speedy-Cab.apk</code>) to the game name
                            (e.g., <code>Speedy Cab</code>).</p>

                        <form method="POST">
                            <button type="submit" name="repair" class="btn btn-primary btn-lg w-100">Scan & Repair
                                Links</button>
                        </form>

                        <div class="mt-4">
                            <a href="games.php" class="btn btn-secondary">Back to Manage Games</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>

</html>