<?php
/**
 * Login Attempts Viewer
 * View and manage login attempts and security logs
 */

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

// Get filter parameters
$filter_status = $_GET['status'] ?? '';
$filter_username = $_GET['username'] ?? '';
$filter_ip = $_GET['ip'] ?? '';
$filter_date_from = $_GET['date_from'] ?? '';
$filter_date_to = $_GET['date_to'] ?? '';

// Build query
$where = [];
$params = [];

if ($filter_status) {
    $where[] = "attempt_status = ?";
    $params[] = $filter_status;
}
if ($filter_username) {
    $where[] = "(username LIKE ? OR username = ?)";
    $params[] = "%$filter_username%";
    $params[] = $filter_username;
}
if ($filter_ip) {
    $where[] = "ip_address LIKE ?";
    $params[] = "%$filter_ip%";
}
if ($filter_date_from) {
    $where[] = "created_at >= ?";
    $params[] = $filter_date_from . ' 00:00:00';
}
if ($filter_date_to) {
    $where[] = "created_at <= ?";
    $params[] = $filter_date_to . ' 23:59:59';
}

$whereClause = count($where) > 0 ? 'WHERE ' . implode(' AND ', $where) : '';

// Get paginated login attempts
$page = intval($_GET['page'] ?? 1);
if ($page < 1) $page = 1;
$per_page = 50;
$offset = ($page - 1) * $per_page;

try {
    $count_stmt = $pdo->prepare("SELECT COUNT(*) FROM login_attempts $whereClause");
    $count_stmt->execute($params);
    $total_records = $count_stmt->fetchColumn();
    $total_pages = ceil($total_records / $per_page);

    // Use string interpolation for LIMIT clause (some MySQL versions don't support binding for LIMIT)
    $sql = "
        SELECT *
        FROM login_attempts
        $whereClause
        ORDER BY created_at DESC
        LIMIT $offset, $per_page
    ";
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $attempts = $stmt->fetchAll();
} catch (PDOException $e) {
    error_log("Login attempts query error: " . $e->getMessage());
    die("Database error occurred while fetching login attempts. Error: " . $e->getMessage());
}

