<?php
/**
 * RUN THIS ONCE after uploading to your host, by visiting:
 *   https://gamesji.com/updates/install.php
 * Then DELETE this file (or rename it) for security.
 */
require_once __DIR__ . '/includes/functions.php';

header('Content-Type: text/plain; charset=utf-8');

echo "GamesJi Updates - Installer\n";
echo "============================\n\n";

$pdo = db(); // creates tables if missing
echo "[OK] Database ready at " . DB_PATH . "\n";

// Import games.csv (only inserts new slugs, safe to re-run)
$csv = __DIR__ . '/data/games.csv';
if (!file_exists($csv)) {
    die("[ERROR] data/games.csv not found.\n");
}

$fh = fopen($csv, 'r');
$header = fgetcsv($fh);
$inserted = 0;
$skipped = 0;

$check = $pdo->prepare("SELECT id FROM games WHERE slug = ?");
$insert = $pdo->prepare("INSERT INTO games (slug, name, category, description, play_url, gplay_url, appstore_url)
    VALUES (?, ?, ?, ?, ?, ?, ?)");

while (($row = fgetcsv($fh)) !== false) {
    $data = array_combine($header, $row);
    $check->execute([$data['slug']]);
    if ($check->fetch()) { $skipped++; continue; }
    $insert->execute([
        $data['slug'], $data['name'], $data['category'], $data['description'],
        $data['play_url'], $data['gplay_url'], $data['appstore_url']
    ]);
    $inserted++;
}
fclose($fh);

echo "[OK] Games imported: $inserted new, $skipped already existed.\n";
echo "[OK] Total games in database: " . count_games() . "\n\n";

echo "Next steps:\n";
echo "1. Set up a cron job to run cron/fetch_rss.php every 20-30 minutes (see README.md)\n";
echo "2. Set up a cron job to run cron/generate_sitemap.php once a day\n";
echo "3. Delete or rename install.php now that setup is complete.\n";
echo "4. Submit sitemap-index.xml to Google Search Console.\n";
