#!/usr/bin/env php
<?php
/**
 * Restore Database from Backup
 * Usage: php restore-database.php backup_file.sql
 */

require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../config/database.php';

$backupFile = $argv[1] ?? null;

if (!$backupFile) {
    echo "Usage: php restore-database.php <backup_file.sql>\n";
    echo "Available backups:\n";
    $backups = glob(__DIR__ . '/../backups/*.sql');
    foreach ($backups as $backup) {
        echo "  - " . basename($backup) . " (" . date('Y-m-d H:i:s', filemtime($backup)) . ")\n";
    }
    exit(1);
}

$backupPath = __DIR__ . '/../backups/' . basename($backupFile);

if (!file_exists($backupPath)) {
    echo "Error: Backup file not found: $backupFile\n";
    exit(1);
}

echo "Restoring database from: " . basename($backupFile) . "\n";
echo "WARNING: This will overwrite all current data!\n";
echo "Type 'RESTORE' to continue: ";
$handle = fopen("php://stdin", "r");
$confirm = trim(fgets($handle));

if ($confirm !== 'RESTORE') {
    echo "Restore cancelled.\n";
    exit(0);
}

$pdo = getDB();
$sql = file_get_contents($backupPath);

// Split SQL into individual queries
$queries = [];
$currentQuery = '';
$lines = explode("\n", $sql);

foreach ($lines as $line) {
    $line = trim($line);
    if (empty($line) || strpos($line, '--') === 0) {
        continue;
    }
    $currentQuery .= $line . "\n";
    if (substr(rtrim($line), -1) == ';') {
        $queries[] = trim($currentQuery);
        $currentQuery = '';
    }
}

echo "Executing " . count($queries) . " queries...\n";

try {
    $pdo->exec("SET FOREIGN_KEY_CHECKS=0");
    
    foreach ($queries as $query) {
        $pdo->exec($query);
    }
    
    $pdo->exec("SET FOREIGN_KEY_CHECKS=1");
    
    echo "Database restored successfully!\n";
} catch (PDOException $e) {
    echo "Error: " . $e->getMessage() . "\n";
    exit(1);
}