<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\BackupDownloadController;
use App\Helpers\BackupEncryption; // ✅ IMPORTANT: Helper class import
use Illuminate\Support\Facades\Artisan;
use Carbon\Carbon;
use Illuminate\Http\Request; // ✅ IMPORTANT: Request class import

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
*/

Route::get('/', function () {
    return view('welcome');
});

// ============================================
// ✅ DOWNLOAD ROUTES - SIRF EK BAAR DEFINE KAREIN
// ============================================

// ✅ YEH SAHI HAI - .sql aur .enc dono support karega
Route::get('/storage/backup/{filename}', [BackupDownloadController::class, 'showDownloadForm'])
     ->where('filename', '.*\.(sql|enc)$');

Route::post('/storage/backup/{filename}', [BackupDownloadController::class, 'download'])
     ->where('filename', '.*\.(sql|enc)$')
     ->name('backup.download');

// ✅ FORCE DOWNLOAD ROUTE - same pattern
Route::get('/backup/download/{filename}', [BackupDownloadController::class, 'showDownloadForm'])
     ->where('filename', '.*\.(sql|enc)$');

// ============================================
// ✅ ENCRYPTION ROUTES
// ============================================

// ✅ CREATE ENCRYPTED BACKUP
Route::get('/backup/create-encrypted', function() {
    try {
        $backupDir = public_path('storage/backup');
        if (!is_dir($backupDir)) {
            mkdir($backupDir, 0755, true);
        }

        $encryption = new BackupEncryption();
        $timestamp = now()->format('Y-m-d_H-i-s');
        $sqlFile = "caxis_backup_{$timestamp}.sql";
        $sqlPath = $backupDir . '/' . $sqlFile;

        // Create SQL dump
        $command = sprintf(
            'mysqldump --user=%s --password=%s --host=%s %s > %s 2>&1',
            escapeshellarg(env('DB_USERNAME')),
            escapeshellarg(env('DB_PASSWORD')),
            escapeshellarg(env('DB_HOST')),
            escapeshellarg(env('DB_DATABASE')),
            $sqlPath
        );

        exec($command, $output, $returnCode);

        if ($returnCode !== 0) {
            throw new \Exception("mysqldump failed: " . implode("\n", $output));
        }

        // Generate random password
        $password = bin2hex(random_bytes(16));

        // Encrypt the file
        $encryptedPath = $encryption->encryptFile($sqlPath, $password);

        // Delete original SQL file
        unlink($sqlPath);

        return "
        <div style='font-family: Inter, sans-serif; max-width: 600px; margin: 50px auto; padding: 30px; background: white; border-radius: 16px; box-shadow: 0 10px 40px rgba(0,0,0,0.1);'>
            <h2 style='color: #10b981; margin-bottom: 20px;'>✅ Encrypted Backup Created</h2>
            <div style='background: #f8fafc; padding: 20px; border-radius: 12px; margin-bottom: 20px;'>
                <p style='margin-bottom: 10px;'><strong>Filename:</strong> " . basename($encryptedPath) . "</p>
                <p style='margin-bottom: 10px;'><strong>Password:</strong> <code style='background: #1e293b; color: #e2e8f0; padding: 5px 10px; border-radius: 6px;'>" . $password . "</code></p>
                <p style='color: #64748b; font-size: 14px; margin-top: 15px;'>⚠️ Save this password! You'll need it to download the file.</p>
            </div>
            <a href='/cleanup-test' style='display: inline-block; padding: 10px 20px; background: #4361ee; color: white; text-decoration: none; border-radius: 8px;'>Back to Dashboard</a>
        </div>";

    } catch (\Exception $e) {
        return "<div style='color: #ef4444; padding: 20px;'>Error: " . 'Something went wrong. Please try again later.' . "</div>";
    }
});

