<?php
/**
 * TellerPro Database Reset Script
 * 
 * This script will:
 * 1. Truncate all database tables (resets auto-increment IDs to 1)
 * 2. Clear session files
 * 3. Clear cache files
 * 4. Clear rate limit files
 * 
 * WARNING: This will delete ALL data. Use with caution!
 * 
 * Usage: php reset_database.php
 */

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

echo "========================================\n";
echo "TELLERPRO DATABASE RESET SCRIPT\n";
echo "========================================\n\n";

// Safety confirmation
echo "⚠️  WARNING: This will delete ALL data in the database!\n";
echo "This action cannot be undone.\n\n";

if (php_sapi_name() !== 'cli') {
    die("This script must be run from command line.\n");
}

echo "Type 'YES' to confirm: ";
$handle = fopen("php://stdin", "r");
$line = fgets($handle);
fclose($handle);

if (trim($line) !== 'YES') {
    echo "\n❌ Reset cancelled.\n";
    exit(1);
}

echo "\n🔄 Starting database reset...\n\n";

try {
    $db = db();
    
    // Disable foreign key checks
    echo "Disabling foreign key checks...\n";
    $db->exec("SET FOREIGN_KEY_CHECKS = 0");
    
    // List of all tables to truncate (in dependency order)
    $tables = [
        // Child tables first
        'stock_transfer_items',
        'sale_items',
        'purchase_items',
        'stock_movements',
        'stock_adjustments',
        'stock_transfers',
        'payments',
        'notifications',
        'audit_logs',
        'login_attempts',
        'supplier_ledger',
        'customer_ledger',
        
        // Parent tables
        'stock',
        'batches',
        'sales',
        'purchases',
        'customers',
        'suppliers',
        'products',
        'locations',
        'categories',
        'brands',
        'units',
        'tax_groups',
        'users',
        'subscriptions',
        'tenants',
        'settings',
        'plans',
        'superadmins'
    ];
    
    // Truncate each table
    foreach ($tables as $table) {
        try {
            $db->exec("TRUNCATE TABLE `$table`");
            echo "✓ Truncated: $table\n";
        } catch (PDOException $e) {
            echo "⚠ Skipped: $table (may not exist)\n";
        }
    }
    
    // Re-enable foreign key checks
    echo "\nRe-enabling foreign key checks...\n";
    $db->exec("SET FOREIGN_KEY_CHECKS = 1");
    
    echo "\n✅ Database reset complete. All auto-increment IDs reset to 1.\n";
    
} catch (PDOException $e) {
    echo "\n❌ Database error: " . $e->getMessage() . "\n";
    exit(1);
}

// Clear session files
echo "\n🗑️  Clearing session files...\n";
$sessionPaths = [
    SESSION_PATH,
    __DIR__ . '/sessions/tenant',
    __DIR__ . '/sessions/superadmin'
];

foreach ($sessionPaths as $path) {
    if (is_dir($path)) {
        $files = glob($path . '/sess_*');
        foreach ($files as $file) {
            if (is_file($file)) {
                unlink($file);
            }
        }
        echo "✓ Cleared sessions in: $path\n";
    }
}

// Clear cache files
echo "\n🗑️  Clearing cache files...\n";
$cachePaths = [
    CACHE_PATH,
    RATELIMIT_PATH
];

foreach ($cachePaths as $path) {
    if (is_dir($path)) {
        $files = glob($path . '/*');
        foreach ($files as $file) {
            if (is_file($file)) {
                unlink($file);
            }
        }
        echo "✓ Cleared cache in: $path\n";
    }
}

// Clear log files (optional)
echo "\n🗑️  Clearing log files...\n";
$logPath = LOGS_PATH;
if (is_dir($logPath)) {
    $files = glob($logPath . '/*.log');
    foreach ($files as $file) {
        if (is_file($file)) {
            unlink($file);
        }
    }
    echo "✓ Cleared logs in: $logPath\n";
}

echo "\n========================================\n";
echo "✅ RESET COMPLETE\n";
echo "========================================\n";
echo "\nDatabase and cache have been reset.\n";
echo "All auto-increment IDs are now set to 1.\n";
echo "You can now start fresh.\n\n";
