<?php
// migrate_events.php
// Place this in /admin/ and run it once to move old files and fix DB paths.

include 'db.php';

$old_base = $_SERVER['DOCUMENT_ROOT'] . "/KCGA-GameHUB/Profile-Me-Page/";
$new_base = $_SERVER['DOCUMENT_ROOT'] . "/admin/uploads/gaming_event/";

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

$res = $conn->query("SELECT event_id, event_image FROM events");
while ($row = $res->fetch_assoc()) {
    $id = $row['event_id'];
    $old_path = $row['event_image'];

    if (empty($old_path))
        continue;

    // Check if path is absolute with /gamehub/
    if (strpos($old_path, '/gamehub/') === 0) {
        $clean_path = substr($old_path, 9); // Remove /gamehub/

        // Try to move physical file if it exists in the old location
        $filename = basename($old_path);
        if (file_exists($old_base . $filename)) {
            if (rename($old_base . $filename, $new_base . $filename)) {
                $new_db_path = "admin/uploads/gaming_event/" . $filename;
                $stmt = $conn->prepare("UPDATE events SET event_image = ? WHERE event_id = ?");
                $stmt->bind_param("si", $new_db_path, $id);
                $stmt->execute();
                echo "Migrated Event $id: $filename\n";
            }
        } else {
            // Just update DB path to be relative if it was absolute
            $stmt = $conn->prepare("UPDATE events SET event_image = ? WHERE event_id = ?");
            $stmt->bind_param("si", $clean_path, $id);
            $stmt->execute();
            echo "Cleaned DB Path for Event $id\n";
        }
    }
}

echo "Migration finished.";
?>