// Get statistics
try {
    $stats_stmt = $pdo->prepare("
        SELECT 
            COUNT(*) as total_attempts,
            COUNT(CASE WHEN attempt_status = 'success' THEN 1 END) as successful,
            COUNT(CASE WHEN attempt_status = 'failed' THEN 1 END) as failed,
            COUNT(DISTINCT ip_address) as unique_ips,
            COUNT(DISTINCT username) as unique_users,
            COUNT(CASE WHEN created_at >= DATE_SUB(CURDATE(), INTERVAL 24 HOUR) THEN 1 END) as last_24_hours
        FROM login_attempts
    ");
    $stats_stmt->execute();
    $stats = $stats_stmt->fetch();
} catch (PDOException $e) {
    error_log("Login stats query error: " . $e->getMessage());
    $stats = [
        'total_attempts' => 0,
        'successful' => 0,
        'failed' => 0,
        'unique_ips' => 0,
        'unique_users' => 0,
        'last_24_hours' => 0
    ];
}

// Get top failed IPs (potential attackers)
try {
    $suspicious_ips_stmt = $pdo->prepare("
        SELECT 
            ip_address,
            COUNT(*) as attempt_count,
            COUNT(CASE WHEN attempt_status = 'failed' THEN 1 END) as failed_count,
            MAX(created_at) as last_attempt,
            GROUP_CONCAT(DISTINCT username SEPARATOR ', ') as attempted_users
        FROM login_attempts
        WHERE created_at >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)
        GROUP BY ip_address
        HAVING failed_count >= 5
        ORDER BY failed_count DESC
        LIMIT 10
    ");
    $suspicious_ips_stmt->execute();
    $suspicious_ips = $suspicious_ips_stmt->fetchAll();
} catch (PDOException $e) {
    error_log("Suspicious IPs query error: " . $e->getMessage());
    $suspicious_ips = [];
}

// Get top usernames with failed attempts
try {
    $problematic_users_stmt = $pdo->prepare("
        SELECT 
            username,
            COUNT(*) as total_attempts,
            COUNT(CASE WHEN attempt_status = 'failed' THEN 1 END) as failed_count,
            COUNT(CASE WHEN attempt_status = 'success' THEN 1 END) as success_count,
            MAX(created_at) as last_attempt
        FROM login_attempts
        WHERE username IS NOT NULL AND username != ''
            AND created_at >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)
        GROUP BY username
        HAVING failed_count >= 3
        ORDER BY failed_count DESC
        LIMIT 10
    ");
    $problematic_users_stmt->execute();
    $problematic_users = $problematic_users_stmt->fetchAll();
} catch (PDOException $e) {
    error_log("Problematic users query error: " . $e->getMessage());
    $problematic_users = [];
}
?>
<!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">
    <style>
        .suspicious-ip { background-color: #fff3cd; }
        .failed-attempt { background-color: #f8d7da; }
        .success-attempt { background-color: #d1e7dd; }
    </style>
    <link href="../assets/css/style.css" rel="stylesheet">
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">🛡️ লগইন প্রচেষ্টা এবং নিরাপত্তা লগ</h1>
                    <div>
                        <a href="index.php" class="btn btn-outline-primary">
                            <i class="fas fa-arrow-left"></i> অডিট ট্রেইলে ফিরুন
                        </a>
                    </div>
                </div>
                
                <!-- Statistics Cards -->
                <div class="row mb-4">
                    <div class="col-md-2">
                        <div class="card bg-primary text-white text-center">
                            <div class="card-body">
                                <h4><?= number_format($stats['total_attempts']) ?></h4>
                                <small>মোট প্রচেষ্টা</small>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-2">
                        <div class="card bg-success text-white text-center">
                            <div class="card-body">
                                <h4><?= number_format($stats['successful']) ?></h4>
                                <small>সফল</small>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-2">
                        <div class="card bg-danger text-white text-center">
                            <div class="card-body">
                                <h4><?= number_format($stats['failed']) ?></h4>
                                <small>ব্যর্থ</small>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-2">
                        <div class="card bg-warning text-dark text-center">
                            <div class="card-body">
                                <h4><?= number_format($stats['unique_ips']) ?></h4>
                                <small>অনন্য IP</small>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-2">
                        <div class="card bg-info text-white text-center">
                            <div class="card-body">
                                <h4><?= number_format($stats['unique_users']) ?></h4>
                                <small>অনন্য ব্যবহারকারী</small>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-2">
                        <div class="card bg-secondary text-white text-center">
                            <div class="card-body">
                                <h4><?= number_format($stats['last_24_hours']) ?></h4>
                                <small>গত ২৪ ঘন্টা</small>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="row">
                    <!-- Suspicious IPs -->
                    <div class="col-md-6">
                        <div class="card mb-4">
                            <div class="card-header bg-warning">
                                <h5 class="mb-0"><i class="fas fa-exclamation-triangle"></i> সন্দেহজনক IP ঠিকানা (গত ৭ দিন)</h5>
                            </div>
                            <div class="card-body p-0">
                                <div class="table-responsive">
                                    <table class="table table-sm table-hover mb-0">
                                        <thead>
                                            <tr>
                                                <th>IP ঠিকানা</th>
                                                <th class="text-center">ব্যর্থ প্রচেষ্টা</th>
                                                <th>শেষ প্রচেষ্টা</th>
                                                <th>ব্যবহারকারী</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php if (count($suspicious_ips) > 0): ?>
                                                <?php foreach ($suspicious_ips as $ip): ?>
                                                <tr>
                                                    <td><code><?= htmlspecialchars($ip['ip_address']) ?></code></td>
                                                    <td class="text-center">
                                                        <span class="badge bg-danger"><?= $ip['failed_count'] ?></span>
                                                    </td>
                                                    <td><?= date('d M H:i', strtotime($ip['last_attempt'])) ?></td>
                                                    <td><small><?= htmlspecialchars(substr($ip['attempted_users'], 0, 50)) ?><?= strlen($ip['attempted_users']) > 50 ? '...' : '' ?></small></td>
                                                </tr>
                                                <?php endforeach; ?>
                                            <?php else: ?>
                                                <tr>
                                                    <td colspan="4" class="text-center text-muted">কোনো সন্দেহজনক IP পাওয়া যায়নি</td>
                                                </tr>
                                            <?php endif; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Problematic Users -->
                    <div class="col-md-6">
                        <div class="card mb-4">
                            <div class="card-header bg-danger text-white">
                                <h5 class="mb-0"><i class="fas fa-user-times"></i> সমস্যাসঙ্কুল ব্যবহারকারী (গত ৭ দিন)</h5>
                            </div>
                            <div class="card-body p-0">
                                <div class="table-responsive">
                                    <table class="table table-sm table-hover mb-0">
                                        <thead>
                                            <tr>
                                                <th>ব্যবহারকারী</th>
                                                <th class="text-center">ব্যর্থ</th>
                                                <th class="text-center">সফল</th>
                                                <th>শেষ প্রচেষ্টা</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php if (count($problematic_users) > 0): ?>
                                                <?php foreach ($problematic_users as $user): ?>
                                                <tr>
                                                    <td><strong><?= htmlspecialchars($user['username']) ?></strong></td>
                                                    <td class="text-center">
                                                        <span class="badge bg-danger"><?= $user['failed_count'] ?></span>
                                                    </td>
                                                    <td class="text-center">
                                                        <span class="badge bg-success"><?= $user['success_count'] ?></span>
                                                    </td>
                                                    <td><?= date('d M H:i', strtotime($user['last_attempt'])) ?></td>
                                                </tr>
                                                <?php endforeach; ?>
                                            <?php else: ?>
                                                <tr>
                                                    <td colspan="4" class="text-center text-muted">কোনো সমস্যাসঙ্কুল ব্যবহারকারী পাওয়া যায়নি</td>
                                                </tr>
                                            <?php endif; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Filters -->
                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="mb-0"><i class="fas fa-filter"></i> ফিল্টার</h5>
                    </div>
                    <div class="card-body">
                        <form method="GET" class="row">
                            <div class="col-md-2 mb-3">
                                <label class="form-label">স্ট্যাটাস</label>
                                <select name="status" class="form-select">
                                    <option value="">সব</option>
                                    <option value="success" <?= $filter_status == 'success' ? 'selected' : '' ?>>সফল</option>
                                    <option value="failed" <?= $filter_status == 'failed' ? 'selected' : '' ?>>ব্যর্থ</option>
                                </select>
                            </div>
                            <div class="col-md-3 mb-3">
                                <label class="form-label">ব্যবহারকারী</label>
                                <input type="text" name="username" class="form-control" value="<?= htmlspecialchars($filter_username) ?>" placeholder="ব্যবহারকারীর নাম">
                            </div>
                            <div class="col-md-3 mb-3">
                                <label class="form-label">IP ঠিকানা</label>
                                <input type="text" name="ip" class="form-control" value="<?= htmlspecialchars($filter_ip) ?>" placeholder="IP ঠিকানা">
                            </div>
                            <div class="col-md-2 mb-3">
                                <label class="form-label">তারিখ থেকে</label>
                                <input type="date" name="date_from" class="form-control" value="<?= $filter_date_from ?>">
                            </div>
                            <div class="col-md-2 mb-3">
                                <label class="form-label">তারিখ পর্যন্ত</label>
                                <input type="date" name="date_to" class="form-control" value="<?= $filter_date_to ?>">
                            </div>
                            <div class="col-md-12">
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-search"></i> ফিল্টার করুন
                                </button>
                                <a href="login_attempts.php" class="btn btn-secondary">
                                    <i class="fas fa-undo"></i> রিসেট
                                </a>
                            </div>
                        </form>
                    </div>
                </div>
                
                <!-- Login Attempts Table -->
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5 class="mb-0">📋 লগইন প্রচেষ্টা লগ</h5>
                        <small class="text-muted">পেজ <?= $page ?> এর <?= $total_pages ?> (মোট <?= $total_records ?> রেকর্ড)</small>
                    </div>
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table table-striped table-hover mb-0">
                                <thead class="table-dark">
                                    <tr>
                                        <th>সময়</th>
                                        <th>ব্যবহারকারী</th>
                                        <th>IP ঠিকানা</th>
                                        <th>স্ট্যাটাস</th>
                                        <th>ব্যর্থতার কারণ</th>
                                        <th>ব্রাউজার</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($attempts as $attempt): ?>
                                    <tr class="<?= $attempt['attempt_status'] == 'failed' ? 'failed-attempt' : 'success-attempt' ?>">
                                        <td nowrap>
                                            <?= date('d M Y', strtotime($attempt['created_at'])) ?><br>
                                            <small class="text-muted"><?= date('h:i:s A', strtotime($attempt['created_at'])) ?></small>
                                        </td>
                                        <td>
                                            <strong><?= htmlspecialchars($attempt['username'] ?? 'N/A') ?></strong>
                                        </td>
                                        <td>
                                            <code><?= htmlspecialchars($attempt['ip_address']) ?></code>
                                        </td>
                                        <td>
                                            <?php if ($attempt['attempt_status'] == 'success'): ?>
                                                <span class="badge bg-success"><i class="fas fa-check"></i> সফল</span>
                                            <?php else: ?>
                                                <span class="badge bg-danger"><i class="fas fa-times"></i> ব্যর্থ</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?php if ($attempt['failure_reason']): ?>
                                                <small class="text-danger"><?= htmlspecialchars($attempt['failure_reason']) ?></small>
                                            <?php else: ?>
                                                <span class="text-muted">-</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <small class="text-muted" title="<?= htmlspecialchars($attempt['user_agent'] ?? 'Unknown') ?>">
                                                <?= htmlspecialchars(substr($attempt['user_agent'] ?? 'Unknown', 0, 50)) ?><?= strlen($attempt['user_agent'] ?? '') > 50 ? '...' : '' ?>
                                            </small>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                    
                                    <?php if (count($attempts) === 0): ?>
                                    <tr>
                                        <td colspan="6" class="text-center py-4 text-muted">
                                            <i class="fas fa-inbox fa-2x mb-2"></i><br>
                                            কোনো লগইন প্রচেষ্টা পাওয়া যায়নি
                                        </td>
                                    </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                    
                    <!-- Pagination -->
                    <?php if ($total_pages > 1): ?>
                    <div class="card-footer">
                        <nav>
                            <ul class="pagination justify-content-center mb-0">
                                <li class="page-item <?= $page <= 1 ? 'disabled' : '' ?>">
                                    <a class="page-link" href="?page=<?= $page-1 ?>&<?= http_build_query(array_diff_key($_GET, ['page' => ''])) ?>">পূর্ববর্তী</a>
                                </li>
                                <?php for ($i = max(1, $page-2); $i <= min($total_pages, $page+2); $i++): ?>
                                <li class="page-item <?= $i == $page ? 'active' : '' ?>">
                                    <a class="page-link" href="?page=<?= $i ?>&<?= http_build_query(array_diff_key($_GET, ['page' => ''])) ?>"><?= $i ?></a>
                                </li>
                                <?php endfor; ?>
                                <li class="page-item <?= $page >= $total_pages ? 'disabled' : '' ?>">
                                    <a class="page-link" href="?page=<?= $page+1 ?>&<?= http_build_query(array_diff_key($_GET, ['page' => ''])) ?>">পরবর্তী</a>
                                </li>
                            </ul>
                        </nav>
                    </div>
                    <?php endif; ?>
                </div>
                
            </main>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
