<?php
/**
 * Archive Old Login Attempts
 * Moves login attempts older than 30 days to archive table
 */

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

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

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

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

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

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

try {
    // Check if archive table exists, if not create it
    $check_table = $pdo->query("SHOW TABLES LIKE 'login_attempts_archive'");
    if ($check_table->rowCount() == 0) {
        $pdo->exec("
            CREATE TABLE IF NOT EXISTS login_attempts_archive (
                id BIGINT PRIMARY KEY,
                username VARCHAR(50),
                ip_address VARCHAR(45) NOT NULL,
                user_agent VARCHAR(255),
                attempt_status ENUM('success', 'failed') NOT NULL,
                failure_reason VARCHAR(255),
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                archived_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                INDEX idx_created_at (created_at),
                INDEX idx_archived_at (archived_at)
            )
        ");
    }
    
    // Get retention days (default 30 days)
    $retention_days = 30;
    $cutoff_date = date('Y-m-d H:i:s', strtotime("-{$retention_days} days"));
    
    // Start transaction
    $pdo->beginTransaction();
    
    // Get old login attempts
    $old_attempts_stmt = $pdo->prepare("
        SELECT * FROM login_attempts 
        WHERE created_at < ? 
        ORDER BY created_at ASC
    ");
    $old_attempts_stmt->execute([$cutoff_date]);
    $old_attempts = $old_attempts_stmt->fetchAll();
    
    $archived_count = 0;
    
    foreach ($old_attempts as $attempt) {
        // Insert into archive
        $archive_stmt = $pdo->prepare("
            INSERT INTO login_attempts_archive 
            (id, username, ip_address, user_agent, attempt_status, failure_reason, created_at, archived_at)
            VALUES (?, ?, ?, ?, ?, ?, ?, NOW())
        ");
        $archive_stmt->execute([
            $attempt['id'],
            $attempt['username'],
            $attempt['ip_address'],
            $attempt['user_agent'],
            $attempt['attempt_status'],
            $attempt['failure_reason'],
            $attempt['created_at']
        ]);
        
        // Delete from main table
        $delete_stmt = $pdo->prepare("DELETE FROM login_attempts WHERE id = ?");
        $delete_stmt->execute([$attempt['id']]);
        
        $archived_count++;
    }
    
    // Commit transaction
    $pdo->commit();
    
    // Log the archive action
    try {
        $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', 'login_attempts', NULL, ?, ?, ?, NOW())
        ");
        $log_stmt->execute([
            $_SESSION['user_id'],
            $user_role,
            $_SERVER['REMOTE_ADDR'] ?? 'unknown',
            $_SERVER['HTTP_USER_AGENT'] ?? 'unknown',
            json_encode([
                'archived_count' => $archived_count,
                'retention_days' => $retention_days,
                'cutoff_date' => $cutoff_date
            ])
        ]);
    } catch (Exception $e) {
        // Ignore audit log errors
        error_log("Failed to log archive action: " . $e->getMessage());
    }
    
    $response['success'] = true;
    $response['message'] = "✅ {$archived_count}টি পুরানো লগইন প্রচেষ্টা আর্কাইভ করা হয়েছে।";
    $response['archived_count'] = $archived_count;
    
} catch (Exception $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    
    $response['success'] = false;
    $response['message'] = '❌ আর্কাইভ ত্রুটি: ' . $e->getMessage();
    
    // Log error
    error_log('Login attempts archive error: ' . $e->getMessage());
}

// 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 {
    // Show result page
    ?>
    <!DOCTYPE html>
    <html lang="bn">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>লগইন প্রচেষ্টা আর্কাইভ - <?= APP_NAME ?></title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    </head>
    <body class="bg-light">
        <div class="container mt-5">
            <div class="row justify-content-center">
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-body text-center">
                            <?php if ($response['success']): ?>
                                <i class="fas fa-check-circle text-success fa-4x mb-3"></i>
                                <h3 class="text-success">আর্কাইভ সম্পন্ন!</h3>
                                <p class="lead"><?= $response['message'] ?></p>
                                <a href="login_attempts.php" class="btn btn-primary">
                                    <i class="fas fa-arrow-left"></i> লগইন প্রচেষ্টায় ফিরুন
                                </a>
                                <a href="login_attempts_archive.php" class="btn btn-secondary ms-2">
                                    <i class="fas fa-archive"></i> আর্কাইভ দেখুন
                                </a>
                            <?php else: ?>
                                <i class="fas fa-times-circle text-danger fa-4x mb-3"></i>
                                <h3 class="text-danger">ত্রুটি!</h3>
                                <p class="lead"><?= $response['message'] ?></p>
                                <a href="login_attempts.php" class="btn btn-primary">
                                    <i class="fas fa-arrow-left"></i> ফিরে যান
                                </a>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </body>
    </html>
    <?php
}

exit;