// ✅ DECRYPT A FILE
Route::get('/backup/decrypt-file', function() {
    $backupDir = public_path('storage/backup');
    $files = glob($backupDir . '/*.enc');

    $options = '';
    foreach ($files as $file) {
        $filename = basename($file);
        $options .= "<option value='" . htmlspecialchars($filename) . "'>" . htmlspecialchars($filename) . "</option>";
    }

    return '
    <!DOCTYPE html>
    <html>
    <head>
        <title>Decrypt Backup File</title>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
        <style>
            body { font-family: Inter, sans-serif; background: #f8fafc; padding: 40px; }
            .container { max-width: 600px; margin: 0 auto; background: white; border-radius: 16px; padding: 30px; box-shadow: 0 10px 40px rgba(0,0,0,0.1); }
            h2 { color: #0f172a; margin-bottom: 20px; }
            .form-group { margin-bottom: 20px; }
            label { display: block; margin-bottom: 8px; font-weight: 600; color: #334155; }
            select, input { width: 100%; padding: 12px; border: 2px solid #e2e8f0; border-radius: 8px; font-size: 14px; }
            .btn { background: #4361ee; color: white; padding: 12px 24px; border: none; border-radius: 8px; cursor: pointer; font-size: 16px; }
            .btn:hover { background: #3730a3; }
            .note { background: #fef3c7; padding: 15px; border-radius: 8px; margin-top: 20px; color: #92400e; }
        </style>
    </head>
    <body>
        <div class="container">
            <h2><i class="fas fa-unlock-alt"></i> Decrypt Backup File</h2>
            <form method="POST" action="/backup/decrypt-process">
                ' . csrf_field() . '
                <div class="form-group">
                    <label>Select Encrypted File:</label>
                    <select name="filename" required>
                        ' . $options . '
                    </select>
                </div>
                <div class="form-group">
                    <label>Password:</label>
                    <input type="password" name="password" required placeholder="Enter encryption password">
                </div>
                <button type="submit" class="btn"><i class="fas fa-lock-open"></i> Decrypt File</button>
            </form>
            <div class="note">
                <i class="fas fa-info-circle"></i> Decrypted file (.sql) same folder mein save hogi.
            </div>
        </div>
    </body>
    </html>';
});

// ✅ PROCESS DECRYPT
Route::post('/backup/decrypt-process', function(Request $request) {
    try {
        $filename = $request->input('filename');
        $password = $request->input('password');

        if (!$filename || !$password) {
            throw new \Exception('Filename and password required');
        }

        $backupDir = public_path('storage/backup');
        $encryptedPath = $backupDir . '/' . $filename;

        if (!file_exists($encryptedPath)) {
            throw new \Exception('File not found: ' . $filename);
        }

        $encryption = new BackupEncryption();
        $outputPath = $backupDir . '/' . str_replace('.enc', '', $filename);

        // Check if output file already exists
        if (file_exists($outputPath)) {
            $outputPath = $backupDir . '/' . str_replace('.enc', '_decrypted_' . time() . '.sql', $filename);
        }

        $encryption->decryptFile($encryptedPath, $password, $outputPath);

        return "
        <div style='font-family: Inter, sans-serif; max-width: 600px; margin: 50px auto; padding: 30px; background: white; border-radius: 16px; box-shadow: 0 10px 40px rgba(0,0,0,0.1);'>
            <h2 style='color: #10b981; margin-bottom: 20px;'><i class='fas fa-check-circle'></i> File Decrypted Successfully!</h2>
            <div style='background: #f8fafc; padding: 20px; border-radius: 12px; margin-bottom: 20px;'>
                <p><strong>Original File:</strong> " . htmlspecialchars($filename) . "</p>
                <p><strong>Decrypted File:</strong> " . htmlspecialchars(basename($outputPath)) . "</p>
            </div>
            <a href='/cleanup-test' style='display: inline-block; padding: 12px 24px; background: #4361ee; color: white; text-decoration: none; border-radius: 8px;'>← Back to Dashboard</a>
        </div>";

    } catch (\Exception $e) {
        return "
        <div style='font-family: Inter, sans-serif; max-width: 600px; margin: 50px auto; padding: 30px; background: white; border-radius: 16px; box-shadow: 0 10px 40px rgba(0,0,0,0.1);'>
            <h2 style='color: #ef4444; margin-bottom: 20px;'><i class='fas fa-exclamation-triangle'></i> Decryption Failed</h2>
            <div style='background: #fee2e2; padding: 20px; border-radius: 12px; margin-bottom: 20px;'>
                <p><strong>Error:</strong> " . 'Something went wrong. Please try again later.' . "</p>
            </div>
            <a href='/backup/decrypt-file' style='display: inline-block; padding: 12px 24px; background: #4361ee; color: white; text-decoration: none; border-radius: 8px;'>← Try Again</a>
        </div>";
    }
});

// ✅ DIRECT DECRYPT FOR SPECIFIC FILE
Route::get('/backup/decrypt-single/{filename}', function($filename) {
    return '
    <!DOCTYPE html>
    <html>
    <head>
        <title>Decrypt File</title>
        <style>
            body { font-family: Inter, sans-serif; background: #f8fafc; padding: 40px; }
            .container { max-width: 500px; margin: 0 auto; background: white; border-radius: 16px; padding: 30px; box-shadow: 0 10px 40px rgba(0,0,0,0.1); }
            h2 { color: #0f172a; margin-bottom: 20px; }
            .form-group { margin-bottom: 20px; }
            label { display: block; margin-bottom: 8px; font-weight: 600; color: #334155; }
            input { width: 100%; padding: 12px; border: 2px solid #e2e8f0; border-radius: 8px; font-size: 14px; }
            .btn { background: #4361ee; color: white; padding: 12px 24px; border: none; border-radius: 8px; cursor: pointer; font-size: 16px; }
            .btn:hover { background: #3730a3; }
            .filename { background: #f1f5f9; padding: 10px; border-radius: 6px; margin-bottom: 20px; font-family: monospace; }
        </style>
    </head>
    <body>
        <div class="container">
            <h2>🔓 Decrypt File</h2>
            <div class="filename">📄 ' . htmlspecialchars($filename) . '</div>
            <form method="POST" action="/backup/decrypt-single-process">
                ' . csrf_field() . '
                <input type="hidden" name="filename" value="' . htmlspecialchars($filename) . '">
                <div class="form-group">
                    <label>Password:</label>
                    <input type="password" name="password" required placeholder="Enter encryption password">
                </div>
                <button type="submit" class="btn">Decrypt File</button>
            </form>
        </div>
    </body>
    </html>';
})->where('filename', '.*\.enc$');

// ✅ PROCESS SINGLE FILE DECRYPT
Route::post('/backup/decrypt-single-process', function(Request $request) {
    try {
        $filename = $request->input('filename');
        $password = $request->input('password');

        $backupDir = public_path('storage/backup');
        $encryptedPath = $backupDir . '/' . $filename;
        $encryption = new BackupEncryption();

        $outputPath = $backupDir . '/' . str_replace('.enc', '', $filename);

        // Check if output file already exists
        if (file_exists($outputPath)) {
            $outputPath = $backupDir . '/' . str_replace('.enc', '_decrypted_' . time() . '.sql', $filename);
        }

        $encryption->decryptFile($encryptedPath, $password, $outputPath);

        return "
        <div style='font-family: Inter, sans-serif; max-width: 600px; margin: 50px auto; padding: 30px; background: white; border-radius: 16px; box-shadow: 0 10px 40px rgba(0,0,0,0.1);'>
            <h2 style='color: #10b981; margin-bottom: 20px;'>✅ File Decrypted Successfully!</h2>
            <div style='background: #f8fafc; padding: 20px; border-radius: 12px; margin-bottom: 20px;'>
                <p><strong>Original:</strong> " . htmlspecialchars($filename) . "</p>
                <p><strong>Decrypted:</strong> " . htmlspecialchars(basename($outputPath)) . "</p>
            </div>
            <a href='/cleanup-test' style='display: inline-block; padding: 12px 24px; background: #4361ee; color: white; text-decoration: none; border-radius: 8px;'>← Back to Dashboard</a>
        </div>";

    } catch (\Exception $e) {
        return "
        <div style='font-family: Inter, sans-serif; max-width: 600px; margin: 50px auto; padding: 30px; background: white; border-radius: 16px; box-shadow: 0 10px 40px rgba(0,0,0,0.1);'>
            <h2 style='color: #ef4444; margin-bottom: 20px;'>❌ Decryption Failed</h2>
            <div style='background: #fee2e2; padding: 20px; border-radius: 12px; margin-bottom: 20px;'>
                <p><strong>Error:</strong> " . 'Something went wrong. Please try again later.' . "</p>
            </div>
            <a href='/backup/decrypt-single/" . htmlspecialchars($filename) . "' style='display: inline-block; padding: 12px 24px; background: #4361ee; color: white; text-decoration: none; border-radius: 8px;'>← Try Again</a>
        </div>";
    }
});

// ✅ FRESH BACKUP (Without encryption)
Route::get('/backup/create-fresh', function() {
    try {
        $backupDir = public_path('storage/backup');
        if (!is_dir($backupDir)) {
            mkdir($backupDir, 0755, true);
        }

        $timestamp = now()->format('Y-m-d_H-i-s');
        $sqlFile = "caxis_backup_{$timestamp}.sql";
        $sqlPath = $backupDir . '/' . $sqlFile;

        // Create SQL dump
        $command = sprintf(
            'mysqldump --user=%s --password=%s --host=%s %s > %s 2>&1',
            escapeshellarg(env('DB_USERNAME')),
            escapeshellarg(env('DB_PASSWORD')),
            escapeshellarg(env('DB_HOST')),
            escapeshellarg(env('DB_DATABASE')),
            $sqlPath
        );

        exec($command, $output, $returnCode);

        if ($returnCode !== 0) {
            throw new \Exception("mysqldump failed: " . implode("\n", $output));
        }

        return "
        <div style='font-family: Inter, sans-serif; max-width: 600px; margin: 50px auto; padding: 30px; background: white; border-radius: 16px; box-shadow: 0 10px 40px rgba(0,0,0,0.1);'>
            <h2 style='color: #10b981; margin-bottom: 20px;'>✅ Fresh Backup Created!</h2>
            <div style='background: #f8fafc; padding: 20px; border-radius: 12px; margin-bottom: 20px;'>
                <p><strong>Filename:</strong> " . basename($sqlPath) . "</p>
                <p><strong>Size:</strong> " . round(filesize($sqlPath)/1024, 2) . " KB</p>
                <p><strong>Status:</strong> Plain SQL (Not Encrypted)</p>
            </div>
            <a href='/cleanup-test' style='display: inline-block; padding: 12px 24px; background: #4361ee; color: white; text-decoration: none; border-radius: 8px;'>← Back to Dashboard</a>
        </div>";

    } catch (\Exception $e) {
        return "<div style='color: #ef4444; padding: 20px;'>Error: " . 'Something went wrong. Please try again later.' . "</div>";
    }
});



// ============================================
// ðŸŽ¨ PERFECT MODERN DESIGN 2026 - BACKUP DASHBOARD
// ============================================
Route::get('/cleanup-test', function() {
    echo "<!DOCTYPE html>
    <html lang='en'>
    <head>
        <meta charset='UTF-8'>
        <meta name='viewport' content='width=device-width, initial-scale=1.0'>
        <title>Backup Manager â€¢ Modern Dashboard</title>
        <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css'>
        <style>
            /* ============================================
               PERFECT MODERN DESIGN 2026
               Clean â€¢ Vibrant â€¢ Professional
               ============================================ */

            @import url('https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&display=swap');

            * {
                margin: 0;
                padding: 0;
                box-sizing: border-box;
            }

            :root {
                /* Perfect Color Palette 2026 */
                --primary: #4361ee;
                --primary-light: #e0e7ff;
                --primary-dark: #3730a3;
                --secondary: #06b6d4;
                --secondary-light: #cffafe;
                --success: #10b981;
                --success-light: #d1fae5;
                --warning: #f59e0b;
                --warning-light: #fef3c7;
                --danger: #ef4444;
                --danger-light: #fee2e2;
                --info: #3b82f6;
                --info-light: #dbeafe;
                --purple: #8b5cf6;
                --purple-light: #ede9fe;

                /* Neutrals - Perfect Balance */
                --bg: #f8fafc;
                --surface: #ffffff;
                --surface-hover: #f1f5f9;
                --border: #e2e8f0;
                --border-dark: #cbd5e1;

                /* Text - High Contrast */
                --text-primary: #0f172a;
                --text-secondary: #334155;
                --text-tertiary: #64748b;
                --text-light: #94a3b8;

                /* Shadows - Subtle */
                --shadow-sm: 0 1px 2px 0 rgb(0 0 0 / 0.02);
                --shadow: 0 4px 6px -1px rgb(0 0 0 / 0.05), 0 2px 4px -2px rgb(0 0 0 / 0.02);
                --shadow-md: 0 10px 15px -3px rgb(0 0 0 / 0.05), 0 4px 6px -4px rgb(0 0 0 / 0.02);
                --shadow-lg: 0 20px 25px -5px rgb(0 0 0 / 0.05), 0 8px 10px -6px rgb(0 0 0 / 0.02);

                /* Radius - Modern */
                --radius-sm: 6px;
                --radius: 8px;
                --radius-md: 12px;
                --radius-lg: 16px;
                --radius-xl: 20px;
                --radius-2xl: 24px;
            }

            body {
                font-family: 'Inter', sans-serif;
                background: var(--bg);
                color: var(--text-primary);
                line-height: 1.5;
                padding: 24px;
                -webkit-font-smoothing: antialiased;
            }

            .dashboard {
                max-width: 1440px;
                margin: 0 auto;
            }

            /* Header - Clean & Modern */
            .header {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin-bottom: 32px;
                flex-wrap: wrap;
                gap: 16px;
                background: var(--surface);
                padding: 20px 24px;
                border-radius: var(--radius-xl);
                box-shadow: var(--shadow);
                border: 1px solid var(--border);
            }

            .header-left {
                display: flex;
                align-items: center;
                gap: 16px;
            }

            .logo {
                width: 48px;
                height: 48px;
                background: var(--primary);
                border-radius: var(--radius-md);
                display: flex;
                align-items: center;
                justify-content: center;
                color: white;
                font-size: 22px;
                box-shadow: var(--shadow-sm);
            }

            .title h1 {
                font-size: 22px;
                font-weight: 700;
                color: var(--text-primary);
                margin-bottom: 4px;
                letter-spacing: -0.3px;
            }

            .title p {
                font-size: 13px;
                color: var(--text-tertiary);
                display: flex;
                align-items: center;
                gap: 6px;
            }

            .title p i {
                color: var(--primary);
                font-size: 12px;
            }

            .time-badge {
                background: var(--bg);
                padding: 10px 18px;
                border-radius: 40px;
                display: flex;
                align-items: center;
                gap: 12px;
                border: 1px solid var(--border);
                color: var(--text-secondary);
                font-size: 14px;
                font-weight: 500;
            }

            .time-badge i {
                color: var(--primary);
                font-size: 14px;
            }

            /* Stats Grid - Perfect Cards */
            .stats-grid {
                display: grid;
                grid-template-columns: repeat(4, 1fr);
                gap: 20px;
                margin-bottom: 32px;
            }

            .stat-card {
                background: var(--surface);
                border-radius: var(--radius-lg);
                padding: 24px;
                box-shadow: var(--shadow);
                border: 1px solid var(--border);
                transition: all 0.2s ease;
            }

            .stat-card:hover {
                transform: translateY(-2px);
                box-shadow: var(--shadow-md);
                border-color: var(--primary);
            }

            .stat-header {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin-bottom: 16px;
            }

            .stat-icon {
                width: 48px;
                height: 48px;
                border-radius: var(--radius-md);
                display: flex;
                align-items: center;
                justify-content: center;
                font-size: 20px;
            }

            .stat-card:nth-child(1) .stat-icon {
                background: var(--primary-light);
                color: var(--primary);
            }

            .stat-card:nth-child(2) .stat-icon {
                background: var(--success-light);
                color: var(--success);
            }

            .stat-card:nth-child(3) .stat-icon {
                background: var(--warning-light);
                color: var(--warning);
            }

            .stat-card:nth-child(4) .stat-icon {
                background: var(--purple-light);
                color: var(--purple);
            }

            .stat-menu {
                color: var(--text-light);
                font-size: 16px;
                cursor: pointer;
                padding: 4px 8px;
                border-radius: var(--radius-sm);
            }

            .stat-menu:hover {
                background: var(--surface-hover);
            }

            .stat-label {
                font-size: 13px;
                font-weight: 500;
                color: var(--text-tertiary);
                margin-bottom: 8px;
                text-transform: uppercase;
                letter-spacing: 0.3px;
            }

            .stat-value {
                font-size: 32px;
                font-weight: 700;
                color: var(--text-primary);
                line-height: 1.2;
                margin-bottom: 8px;
            }

            .stat-trend {
                display: flex;
                align-items: center;
                gap: 8px;
                font-size: 13px;
            }

            .trend-up {
                background: var(--success-light);
                color: var(--success);
                padding: 2px 8px;
                border-radius: 20px;
                font-weight: 600;
                font-size: 12px;
            }

            .trend-text {
                color: var(--text-tertiary);
            }

            /* Section Headers */
            .section-header {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin: 32px 0 20px;
            }

            .section-title {
                display: flex;
                align-items: center;
                gap: 12px;
            }

            .section-title i {
                width: 40px;
                height: 40px;
                background: var(--surface);
                border: 1px solid var(--border);
                border-radius: var(--radius);
                display: flex;
                align-items: center;
                justify-content: center;
                color: var(--primary);
                font-size: 18px;
            }

            .section-title h2 {
                font-size: 18px;
                font-weight: 600;
                color: var(--text-primary);
            }

            .section-badge {
                background: var(--surface);
                border: 1px solid var(--border);
                padding: 6px 14px;
                border-radius: 40px;
                font-size: 12px;
                font-weight: 500;
                color: var(--text-secondary);
                display: flex;
                align-items: center;
                gap: 6px;
            }

            .section-badge i {
                color: var(--primary);
                font-size: 12px;
            }

            /* Info Cards */
            .info-grid {
                display: grid;
                grid-template-columns: repeat(3, 1fr);
                gap: 20px;
                margin-bottom: 32px;
            }

            .info-card {
                background: var(--surface);
                border: 1px solid var(--border);
                border-radius: var(--radius-lg);
                padding: 20px;
                display: flex;
                align-items: center;
                gap: 16px;
                transition: all 0.2s ease;
            }

            .info-card:hover {
                border-color: var(--primary);
                box-shadow: var(--shadow);
            }

            .info-icon {
                width: 52px;
                height: 52px;
                background: var(--primary-light);
                border-radius: var(--radius-md);
                display: flex;
                align-items: center;
                justify-content: center;
                color: var(--primary);
                font-size: 22px;
            }

            .info-content {
                flex: 1;
            }

            .info-label {
                font-size: 12px;
                color: var(--text-tertiary);
                margin-bottom: 4px;
                font-weight: 500;
            }

            .info-value {
                font-size: 14px;
                font-weight: 600;
                color: var(--text-primary);
                font-family: 'SF Mono', monospace;
            }

            /* Table Container */
            .table-container {
                background: var(--surface);
                border: 1px solid var(--border);
                border-radius: var(--radius-lg);
                overflow: hidden;
                margin-bottom: 32px;
            }

            .table-header {
                padding: 18px 20px;
                background: var(--bg);
                border-bottom: 1px solid var(--border);
                display: flex;
                justify-content: space-between;
                align-items: center;
            }

            .table-header h3 {
                font-size: 15px;
                font-weight: 600;
                color: var(--text-primary);
                display: flex;
                align-items: center;
                gap: 8px;
            }

            .table-header h3 i {
                color: var(--primary);
            }

            .table-count {
                background: var(--surface);
                padding: 4px 12px;
                border-radius: 30px;
                font-size: 12px;
                font-weight: 600;
                color: var(--text-secondary);
                border: 1px solid var(--border);
            }

            .table-wrapper {
                overflow-x: auto;
            }

            table {
                width: 100%;
                border-collapse: collapse;
                font-size: 14px;
            }

            th {
                text-align: left;
                padding: 16px 20px;
                background: var(--bg);
                color: var(--text-tertiary);
                font-weight: 600;
                font-size: 12px;
                text-transform: uppercase;
                letter-spacing: 0.3px;
                border-bottom: 1px solid var(--border);
            }

            td {
                padding: 16px 20px;
                border-bottom: 1px solid var(--border);
                color: var(--text-primary);
            }

            tr:last-child td {
                border-bottom: none;
            }

            tr:hover td {
                background: var(--bg);
            }

            .file-cell {
                display: flex;
                align-items: center;
                gap: 12px;
            }

            .file-icon {
                width: 40px;
                height: 40px;
                background: var(--primary-light);
                border-radius: var(--radius-sm);
                display: flex;
                align-items: center;
                justify-content: center;
                color: var(--primary);
                font-size: 18px;
            }

            .file-name {
                font-weight: 600;
                color: var(--text-primary);
                margin-bottom: 2px;
                font-family: 'SF Mono', monospace;
                font-size: 13px;
            }

            .file-meta {
                font-size: 11px;
                color: var(--text-tertiary);
            }

            /* Badges - Modern */
            .badge {
                display: inline-flex;
                align-items: center;
                gap: 4px;
                padding: 4px 10px;
                border-radius: 30px;
                font-size: 12px;
                font-weight: 500;
            }

            .badge.size {
                background: var(--bg);
                color: var(--text-secondary);
                border: 1px solid var(--border);
            }

            .badge.age {
                background: var(--bg);
                color: var(--text-secondary);
                border: 1px solid var(--border);
            }

            .badge.keep {
                background: var(--success-light);
                color: var(--success);
                border: none;
            }

            .badge.delete {
                background: var(--danger-light);
                color: var(--danger);
                border: none;
            }

            /* Action Buttons - Clean */
            .actions {
                display: flex;
                gap: 6px;
            }

            .btn-icon {
                width: 34px;
                height: 34px;
                border-radius: var(--radius-sm);
                display: flex;
                align-items: center;
                justify-content: center;
                text-decoration: none;
                transition: all 0.2s ease;
                font-size: 14px;
                background: var(--bg);
                border: 1px solid var(--border);
                color: var(--text-secondary);
            }

            .btn-icon:hover {
                background: var(--primary);
                color: white;
                border-color: var(--primary);
                transform: translateY(-1px);
            }

            .btn-icon.view:hover {
                background: var(--primary);
                border-color: var(--primary);
            }

            /* Action Cards - Clean */
            .action-grid {
                display: grid;
                grid-template-columns: repeat(3, 1fr);
                gap: 20px;
                margin-bottom: 32px;
            }

            .action-card {
                background: var(--surface);
                border: 1px solid var(--border);
                border-radius: var(--radius-lg);
                padding: 24px;
                text-align: center;
                text-decoration: none;
                transition: all 0.2s ease;
                display: block;
            }

            .action-card:hover {
                transform: translateY(-2px);
                border-color: var(--primary);
                box-shadow: var(--shadow);
            }

            .action-card i {
                font-size: 32px;
                margin-bottom: 16px;
            }

            .action-card:nth-child(1) i {
                color: var(--primary);
            }

            .action-card:nth-child(2) i {
                color: var(--warning);
            }

            .action-card:nth-child(3) i {
                color: var(--danger);
            }

            .action-title {
                font-size: 16px;
                font-weight: 600;
                color: var(--text-primary);
                margin-bottom: 8px;
            }

            .action-desc {
                font-size: 12px;
                color: var(--text-tertiary);
            }

            /* Log Viewer */
            .log-container {
                background: var(--surface);
                border: 1px solid var(--border);
                border-radius: var(--radius-lg);
                overflow: hidden;
                margin-bottom: 32px;
            }

            .log-header {
                padding: 16px 20px;
                background: var(--bg);
                border-bottom: 1px solid var(--border);
                display: flex;
                justify-content: space-between;
                align-items: center;
            }

            .log-title {
                display: flex;
                align-items: center;
                gap: 8px;
                font-weight: 600;
                color: var(--text-primary);
                font-size: 14px;
            }

            .log-title i {
                color: var(--primary);
            }

            .log-time {
                color: var(--text-tertiary);
                font-size: 12px;
                display: flex;
                align-items: center;
                gap: 6px;
            }

            .log-content {
                padding: 20px;
                background: #1a1e24;
                font-family: 'SF Mono', monospace;
                font-size: 12px;
                line-height: 1.7;
                color: #e2e8f0;
                max-height: 400px;
                overflow-y: auto;
            }

            .log-line {
                padding: 4px 0;
                border-bottom: 1px solid #2d3748;
                font-family: 'SF Mono', monospace;
            }

            .log-line.success { color: #10b981; }
            .log-line.error { color: #ef4444; }
            .log-line.warning { color: #f59e0b; }

            /* Footer */
            .footer {
                display: grid;
                grid-template-columns: repeat(4, 1fr);
                gap: 20px;
                margin-top: 40px;
                padding: 24px;
                background: var(--surface);
                border: 1px solid var(--border);
                border-radius: var(--radius-lg);
            }

            .footer-item {
                text-align: center;
            }

            .footer-label {
                font-size: 11px;
                font-weight: 600;
                color: var(--text-tertiary);
                text-transform: uppercase;
                letter-spacing: 0.5px;
                margin-bottom: 8px;
            }

            .footer-value {
                font-size: 18px;
                font-weight: 700;
                color: var(--text-primary);
                margin-bottom: 4px;
            }

            .footer-sub {
                font-size: 11px;
                color: var(--text-tertiary);
            }

            /* Empty State */
            .empty-state {
                text-align: center;
                padding: 60px 20px;
                background: var(--surface);
                border: 1px solid var(--border);
                border-radius: var(--radius-lg);
            }

            .empty-state i {
                font-size: 48px;
                color: var(--text-light);
                margin-bottom: 16px;
            }

            .empty-state h3 {
                font-size: 18px;
                font-weight: 600;
                color: var(--text-primary);
                margin-bottom: 8px;
            }

            .empty-state p {
                color: var(--text-tertiary);
                font-size: 14px;
            }

            /* Responsive */
            @media (max-width: 1024px) {
                .stats-grid { grid-template-columns: repeat(2, 1fr); }
                .info-grid { grid-template-columns: repeat(2, 1fr); }
            }

            @media (max-width: 768px) {
                body { padding: 16px; }
                .header { flex-direction: column; align-items: flex-start; }
                .stats-grid,
                .info-grid,
                .action-grid,
                .footer {
                    grid-template-columns: 1fr;
                }
                .time-badge { width: 100%; }
            }

            /* Utility Classes */
            .text-primary { color: var(--primary); }
            .text-success { color: var(--success); }
            .text-warning { color: var(--warning); }
            .text-danger { color: var(--danger); }
            .bg-light { background: var(--bg); }
        </style>
    </head>
    <body>
        <div class='dashboard'>";

    // ============================================
    // LOGIC - EXACTLY SAME
    // ============================================
    $backupDir = public_path('storage/backup');
    $files = is_dir($backupDir) ? scandir($backupDir) : array();
    $sqlFiles = array();
    foreach ($files as $f) {
        if ($f !== '.' && $f !== '..' && pathinfo($f, PATHINFO_EXTENSION) === 'sql') {
            $sqlFiles[] = $f;
        }
    }

    $totalSize = 0;
    $oldestFile = null;
    $newestFile = null;

    foreach ($sqlFiles as $file) {
        $filePath = $backupDir . '/' . $file;
        $totalSize += filesize($filePath);
        $fileTime = filemtime($filePath);
        if (!$oldestFile || $fileTime < $oldestFile['time']) {
            $oldestFile = array('name' => $file, 'time' => $fileTime);
        }
        if (!$newestFile || $fileTime > $newestFile['time']) {
            $newestFile = array('name' => $file, 'time' => $fileTime);
        }
    }

    // ============================================
    // HEADER
    // ============================================
    echo "<div class='header'>
            <div class='header-left'>
                <div class='logo'>
                    <i class='fas fa-database'></i>
                </div>
                <div class='title'>
                    <h1>Backup Manager</h1>
                    <p><i class='fas fa-shield-alt'></i> 30 Days Retention â€¢ Automated</p>
                </div>
            </div>
            <div class='time-badge'>
                <i class='far fa-calendar'></i>
                " . now('Asia/Kolkata')->format('D, M j, Y â€¢ g:i A') . "
                <i class='fas fa-chevron-down' style='font-size: 10px; opacity: 0.5;'></i>
            </div>
          </div>";

    // ============================================
    // STATS CARDS
    // ============================================
    echo "<div class='stats-grid'>";

    $stats = [
        ['icon' => 'fa-copy', 'label' => 'Total Backups', 'value' => count($sqlFiles), 'trend' => 'files', 'trendValue' => '+2 this week'],
        ['icon' => 'fa-hard-drive', 'label' => 'Storage Used', 'value' => round($totalSize / 1024 / 1024, 2) . ' MB', 'trend' => 'total', 'trendValue' => round($totalSize / 1024 / 1024 / 1024, 2) . ' GB'],
        ['icon' => 'fa-calendar', 'label' => 'Oldest Backup', 'value' => ($oldestFile ? Carbon::createFromTimestamp($oldestFile['time'])->diffInDays(now('Asia/Kolkata')) . ' days' : '-'), 'trend' => 'created', 'trendValue' => ($oldestFile ? Carbon::createFromTimestamp($oldestFile['time'])->format('M d, Y') : '')],
        ['icon' => 'fa-clock', 'label' => 'Newest Backup', 'value' => ($newestFile ? Carbon::createFromTimestamp($newestFile['time'])->diffInHours(now('Asia/Kolkata')) . ' hours' : '-'), 'trend' => 'today', 'trendValue' => ($newestFile ? Carbon::createFromTimestamp($newestFile['time'])->format('g:i A') : '')]
    ];

    foreach ($stats as $stat) {
        echo "<div class='stat-card'>
                <div class='stat-header'>
                    <div class='stat-icon'><i class='fas {$stat['icon']}'></i></div>
                    <div class='stat-menu'><i class='fas fa-ellipsis-v'></i></div>
                </div>
                <div class='stat-label'>{$stat['label']}</div>
                <div class='stat-value'>{$stat['value']}</div>
                <div class='stat-trend'>
                    <span class='trend-up'>â†‘</span>
                    <span class='trend-text'>{$stat['trendValue']}</span>
                </div>
              </div>";
    }

    echo "</div>";

    // ============================================
    // SYSTEM INFO
    // ============================================
    echo "<div class='section-header'>
            <div class='section-title'>
                <i class='fas fa-server'></i>
                <h2>System Information</h2>
            </div>
            <div class='section-badge'>
                <i class='fas fa-circle' style='color: #10b981;'></i> Operational
            </div>
          </div>";

    echo "<div class='info-grid'>";

    $infoItems = [
        ['icon' => 'fa-folder', 'label' => 'Storage Path', 'value' => '<code>' . htmlspecialchars($backupDir) . '</code>'],
        ['icon' => 'fa-check-circle', 'label' => 'Directory Status', 'value' => is_dir($backupDir) ? 'Active' : 'Inactive'],
        ['icon' => 'fa-lock', 'label' => 'Permissions', 'value' => is_dir($backupDir) ? substr(sprintf('%o', fileperms($backupDir)), -4) . ' â€¢ ' . (is_writable($backupDir) ? 'Writable' : 'Read Only') : 'N/A']
    ];

    foreach ($infoItems as $item) {
        echo "<div class='info-card'>
                <div class='info-icon'><i class='fas {$item['icon']}'></i></div>
                <div class='info-content'>
                    <div class='info-label'>{$item['label']}</div>
                    <div class='info-value'>{$item['value']}</div>
                </div>
              </div>";
    }

    echo "</div>";

    // ============================================
    // FILE LIST
    // ============================================
    echo "<div class='section-header'>
            <div class='section-title'>
                <i class='fas fa-list'></i>
                <h2>Backup Files</h2>
            </div>
            <div class='section-badge'>
                <i class='fas fa-database'></i> " . count($sqlFiles) . " Items
            </div>
          </div>";

    if (is_dir($backupDir) && count($sqlFiles) > 0) {
        echo "<div class='table-container'>
                <div class='table-header'>
                    <h3><i class='fas fa-database'></i> Active Backups</h3>
                    <span class='table-count'>Last 30 days</span>
                </div>
                <div class='table-wrapper'>
                    <table>
                        <thead>
                            <tr>
                                <th>File Name</th>
                                <th>Size</th>
                                <th>Created</th>
                                <th>Age</th>
                                <th>Status</th>
                                <th>View</th>
                            </tr>
                        </thead>
                        <tbody>";

        $now = now('Asia/Kolkata');
        $fileData = array();

        foreach ($sqlFiles as $file) {
            $filePath = $backupDir . '/' . $file;
            $fileTime = Carbon::createFromTimestamp(filemtime($filePath))->tz('Asia/Kolkata');
            $ageDays = $fileTime->diffInDays($now);
            $ageHours = $fileTime->diffInHours($now) % 24;
            $fileSize = round(filesize($filePath) / 1024, 2);

            $statusClass = $ageDays >= 30 ? 'delete' : 'keep';
            $statusText = $ageDays >= 30 ? 'To Delete' : 'Keep';

            $fileData[] = array(
                'name' => $file,
                'path' => $filePath,
                'ageDays' => $ageDays,
                'fileTime' => $fileTime
            );

            echo "<tr>
                    <td>
                        <div class='file-cell'>
                            <div class='file-icon'><i class='fas fa-database'></i></div>
                            <div>
                                <div class='file-name'>" . htmlspecialchars($file) . "</div>
                                <div class='file-meta'>Modified: " . $fileTime->format('H:i:s') . "</div>
                            </div>
                        </div>
                    </td>
                    <td><span class='badge size'><i class='fas fa-weight-hanging'></i> {$fileSize} KB</span></td>
                    <td>" . $fileTime->format('M j, Y') . "</td>
                    <td><span class='badge age'><i class='far fa-clock'></i> {$ageDays}d {$ageHours}h</span></td>
                    <td><span class='badge {$statusClass}'><i class='fas " . ($ageDays >= 30 ? 'fa-exclamation-triangle' : 'fa-check-circle') . "'></i> {$statusText}</span></td>
                    <td>
                        <div class='actions'>
                            <a href='/public/storage/backup/" . urlencode($file) . "' target='_blank' class='btn-icon view' title='View'><i class='fas fa-eye'></i></a>
                        </div>
                    </td>
                  </tr>";
        }

        echo "</tbody></table>
                </div>
            </div>";

        // Daily Summary
        echo "<div class='section-header' style='margin-top: 24px;'>
                <div class='section-title'>
                    <i class='fas fa-calendar-week'></i>
                    <h2>Retention Summary</h2>
                </div>
                <div class='section-badge'>
                    <i class='fas fa-clock'></i> 30 Days Policy
                </div>
              </div>";

        echo "<div class='table-container'>
                <div class='table-wrapper'>
                    <table>
                        <thead>
                            <tr>
                                <th>Date</th>
                                <th>Backups</th>
                                <th>Status</th>
                                <th>Days Remaining</th>
                            </tr>
                        </thead>
                        <tbody>";

        $daily = array();
        foreach ($fileData as $f) {
            $day = $f['fileTime']->format('Y-m-d');
            if (!isset($daily[$day])) {
                $daily[$day] = 0;
            }
            $daily[$day]++;
        }

        foreach ($daily as $day => $count) {
            $ageDays = Carbon::parse($day, 'Asia/Kolkata')->diffInDays($now);
            $status = $ageDays >= 30 ? 'To Delete' : 'Keep';
            $statusClass = $ageDays >= 30 ? 'delete' : 'keep';
            $daysLeft = $ageDays >= 30 ? 0 : 30 - $ageDays;

            echo "<tr>
                    <td><span style='font-weight: 600;'>" . Carbon::parse($day, 'Asia/Kolkata')->format('l, M j, Y') . "</span></td>
                    <td><span class='badge' style='background: var(--bg); color: var(--text-secondary);'>{$count}</span></td>
                    <td><span class='badge {$statusClass}'><i class='fas " . ($ageDays >= 30 ? 'fa-exclamation-triangle' : 'fa-check-circle') . "'></i> {$status}</span></td>
                    <td><span class='badge age'><i class='far fa-clock'></i> {$daysLeft} days</span></td>
                  </tr>";
        }

        echo "</tbody></table>
                </div>
            </div>";

    } else {
        echo "<div class='empty-state'>
                <i class='fas fa-database'></i>
                <h3>No Backup Files Found</h3>
                <p>Run a backup to see files here</p>
              </div>";
    }

    // ============================================
    // CLEANUP ACTIONS SECTION (REMOVED)
    // ============================================
    // All cleanup operations have been removed as requested

    // ============================================
    // SYSTEM LOGS
    // ============================================
    echo "<div class='section-header' style='margin-top: 32px;'>
            <div class='section-title'>
                <i class='fas fa-history'></i>
                <h2>System Logs</h2>
            </div>
          </div>";

    echo "<div class='action-grid' style='grid-template-columns: repeat(2, 1fr); margin-bottom: 24px;'>";

    $logActions = [
        ['icon' => 'fa-file-alt', 'title' => 'Laravel Log', 'link' => '?viewlog=laravel'],
        ['icon' => 'fa-database', 'title' => 'Backup Log', 'link' => '?viewlog=backup']
    ];

    foreach ($logActions as $action) {
        echo "<a href='" . $action['link'] . "' class='action-card'>
                <i class='fas " . $action['icon'] . "'></i>
                <div class='action-title'>" . $action['title'] . "</div>
              </a>";
    }

    echo "</div>";

    if (isset($_GET['viewlog'])) {
        $logFile = $_GET['viewlog'] == 'laravel'
            ? storage_path('logs/laravel.log')
            : storage_path('logs/backup.log');

        echo "<div class='log-container'>
                <div class='log-header'>
                    <div class='log-title'>
                        <i class='fas fa-file-alt'></i>
                        <span>" . basename($logFile) . "</span>
                    </div>
                    <div class='log-time'>
                        <i class='far fa-clock'></i>
                        " . now('Asia/Kolkata')->format('H:i:s') . "
                    </div>
                </div>
                <div class='log-content'>";

        if (file_exists($logFile)) {
            $logs = file($logFile);
            $logs = array_slice($logs, -100);
            $logs = array_reverse($logs);
            foreach ($logs as $log) {
                $log = htmlspecialchars($log);
                $class = 'log-line';
                if (strpos($log, 'ERROR') !== false) $class .= ' error';
                elseif (strpos($log, 'INFO') !== false) $class .= ' success';
                elseif (strpos($log, 'WARNING') !== false) $class .= ' warning';
                echo "<div class='$class'>" . $log . "</div>";
            }
        } else {
            echo "<div class='log-line'>ðŸ“­ Log file not found</div>";
        }

        echo "</div></div>";
    }

    // ============================================
    // FOOTER
    // ============================================
    $nextCleanup = now('Asia/Kolkata')->addDay()->setTime(2, 0, 0);
    $storagePercent = min(round(($totalSize / 1024 / 1024 / 1024) * 100, 2), 100);

    echo "<div class='footer'>
            <div class='footer-item'>
                <div class='footer-label'>Next Cleanup</div>
                <div class='footer-value'>" . $nextCleanup->format('M j') . "</div>
                <div class='footer-sub'>2:00 AM IST</div>
            </div>
            <div class='footer-item'>
                <div class='footer-label'>Retention</div>
                <div class='footer-value'>30 Days</div>
                <div class='footer-sub'>Auto</div>
            </div>
            <div class='footer-item'>
                <div class='footer-label'>Storage</div>
                <div class='footer-value'>" . round($totalSize / 1024 / 1024, 2) . " MB</div>
                <div class='footer-sub'>" . $storagePercent . "% used</div>
            </div>
            <div class='footer-item'>
                <div class='footer-label'>Status</div>
                <div class='footer-value'>" . (count($sqlFiles) > 0 ? 'Active' : 'Idle') . "</div>
                <div class='footer-sub'>" . count($sqlFiles) . " files</div>
            </div>
          </div>";

    echo "</div></body></html>";
})->name('cleanup.test');
