<?php
/**
 * Audit Logging Database Migration Runner
 * SSCI Office Platform
 * 
 * Executes the audit logging migration script to add audit trail support
 */

// Include config
require_once dirname(__DIR__) . '/config/bootstrap.php';

$db = $GLOBALS['db'];
$pdo = $db->connect();

echo "⏳ Running Audit Logging Migration...\n";
echo str_repeat("-", 60) . "\n";

$migration_sql = file_get_contents(__DIR__ . '/migrations/006_add_audit_logging.sql');

// Split by statements (handle multiple statements)
$statements = array_filter(array_map('trim', preg_split('/;[\n\r]+/', $migration_sql)));

$successCount = 0;
$failureCount = 0;
$errors = [];

foreach ($statements as $sql) {
    if (empty($sql)) continue;
    
    try {
        $pdo->exec($sql);
        $successCount++;
        echo "✓ " . substr($sql, 0, 80) . (strlen($sql) > 80 ? "..." : "") . "\n";
    } catch (Exception $e) {
        $failureCount++;
        $errors[] = $e->getMessage();
        echo "✗ " . substr($sql, 0, 80) . (strlen($sql) > 80 ? "..." : "") . "\n";
        echo "  Error: " . $e->getMessage() . "\n";
    }
}

echo str_repeat("-", 60) . "\n";
echo "\nMigration Complete!\n";
echo "✓ Successful: $successCount\n";
echo "✗ Failed: $failureCount\n";

if ($failureCount > 0) {
    echo "\nErrors:\n";
    foreach ($errors as $error) {
        echo "- $error\n";
    }
}

// Verify tables exist
echo "\n" . str_repeat("-", 60) . "\n";
echo "Verification:\n";

try {
    $result = $pdo->query("SELECT COUNT(*) FROM audit_logs");
    $count = $result->fetchColumn();
    echo "✓ audit_logs table exists and contains $count records\n";
} catch (Exception $e) {
    echo "✗ audit_logs table: " . $e->getMessage() . "\n";
}

try {
    $result = $pdo->query("SELECT COUNT(*) FROM audit_log_types");
    $count = $result->fetchColumn();
    echo "✓ audit_log_types table exists with $count action types\n";
} catch (Exception $e) {
    echo "✗ audit_log_types table: " . $e->getMessage() . "\n";
}

// Check if settings columns exist
try {
    $result = $pdo->query("SHOW COLUMNS FROM settings LIKE 'enable_audit_logging'");
    if ($result->rowCount() > 0) {
        echo "✓ Settings audit columns added\n";
    }
} catch (Exception $e) {
    echo "✗ Settings columns: " . $e->getMessage() . "\n";
}

echo str_repeat("-", 60) . "\n";
echo "\n✅ Audit Logging Migration Complete!\n\n";
echo "Next Steps:\n";
echo "1. Configure audit settings in admin panel\n";
echo "2. Start using AuditLog class: AuditLog::logCreate(...)\n";
echo "3. View audit logs: AuditLog->getAuditLogs(...)\n";
echo "4. Export audit trail: AuditLog->exportAuditLogs(...)\n";
echo "\n";
?>
