<?php
include 'db.php';
include 'auth.php';
include 'layout.php';

// Load backup engine
include_once 'backup_engine.php';

$success_message = '';
$error_message = '';
$backups = [];

try {
    $engine = new DatabaseBackupEngine();
    $backups = $engine->getBackupsList();
} catch (Exception $e) {
    $error_message = "Error loading backup information: " . $e->getMessage();
}

// Handle restoration request
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['restore_backup'])) {
    $backupFile = $_POST['backup_file'] ?? '';
    $confirmRestore = isset($_POST['confirm_restore']);
    $createBackupBeforeRestore = isset($_POST['create_backup_before_restore']);
    
    if (empty($backupFile)) {
        $error_message = "Please select a backup file to restore.";
    } elseif (!$confirmRestore) {
        $error_message = "Please confirm that you understand this action will replace your current database.";
    } else {
        try {
            // Create a backup before restoring if requested
            if ($createBackupBeforeRestore) {
                $preRestoreBackup = $engine->createBackup('pre_restore');
                if (!$preRestoreBackup['success']) {
                    throw new Exception("Failed to create pre-restore backup: " . $preRestoreBackup['message']);
                }
            }
            
            // Perform restoration
            $result = restoreDatabase($backupFile);
            if ($result['success']) {
                $success_message = $result['message'];
            } else {
                throw new Exception($result['message']);
            }
            
        } catch (Exception $e) {
            $error_message = "Restoration failed: " . $e->getMessage();
        }
    }
}

// Handle file upload for external backup
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['upload_backup'])) {
    $uploadedFile = $_FILES['upload_backup'];
    
    if ($uploadedFile['error'] === UPLOAD_ERR_OK) {
        $backupDir = 'D:/wamp/backups/itrpos/';
        if (!is_dir($backupDir)) {
            mkdir($backupDir, 0755, true);
        }
        
        $filename = 'uploaded_backup_' . date('Y-m-d_H-i-s') . '.sql';
        $targetPath = $backupDir . $filename;
        
        if (move_uploaded_file($uploadedFile['tmp_name'], $targetPath)) {
            $success_message = "Backup file uploaded successfully: $filename";
            // Refresh backup list
            $backups = $engine->getBackupsList();
        } else {
            $error_message = "Failed to upload backup file.";
        }
    } else {
        $error_message = "Upload error: " . getUploadErrorMessage($uploadedFile['error']);
    }
}

function restoreDatabase($backupFilename) {
    global $host, $username, $password, $db_name;
    
    $backupDir = 'D:/wamp/backups/itrpos/';
    $backupPath = $backupDir . $backupFilename;
    
    if (!file_exists($backupPath)) {
        return ['success' => false, 'message' => 'Backup file not found: ' . $backupFilename];
    }
    
    try {
        // Log restoration attempt
        $logFile = $backupDir . 'backup_log.txt';
        $logEntry = "[" . date('Y-m-d H:i:s') . "] [INFO] Starting database restoration from: $backupFilename" . PHP_EOL;
        file_put_contents($logFile, $logEntry, FILE_APPEND | LOCK_EX);
        
        // Check if file is compressed
        $isCompressed = substr($backupFilename, -3) === '.gz';
        
        if ($isCompressed) {
            // Handle compressed backup
            $command = "gunzip < " . escapeshellarg($backupPath) . " | mysql";
        } else {
            // Handle uncompressed backup
            $command = "mysql";
        }
        
        $command .= " --host=" . escapeshellarg($host);
        $command .= " --user=" . escapeshellarg($username);
        $command .= " --password=" . escapeshellarg($password);
        $command .= " " . escapeshellarg($db_name);
        
        if (!$isCompressed) {
            $command .= " < " . escapeshellarg($backupPath);
        }
        
        // Execute restoration
        exec($command . ' 2>&1', $output, $returnCode);
        
        if ($returnCode === 0) {
            $message = "Database restored successfully from: $backupFilename";
            $logEntry = "[" . date('Y-m-d H:i:s') . "] [SUCCESS] $message" . PHP_EOL;
            file_put_contents($logFile, $logEntry, FILE_APPEND | LOCK_EX);
            
            return ['success' => true, 'message' => $message];
        } else {
            $errorOutput = implode("\n", $output);
            $message = "MySQL restoration failed. Return code: $returnCode. Output: $errorOutput";
            $logEntry = "[" . date('Y-m-d H:i:s') . "] [ERROR] $message" . PHP_EOL;
            file_put_contents($logFile, $logEntry, FILE_APPEND | LOCK_EX);
            
            return ['success' => false, 'message' => $message];
        }
        
    } catch (Exception $e) {
        $message = "Restoration exception: " . $e->getMessage();
        $logEntry = "[" . date('Y-m-d H:i:s') . "] [ERROR] $message" . PHP_EOL;
        file_put_contents($logFile, $logEntry, FILE_APPEND | LOCK_EX);
        
        return ['success' => false, 'message' => $message];
    }
}

