<?php
/**
 * Update System Test Script
 * 
 * This script tests the update system functionality without making actual changes.
 * Use this to verify that the update system is working correctly.
 */

// Include required files
require_once('update.php');

// Test configuration
$test_config = [
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => '',
    'database' => 'test_ncs_update'
];

// Override $_POST for testing
$_POST = $test_config;

echo "NCS Billing System Update Test\n";
echo "==============================\n\n";

// Test 1: Check if update system can be instantiated
echo "Test 1: Instantiating UpdateSystem class...\n";
try {
    $updateSystem = new UpdateSystem();
    echo "✓ UpdateSystem class instantiated successfully\n";
    echo "  Current version: " . $updateSystem->getCurrentVersion() . "\n";
    echo "  Target version: " . $updateSystem->getTargetVersion() . "\n";
    echo "  Update needed: " . ($updateSystem->checkUpdateNeeded() ? 'Yes' : 'No') . "\n\n";
} catch (Exception $e) {
    echo "✗ Failed to instantiate UpdateSystem: " . $e->getMessage() . "\n\n";
}

// Test 2: Check database connection
echo "Test 2: Testing database connection...\n";
try {
    $connection = new mysqli($test_config['hostname'], $test_config['username'], $test_config['password']);
    if ($connection->connect_error) {
        echo "✗ Database connection failed: " . $connection->connect_error . "\n";
        echo "  Please ensure MySQL is running and credentials are correct\n\n";
    } else {
        echo "✓ Database connection successful\n";
        $connection->close();
    }
} catch (Exception $e) {
    echo "✗ Database connection error: " . $e->getMessage() . "\n\n";
}

// Test 3: Check if test database exists
echo "Test 3: Checking test database...\n";
try {
    $connection = new mysqli($test_config['hostname'], $test_config['username'], $test_config['password']);
    $result = $connection->query("SHOW DATABASES LIKE '" . $test_config['database'] . "'");
    if ($result->num_rows > 0) {
        echo "✓ Test database exists\n";
        
        // Check if it has the required tables
        $connection->select_db($test_config['database']);
        $tables_result = $connection->query("SHOW TABLES");
        $tables = [];
        while ($row = $tables_result->fetch_array()) {
            $tables[] = $row[0];
        }
        echo "  Tables found: " . count($tables) . "\n";
        
        // Check for sitesettings table
        if (in_array('db_sitesettings', $tables)) {
            $version_result = $connection->query("SELECT version FROM db_sitesettings WHERE id = 1");
            if ($version_result && $version_result->num_rows > 0) {
                $version = $version_result->fetch_assoc()['version'];
                echo "  Current version in database: " . $version . "\n";
            }
        }
        
    } else {
        echo "✗ Test database does not exist\n";
        echo "  Please create the test database or update the configuration\n";
    }
    $connection->close();
} catch (Exception $e) {
    echo "✗ Database check error: " . $e->getMessage() . "\n";
}

echo "\n";

// Test 4: Check billing.sql file
echo "Test 4: Checking billing.sql file...\n";
$billing_sql = '../install/billing.sql';
if (file_exists($billing_sql)) {
    echo "✓ billing.sql file found\n";
    
    $file_size = filesize($billing_sql);
    echo "  File size: " . number_format($file_size) . " bytes\n";
    
    // Check if file is readable
    if (is_readable($billing_sql)) {
        echo "  ✓ File is readable\n";
        
        // Check for basic SQL content
        $content = file_get_contents($billing_sql);
        if (strpos($content, 'CREATE TABLE') !== false) {
            echo "  ✓ Contains CREATE TABLE statements\n";
        } else {
            echo "  ✗ No CREATE TABLE statements found\n";
        }
        
        if (strpos($content, 'INSERT INTO') !== false) {
            echo "  ✓ Contains INSERT statements\n";
        } else {
            echo "  ✗ No INSERT statements found\n";
        }
    } else {
        echo "  ✗ File is not readable\n";
    }
} else {
    echo "✗ billing.sql file not found: " . $billing_sql . "\n";
}

echo "\n";

// Test 5: Check backup directory
echo "Test 5: Checking backup directory...\n";
$backup_dir = '../../backups/';
if (is_dir($backup_dir)) {
    echo "✓ Backup directory exists\n";
    if (is_writable($backup_dir)) {
        echo "  ✓ Backup directory is writable\n";
    } else {
        echo "  ✗ Backup directory is not writable\n";
    }
} else {
    echo "✗ Backup directory does not exist: " . $backup_dir . "\n";
    echo "  Creating backup directory...\n";
    if (mkdir($backup_dir, 0755, true)) {
        echo "  ✓ Backup directory created successfully\n";
    } else {
        echo "  ✗ Failed to create backup directory\n";
    }
}

echo "\n";

// Test 6: Check file permissions
echo "Test 6: Checking file permissions...\n";
$critical_files = [
    '../../application/config/database.php',
    '../../application/config/config.php',
    '../../index.php'
];

foreach ($critical_files as $file) {
    if (file_exists($file)) {
        if (is_readable($file)) {
            echo "✓ " . $file . " is readable\n";
        } else {
            echo "✗ " . $file . " is not readable\n";
        }
        
        if (is_writable($file)) {
            echo "  ✓ " . $file . " is writable\n";
        } else {
            echo "  ✗ " . $file . " is not writable\n";
        }
    } else {
        echo "✗ " . $file . " does not exist\n";
    }
}

echo "\n";

// Test 7: Check update system files
echo "Test 7: Checking update system files...\n";
$update_files = [
    'update.php',
    'taskCoreClass.php',
    'includes/databaseLibrary.php',
    'index.php'
];

foreach ($update_files as $file) {
    if (file_exists($file)) {
        echo "✓ " . $file . " exists\n";
    } else {
        echo "✗ " . $file . " missing\n";
    }
}

echo "\n";

// Summary
echo "Test Summary\n";
echo "============\n";
echo "This test script has checked the basic functionality of the update system.\n";
echo "If all tests passed, the update system should work correctly.\n";
echo "If any tests failed, please address the issues before running updates.\n\n";

echo "To run a real update test:\n";
echo "1. Ensure you have a test database with sample data\n";
echo "2. Run the update interface: http://yourdomain.com/setup/update/\n";
echo "3. Enter your database credentials\n";
echo "4. Follow the update process\n\n";

echo "For production updates:\n";
echo "1. Always backup your data first\n";
echo "2. Test updates in a staging environment\n";
echo "3. Monitor the update process carefully\n";
echo "4. Have a rollback plan ready\n";
?>
