<?php
/**
 * Archive Old Backup Logs
 * Archives backup history records older than retention period
 */

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/SecurityHelper.php';

// Check authentication - redirect to login if not logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: ../login.php');
    exit;
}

// Check admin role
if (!isset($_SESSION['user_role']) || $_SESSION['user_role'] !== 'admin') {
    http_response_code(403);
    die('❌ অ্যাক্সেস denied। আপনার এই পেজ দেখার অনুমতি নেই।<br><br>
    <a href="../login.php" class="btn btn-primary">লগইন পেজে যান</a>');
}

$response = [
    'success' => false,
    'message' => '',
    'archived_count' => 0,
    'deleted_count' => 0
];

try {
    // Get retention days from config (default 30 days)
    $config_stmt = $pdo->query("SELECT retention_days FROM backup_config WHERE is_active = TRUE LIMIT 1");
    $config = $config_stmt->fetch();
    $retention_days = $config['retention_days'] ?? 30;
    
    $cutoff_date = date('Y-m-d H:i:s', strtotime("-{$retention_days} days"));
    
    // Start transaction
    $pdo->beginTransaction();
    
    // Get old backup records
    $old_backups_stmt = $pdo->prepare("
        SELECT * FROM backup_history 
        WHERE start_time < ? 
        AND is_deleted = FALSE
        AND status = 'completed'
        ORDER BY start_time ASC
    ");
    $old_backups_stmt->execute([$cutoff_date]);
    $old_backups = $old_backups_stmt->fetchAll();
    
    $archived_count = 0;
    $deleted_count = 0;
    $archive_dir = __DIR__ . '/../backups/archive/';
    
    // Create archive directory if not exists
    if (!is_dir($archive_dir)) {
        mkdir($archive_dir, 0755, true);
    }
    
    foreach ($old_backups as $backup) {
        // Move physical file to archive
        if (file_exists($backup['file_path'])) {
            $archive_path = $archive_dir . $backup['file_name'];
            
            // If file already exists in archive, delete the old one
            if (file_exists($archive_path)) {
                unlink($backup['file_path']);
            } else {
                rename($backup['file_path'], $archive_path);
            }
        }
        
        // Update record as archived (soft delete)
        $archive_stmt = $pdo->prepare("
            UPDATE backup_history 
            SET is_deleted = TRUE 
            WHERE id = ?
        ");
        $archive_stmt->execute([$backup['id']]);
        
        $archived_count++;
    }
    
    // Delete orphaned backup files that have no database record
    $backup_dir = __DIR__ . '/../backups/';
    $orphaned_files = [];
    
    if (is_dir($backup_dir)) {
        $files = glob($backup_dir . '*.{zip,sql,gz,tar}', GLOB_BRACE);
        foreach ($files as $file) {
            $file_name = basename($file);
            $file_mtime = filemtime($file);
            
            // Check if file is older than retention period
            if ($file_mtime < strtotime($cutoff_date)) {
                // Check if this file is in the database
                $check_stmt = $pdo->prepare("SELECT COUNT(*) FROM backup_history WHERE file_name = ?");
                $check_stmt->execute([$file_name]);
                $exists = $check_stmt->fetchColumn() > 0;
                
                if (!$exists) {
                    // Delete orphaned file
                    unlink($file);
                    $deleted_count++;
                }
            }
        }
    }
    
    // Commit transaction
    $pdo->commit();
    
    // Log the archive action
    $log_stmt = $pdo->prepare("
        INSERT INTO audit_log (user_id, user_role, action, table_name, record_id, ip_address, user_agent, new_values, created_at)
        VALUES (?, ?, 'ARCHIVE', 'backup_history', NULL, ?, ?, ?, NOW())
    ");
    $log_stmt->execute([
        $_SESSION['user_id'],
        $_SESSION['user_role'],
        $_SERVER['REMOTE_ADDR'] ?? 'unknown',
        $_SERVER['HTTP_USER_AGENT'] ?? 'unknown',
        json_encode([
            'archived_count' => $archived_count,
            'deleted_count' => $deleted_count,
            'retention_days' => $retention_days,
            'cutoff_date' => $cutoff_date
        ])
    ]);
    
    $response['success'] = true;
    $response['message'] = "✅ {$archived_count}টি ব্যাকআপ আর্কাইভ করা হয়েছে এবং {$deleted_count}টি অর্ফান ফাইল মুছে ফেলা হয়েছে।";
    $response['archived_count'] = $archived_count;
    $response['deleted_count'] = $deleted_count;
    
} catch (Exception $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    
    $response['success'] = false;
    $response['message'] = '❌ আর্কাইভ ত্রুটি: ' . $e->getMessage();
    
    // Log error
    SecurityHelper::logEvent('BACKUP_ARCHIVE_ERROR', [
        'error' => $e->getMessage(),
        'user_id' => $_SESSION['user_id'] ?? null
    ]);
}

// Check if request is AJAX or regular request
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
    header('Content-Type: application/json');
    echo json_encode($response);
} else {
    // Redirect back with message
    $redirect_url = 'index.php?' . http_build_query([
        'success' => $response['success'] ? 1 : 0,
        'message' => urlencode($response['message'])
    ]);
    header('Location: ' . $redirect_url);
}

exit;