function getUploadErrorMessage($errorCode) {
    $messages = [
        UPLOAD_ERR_INI_SIZE => 'File exceeds upload_max_filesize directive',
        UPLOAD_ERR_FORM_SIZE => 'File exceeds MAX_FILE_SIZE directive',
        UPLOAD_ERR_PARTIAL => 'File was only partially uploaded',
        UPLOAD_ERR_NO_FILE => 'No file was uploaded',
        UPLOAD_ERR_NO_TMP_DIR => 'Missing temporary folder',
        UPLOAD_ERR_CANT_WRITE => 'Failed to write file to disk',
        UPLOAD_ERR_EXTENSION => 'A PHP extension stopped the file upload'
    ];
    
    return $messages[$errorCode] ?? 'Unknown upload error';
}

// Get database information for display
function getDatabaseInfo() {
    global $conn;
    
    $info = [
        'tables' => 0,
        'total_records' => 0,
        'database_size' => 'Unknown'
    ];
    
    try {
        // Get table count
        $result = $conn->query("SELECT COUNT(*) as table_count FROM information_schema.tables WHERE table_schema = DATABASE()");
        if ($result && $row = $result->fetch_assoc()) {
            $info['tables'] = $row['table_count'];
        }
        
        // Get total records (approximate)
        $result = $conn->query("
            SELECT SUM(table_rows) as total_rows 
            FROM information_schema.tables 
            WHERE table_schema = DATABASE() AND table_type = 'BASE TABLE'
        ");
        if ($result && $row = $result->fetch_assoc()) {
            $info['total_records'] = $row['total_rows'] ?? 0;
        }
        
        // Get database size
        $result = $conn->query("
            SELECT ROUND(SUM(data_length + index_length) / 1024 / 1024, 2) AS size_mb
            FROM information_schema.tables
            WHERE table_schema = DATABASE()
        ");
        if ($result && $row = $result->fetch_assoc()) {
            $info['database_size'] = $row['size_mb'] . ' MB';
        }
        
    } catch (Exception $e) {
        // Error getting database info
    }
    
    return $info;
}

$dbInfo = getDatabaseInfo();
?>

<div class="page-wrapper">
    <div class="content">
        <div class="page-header">
            <div class="add-item d-flex">
                <div class="page-title">
                    <h4>🔄 Database Restore</h4>
                    <h6>Restore your database from a backup file</h6>
                </div>
            </div>
            <ul class="table-top-head">
                <li>
                    <a href="backup_management.php" class="btn btn-secondary">
                        <i data-feather="bar-chart-2" class="feather-16"></i> Management
                    </a>
                </li>
                <li>
                    <a href="backup_management.php" class="btn btn-info">
                        <i data-feather="settings" class="feather-16"></i> Settings
                    </a>
                </li>
                <li>
                    <a href="backup_engine.php?action=run_now&type=manual" class="btn btn-primary" 
                       onclick="return confirm('Create a backup now?')">
                        <i data-feather="save" class="feather-16"></i> Create Backup
                    </a>
                </li>
            </ul>
        </div>

        <?php if ($success_message): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <i data-feather="check-circle" class="feather-16"></i> <?php echo htmlspecialchars($success_message); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        <?php endif; ?>

        <?php if ($error_message): ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <i data-feather="alert-circle" class="feather-16"></i> <?php echo htmlspecialchars($error_message); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        <?php endif; ?>

        <!-- Warning Banner -->
        <div class="alert alert-warning" role="alert">
            <h6><i data-feather="alert-triangle" class="feather-16"></i> Important Warning</h6>
            <p class="mb-0">
                Database restoration will <strong>completely replace</strong> your current database with the backup data. 
                This action cannot be undone. We strongly recommend creating a backup of your current database before proceeding.
            </p>
        </div>

        <div class="row">
            <!-- Current Database Information -->
            <div class="col-lg-4 col-12 mb-4">
                <div class="card">
                    <div class="card-header">
                        <h5 class="card-title">📊 Current Database</h5>
                    </div>
                    <div class="card-body">
                        <div class="database-info">
                            <div class="info-row">
                                <span class="label">Database Name:</span>
                                <span class="value"><?php echo htmlspecialchars($db_name); ?></span>
                            </div>
                            <div class="info-row">
                                <span class="label">Tables:</span>
                                <span class="value"><?php echo number_format($dbInfo['tables']); ?></span>
                            </div>
                            <div class="info-row">
                                <span class="label">Total Records:</span>
                                <span class="value"><?php echo number_format($dbInfo['total_records']); ?></span>
                            </div>
                            <div class="info-row">
                                <span class="label">Database Size:</span>
                                <span class="value"><?php echo $dbInfo['database_size']; ?></span>
                            </div>
                            <div class="info-row">
                                <span class="label">Last Updated:</span>
                                <span class="value"><?php echo date('Y-m-d H:i:s'); ?></span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Restore from Available Backups -->
            <div class="col-lg-8 col-12 mb-4">
                <div class="card">
                    <div class="card-header">
                        <h5 class="card-title">📁 Restore from Available Backups</h5>
                    </div>
                    <div class="card-body">
                        <?php if (empty($backups)): ?>
                        <div class="text-center text-muted">
                            <i data-feather="archive" class="feather-48 mb-3"></i>
                            <h6>No Backups Available</h6>
                            <p>Create a backup first before you can restore from one.</p>
                            <a href="backup_engine.php?action=run_now&type=manual" class="btn btn-primary"
                               onclick="return confirm('Create a backup now?')">
                                <i data-feather="save" class="feather-16"></i> Create Backup Now
                            </a>
                        </div>
                        <?php else: ?>
                        <form method="POST" id="restore-form">
                            <div class="form-group">
                                <label for="backup_file">Select Backup to Restore:</label>
                                <select class="form-control" name="backup_file" id="backup_file" required>
                                    <option value="">-- Select a backup file --</option>
                                    <?php foreach ($backups as $backup): ?>
                                    <option value="<?php echo htmlspecialchars($backup['filename']); ?>"
                                            data-size="<?php echo htmlspecialchars($backup['size']); ?>"
                                            data-created="<?php echo htmlspecialchars($backup['created']); ?>"
                                            data-type="<?php echo htmlspecialchars($backup['type']); ?>">
                                        <?php echo htmlspecialchars($backup['filename']); ?> 
                                        (<?php echo $backup['size']; ?>, <?php echo $backup['created']; ?>)
                                    </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div id="backup-details" class="mt-3" style="display: none;">
                                <div class="card bg-light">
                                    <div class="card-body">
                                        <h6>Backup Details:</h6>
                                        <div class="row">
                                            <div class="col-sm-6">
                                                <strong>Type:</strong> <span id="detail-type"></span>
                                            </div>
                                            <div class="col-sm-6">
                                                <strong>Size:</strong> <span id="detail-size"></span>
                                            </div>
                                            <div class="col-sm-6">
                                                <strong>Created:</strong> <span id="detail-created"></span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="form-group mt-3">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="create_backup_before_restore" 
                                           id="create_backup_before_restore" checked>
                                    <label class="form-check-label" for="create_backup_before_restore">
                                        <strong>Create a backup of current database before restoring</strong>
                                        <small class="text-muted d-block">Recommended - allows you to undo this restoration</small>
                                    </label>
                                </div>
                            </div>

                            <div class="form-group mt-3">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="confirm_restore" 
                                           id="confirm_restore" required>
                                    <label class="form-check-label" for="confirm_restore">
                                        <strong>I understand this will replace my current database</strong>
                                        <small class="text-danger d-block">This action cannot be undone without a backup</small>
                                    </label>
                                </div>
                            </div>

                            <div class="form-group mt-4">
                                <button type="submit" name="restore_backup" class="btn btn-danger btn-lg" id="restore-btn" disabled>
                                    <i data-feather="upload" class="feather-16"></i> Restore Database
                                </button>
                                <a href="backup_management.php" class="btn btn-secondary btn-lg ms-2">
                                    <i data-feather="x" class="feather-16"></i> Cancel
                                </a>
                            </div>
                        </form>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Upload External Backup -->
        <div class="row">
            <div class="col-lg-12">
                <div class="card">
                    <div class="card-header">
                        <h5 class="card-title">📤 Upload External Backup</h5>
                    </div>
                    <div class="card-body">
                        <p class="text-muted">
                            If you have a backup file from another source, you can upload it here and then restore from it.
                        </p>
                        
                        <form method="POST" enctype="multipart/form-data" id="upload-form">
                            <div class="row">
                                <div class="col-lg-8">
                                    <div class="form-group">
                                        <label for="upload_backup">Select Backup File (.sql or .sql.gz):</label>
                                        <input type="file" class="form-control" name="upload_backup" id="upload_backup" 
                                               accept=".sql,.gz" required>
                                        <small class="text-muted">
                                            Supported formats: .sql (uncompressed) or .sql.gz (compressed)
                                        </small>
                                    </div>
                                </div>
                                <div class="col-lg-4">
                                    <div class="form-group">
                                        <label>&nbsp;</label>
                                        <button type="submit" class="btn btn-primary form-control">
                                            <i data-feather="upload" class="feather-16"></i> Upload Backup
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <!-- Restoration Process Information -->
        <div class="row">
            <div class="col-lg-12">
                <div class="card">
                    <div class="card-header">
                        <h5 class="card-title">ℹ️ Restoration Process</h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-lg-6">
                                <h6>What happens during restoration:</h6>
                                <ol class="process-list">
                                    <li>Current database is optionally backed up (if selected)</li>
                                    <li>Selected backup file is validated</li>
                                    <li>Database tables are dropped and recreated</li>
                                    <li>Data is imported from the backup file</li>
                                    <li>Process completion is logged</li>
                                </ol>
                            </div>
                            <div class="col-lg-6">
                                <h6>Important notes:</h6>
                                <ul class="notes-list">
                                    <li><strong>Downtime:</strong> Your application will be temporarily unavailable</li>
                                    <li><strong>Active sessions:</strong> All user sessions will be lost</li>
                                    <li><strong>File size:</strong> Large backups may take several minutes</li>
                                    <li><strong>Verification:</strong> Test restored data before resuming operations</li>
                                    <li><strong>Permissions:</strong> Ensure database user has restoration privileges</li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Restore Confirmation Modal -->
<div class="modal fade" id="restoreModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">⚠️ Confirm Database Restoration</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="alert alert-danger">
                    <strong>WARNING:</strong> This action will completely replace your current database!
                </div>
                <p>You are about to restore from backup: <strong id="modal-backup-file"></strong></p>
                <p>Are you absolutely sure you want to proceed?</p>
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" id="final-confirm">
                    <label class="form-check-label" for="final-confirm">
                        Yes, I want to replace my current database
                    </label>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-danger" id="final-restore-btn" disabled>
                    Restore Database
                </button>
            </div>
        </div>
    </div>
</div>

<style>
.database-info .info-row {
    display: flex;
    justify-content: space-between;
    padding: 8px 0;
    border-bottom: 1px solid #eee;
}

.database-info .info-row:last-child {
    border-bottom: none;
}

.database-info .label {
    font-weight: 600;
    color: #666;
}

.database-info .value {
    font-family: monospace;
    color: #333;
}

.process-list, .notes-list {
    padding-left: 20px;
}

.process-list li, .notes-list li {
    margin-bottom: 8px;
}

.notes-list li strong {
    color: #dc3545;
}

#backup-details {
    transition: all 0.3s ease;
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const backupSelect = document.getElementById('backup_file');
    const backupDetails = document.getElementById('backup-details');
    const confirmCheckbox = document.getElementById('confirm_restore');
    const restoreBtn = document.getElementById('restore-btn');
    const restoreForm = document.getElementById('restore-form');
    
    // Handle backup selection
    backupSelect.addEventListener('change', function() {
        const selectedOption = this.options[this.selectedIndex];
        
        if (this.value) {
            // Show backup details
            document.getElementById('detail-type').textContent = selectedOption.dataset.type;
            document.getElementById('detail-size').textContent = selectedOption.dataset.size;
            document.getElementById('detail-created').textContent = selectedOption.dataset.created;
            backupDetails.style.display = 'block';
        } else {
            backupDetails.style.display = 'none';
        }
        
        updateRestoreButton();
    });
    
    // Handle confirmation checkbox
    confirmCheckbox.addEventListener('change', updateRestoreButton);
    
    function updateRestoreButton() {
        const backupSelected = backupSelect.value !== '';
        const confirmed = confirmCheckbox.checked;
        restoreBtn.disabled = !(backupSelected && confirmed);
    }
    
    // Handle form submission with additional confirmation
    restoreForm.addEventListener('submit', function(e) {
        e.preventDefault();
        
        const selectedBackup = backupSelect.options[backupSelect.selectedIndex].text;
        document.getElementById('modal-backup-file').textContent = selectedBackup;
        
        const modal = new bootstrap.Modal(document.getElementById('restoreModal'));
        modal.show();
    });
    
    // Handle final confirmation
    const finalConfirm = document.getElementById('final-confirm');
    const finalRestoreBtn = document.getElementById('final-restore-btn');
    
    finalConfirm.addEventListener('change', function() {
        finalRestoreBtn.disabled = !this.checked;
    });
    
    finalRestoreBtn.addEventListener('click', function() {
        // Show loading state
        this.disabled = true;
        this.innerHTML = '<span class="spinner-border spinner-border-sm" role="status"></span> Restoring...';
        
        // Submit the form
        restoreForm.submit();
    });
    
    // File upload validation
    document.getElementById('upload_backup').addEventListener('change', function() {
        const file = this.files[0];
        if (file) {
            const validExtensions = ['.sql', '.gz'];
            const fileName = file.name.toLowerCase();
            const isValid = validExtensions.some(ext => fileName.endsWith(ext));
            
            if (!isValid) {
                alert('Please select a valid backup file (.sql or .sql.gz)');
                this.value = '';
            }
        }
    });
});
</script>
