<?php
/**
 * TellerPro Database Reset - Browser Version
 * 
 * WARNING: This will delete ALL data in the database!
 * Requires superadmin authentication.
 * 
 * Usage: Access via browser at /reset_database_browser.php
 */

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

// Start session
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Handle POST request for reset
$message = '';
$messageType = '';
$resetDetails = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['confirm'])) {
        if ($_POST['confirm'] !== 'RESET_DATABASE') {
            $message = 'Confirmation text did not match. Database reset cancelled.';
            $messageType = 'error';
        } else {
            try {
                $db = db();
            
            // Disable foreign key checks
            $db->exec("SET FOREIGN_KEY_CHECKS = 0");
            
            // List of all tables to truncate (in dependency order)
            $tables = [
                'stock_transfer_items',
                'sale_items',
                'purchase_items',
                'stock_movements',
                'stock_adjustments',
                'stock_transfers',
                'payments',
                'notifications',
                'audit_logs',
                'login_attempts',
                'supplier_ledger',
                'customer_ledger',
                '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`");
                    $resetDetails[] = "✓ Truncated: $table";
                } catch (PDOException $e) {
                    $resetDetails[] = "⚠ Skipped: $table (may not exist)";
                }
            }
            
            // Re-enable foreign key checks
            $db->exec("SET FOREIGN_KEY_CHECKS = 1");
            
            // Clear session files
            $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);
                        }
                    }
                    $resetDetails[] = "✓ Cleared sessions in: $path";
                }
            }
            
            // Clear cache files
            $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);
                        }
                    }
                    $resetDetails[] = "✓ Cleared cache in: $path";
                }
            }
            
            // Clear log files
            $logPath = LOGS_PATH;
            if (is_dir($logPath)) {
                $files = glob($logPath . '/*.log');
                foreach ($files as $file) {
                    if (is_file($file)) {
                        unlink($file);
                    }
                }
                $resetDetails[] = "✓ Cleared logs in: $logPath";
            }
            
            $message = 'Database and cache have been successfully reset. All auto-increment IDs are now set to 1.';
            $messageType = 'success';
            
        } catch (PDOException $e) {
            $message = 'Database error: ' . $e->getMessage();
            $messageType = 'error';
        }
    }
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Reset Database - TellerPro</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        
        .container {
            background: white;
            border-radius: 12px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
            max-width: 600px;
            width: 100%;
            padding: 40px;
        }
        
        .header {
            text-align: center;
            margin-bottom: 30px;
        }
        
        .header h1 {
            color: #333;
            font-size: 28px;
            margin-bottom: 10px;
        }
        
        .header .subtitle {
            color: #666;
            font-size: 14px;
        }
        
        .warning-box {
            background: #fff3cd;
            border: 1px solid #ffc107;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 30px;
        }
        
        .warning-box h3 {
            color: #856404;
            font-size: 16px;
            margin-bottom: 10px;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .warning-box p {
            color: #856404;
            font-size: 14px;
            line-height: 1.6;
        }
        
        .warning-box ul {
            color: #856404;
            font-size: 14px;
            margin-left: 20px;
            margin-top: 10px;
        }
        
        .warning-box li {
            margin: 5px 0;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-group label {
            display: block;
            color: #333;
            font-weight: 600;
            margin-bottom: 8px;
            font-size: 14px;
        }
        
        .form-group input[type="text"] {
            width: 100%;
            padding: 12px 16px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            font-size: 14px;
            transition: border-color 0.3s;
        }
        
        .form-group input[type="text"]:focus {
            outline: none;
            border-color: #667eea;
        }
        
        .form-group .hint {
            color: #666;
            font-size: 12px;
            margin-top: 6px;
        }
        
        .btn {
            width: 100%;
            padding: 14px 24px;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .btn-danger {
            background: #dc3545;
            color: white;
        }
        
        .btn-danger:hover {
            background: #c82333;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(220, 53, 69, 0.4);
        }
        
        .btn-secondary {
            background: #6c757d;
            color: white;
            margin-top: 10px;
        }
        
        .btn-secondary:hover {
            background: #5a6268;
        }
        
        .alert {
            padding: 16px 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            font-size: 14px;
        }
        
        .alert-success {
            background: #d4edda;
            border: 1px solid #28a745;
            color: #155724;
        }
        
        .alert-error {
            background: #f8d7da;
            border: 1px solid #dc3545;
            color: #721c24;
        }
        
        .reset-details {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 20px;
            margin-top: 20px;
        }
        
        .reset-details h4 {
            color: #333;
            font-size: 16px;
            margin-bottom: 15px;
        }
        
        .reset-details ul {
            list-style: none;
            max-height: 300px;
            overflow-y: auto;
        }
        
        .reset-details li {
            color: #555;
            font-size: 13px;
            padding: 4px 0;
            font-family: 'Courier New', monospace;
        }
        
        .back-link {
            text-align: center;
            margin-top: 20px;
        }
        
        .back-link a {
            color: #667eea;
            text-decoration: none;
            font-size: 14px;
        }
        
        .back-link a:hover {
            text-decoration: underline;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🗑️ Reset Database</h1>
            <p class="subtitle">TellerPro Database Management</p>
        </div>
        
        <?php if ($message): ?>
            <div class="alert alert-<?php echo $messageType; ?>">
                <?php echo htmlspecialchars($message); ?>
            </div>
        <?php endif; ?>
        
        <?php if (!$resetDetails): ?>
            <?php if (!isset($_SESSION['reset_authenticated']) || !$_SESSION['reset_authenticated']): ?>
                <div class="warning-box">
                    <h3>🔐 Authentication Required</h3>
                    <p>Enter the admin password to access the database reset tool.</p>
                    <p style="margin-top: 10px; font-size: 12px;">Default password: <code>admin123</code> (change this in the script)</p>
                </div>
                
                <form method="POST">
                    <div class="form-group">
                        <label for="password">Admin Password:</label>
                        <input 
                            type="password" 
                            id="password" 
                            name="password" 
                            required 
                            autofocus
                        >
                    </div>
                    
                    <button type="submit" class="btn btn-danger">
                        🔓 Authenticate
                    </button>
                </form>
            <?php else: ?>
                <div class="warning-box">
                    <h3>⚠️ DANGER: Irreversible Action</h3>
                    <p>This will permanently delete ALL data in the database:</p>
                    <ul>
                        <li>All tenants, users, and subscriptions</li>
                        <li>All products, sales, purchases, and stock</li>
                        <li>All customers, suppliers, and transactions</li>
                        <li>All settings and notifications</li>
                        <li>All session and cache files</li>
                    </ul>
                    <p style="margin-top: 15px;"><strong>This action cannot be undone!</strong></p>
                </div>
                
                <form method="POST">
                    <div class="form-group">
                        <label for="confirm">Type <code>RESET_DATABASE</code> to confirm:</label>
                        <input 
                            type="text" 
                            id="confirm" 
                            name="confirm" 
                            required 
                            autocomplete="off"
                            placeholder="RESET_DATABASE"
                        >
                        <p class="hint">This confirms you understand the consequences</p>
                    </div>
                    
                    <button type="submit" class="btn btn-danger">
                        🗑️ Reset All Data
                    </button>
                </form>
        <?php else: ?>
            <div class="reset-details">
                <h4>✅ Reset Completed Successfully</h4>
                <ul>
                    <?php foreach ($resetDetails as $detail): ?>
                        <li><?php echo htmlspecialchars($detail); ?></li>
                    <?php endforeach; ?>
                </ul>
            </div>
            
            <div class="back-link">
                <a href="<?php echo $_SERVER['PHP_SELF']; ?>">← Reset Again</a>
            </div>
        <?php endif; ?>
    </div>
</body>
</html>
