<?php
// admin/login.php - Me masa sigurie kundër hacking
require_once '../includes/config.php';

// ============================================
// MASAT E SIGURISE
// ============================================

// 1. Rate Limiting - Kufizimi i tentativave të dështuara
session_start();

// Max 5 tentativa të dështuara për 15 minuta
$max_attempts = 5;
$lockout_time = 15 * 60; // 15 minuta në sekonda

// Pastro tentativat e vjetra (> 1 orë)
if(isset($_SESSION['login_attempts']) && is_array($_SESSION['login_attempts'])) {
    $_SESSION['login_attempts'] = array_filter($_SESSION['login_attempts'], function($timestamp) {
        return (time() - $timestamp) < 3600; // 1 orë
    });
}

// Kontrollo nëse IP-ja është e bllokuar
$ip = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
$attempts = isset($_SESSION['login_attempts']) ? count($_SESSION['login_attempts']) : 0;

if($attempts >= $max_attempts) {
    $oldest = min($_SESSION['login_attempts']);
    $time_left = $lockout_time - (time() - $oldest);
    if($time_left > 0) {
        $error = "Too many failed attempts. Please try again in " . ceil($time_left / 60) . " minutes.";
        $show_form = false;
    } else {
        // Reset attempts if lockout time has passed
        $_SESSION['login_attempts'] = [];
        $show_form = true;
    }
} else {
    $show_form = true;
}

$error = '';
$success = false;

// Get site settings for logo
$logo_url = getSetting('logo_url', $pdo, '');
$site_name = getSetting('site_name', $pdo, 'Car Rental Albania');

// ============================================
// HANDLE LOGIN
// ============================================
if($_SERVER['REQUEST_METHOD'] == 'POST' && $show_form) {
    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';
    
    // 2. Validimi i inputeve - parandalon SQL Injection
    if(empty($username) || empty($password)) {
        $error = "Please enter both username and password.";
        // Regjistro tentativën e dështuar
        $_SESSION['login_attempts'][] = time();
    } else {
        // 3. Përdor prepared statements - mbrojtje nga SQL Injection
        try {
            // Kontrollo nëse tabela admin_users ekziston
            try {
                $stmt = $pdo->prepare("SELECT * FROM admin_users WHERE username = ? AND is_active = 1");
                $stmt->execute([$username]);
                $admin = $stmt->fetch(PDO::FETCH_ASSOC);
            } catch(PDOException $e) {
                // Table might not exist yet - create it
                $pdo->query("
                    CREATE TABLE IF NOT EXISTS `admin_users` (
                        `id` int(11) NOT NULL AUTO_INCREMENT,
                        `username` varchar(50) NOT NULL,
                        `password` varchar(255) NOT NULL,
                        `email` varchar(100) DEFAULT NULL,
                        `full_name` varchar(100) DEFAULT NULL,
                        `role` enum('super_admin','admin','viewer') DEFAULT 'admin',
                        `is_active` tinyint(4) DEFAULT 1,
                        `created_at` timestamp NULL DEFAULT current_timestamp(),
                        `last_login` timestamp NULL DEFAULT NULL,
                        PRIMARY KEY (`id`),
                        UNIQUE KEY `username` (`username`)
                    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
                ");
                
                // Check if any admin exists
                $check = $pdo->query("SELECT COUNT(*) FROM admin_users")->fetchColumn();
                if($check == 0) {
                    $default_password = password_hash('admin123', PASSWORD_DEFAULT);
                    $pdo->query("
                        INSERT INTO admin_users (username, password, full_name, role, is_active) 
                        VALUES ('admin', '$default_password', 'Super Admin', 'super_admin', 1)
                    ");
                }
                
                // Try again
                $stmt = $pdo->prepare("SELECT * FROM admin_users WHERE username = ? AND is_active = 1");
                $stmt->execute([$username]);
                $admin = $stmt->fetch(PDO::FETCH_ASSOC);
            }
            
            // 4. Përdor password_verify() - mbrojtje nga hash krahason
            if($admin && password_verify($password, $admin['password'])) {
                // Login i suksesshëm - pastro tentativat
                $_SESSION['login_attempts'] = [];
                
                // Rregjistro session-in
                $_SESSION['admin_logged_in'] = true;
                $_SESSION['admin_username'] = $admin['username'];
                $_SESSION['admin_role'] = $admin['role'] ?? 'admin';
                $_SESSION['admin_id'] = $admin['id'];
                $_SESSION['admin_login_time'] = time();
                $_SESSION['admin_ip'] = $ip;
                
                // 5. Regjistro hyrjen në log (optional)
                try {
                    $pdo->prepare("UPDATE admin_users SET last_login = NOW() WHERE id = ?")->execute([$admin['id']]);
                } catch(PDOException $e) {
                    // Ignore if column doesn't exist
                }
                
                // 6. Regjistro në log file (optional)
                $log_entry = date('Y-m-d H:i:s') . " - Login successful: {$username} from IP: {$ip}\n";
                @file_put_contents(__DIR__ . '/../logs/admin_login.log', $log_entry, FILE_APPEND);
                
                header('Location: dashboard.php');
                exit();
            } else {
                // Login i dështuar - regjistro tentativën
                $_SESSION['login_attempts'][] = time();
                
                // Regjistro në log file
                $log_entry = date('Y-m-d H:i:s') . " - Login failed: {$username} from IP: {$ip}\n";
                @file_put_contents(__DIR__ . '/../logs/admin_login.log', $log_entry, FILE_APPEND);
                
                // 7. Delay për të parandaluar brute-force (0.5-1.5 sekonda)
                usleep(rand(500000, 1500000));
                
                $error = "Invalid username or password!";
                
                // Kontrollo nëse ka arritur limitin
                $current_attempts = isset($_SESSION['login_attempts']) ? count($_SESSION['login_attempts']) : 0;
                $remaining = $max_attempts - $current_attempts;
                if($remaining <= 0) {
                    $error = "Too many failed attempts. Please try again in 15 minutes.";
                    $show_form = false;
                } elseif($remaining <= 2) {
                    $error .= " (" . $remaining . " attempt" . ($remaining > 1 ? "s" : "") . " remaining before lockout)";
                }
            }
        } catch(PDOException $e) {
            // 8. Gabim i përgjithshëm - mos shfaq detaje të ndjeshme
            error_log("Login error: " . $e->getMessage());
            $error = "An error occurred. Please try again later.";
        }
    }
}

// 9. Regjistro IP-në në sesion për mbrojtje shtesë
if(!isset($_SESSION['login_ip'])) {
    $_SESSION['login_ip'] = $ip;
}

// 10. Mbrojtje nga session hijacking
if(isset($_SESSION['admin_logged_in']) && $_SESSION['admin_logged_in'] === true) {
    // Kontrollo nëse IP-ja ka ndryshuar
    if(isset($_SESSION['admin_ip']) && $_SESSION['admin_ip'] !== $ip) {
        // IP ndryshoi - mund të jetë session hijacking
        session_destroy();
        header('Location: login.php?error=session');
        exit();
    }
    
    // Kontrollo nëse sessioni ka skaduar (8 orë)
    if(isset($_SESSION['admin_login_time']) && (time() - $_SESSION['admin_login_time']) > 28800) {
        session_destroy();
        header('Location: login.php?error=timeout');
        exit();
    }
}

// 11. CSRF Token për formën
if(empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrf_token = $_SESSION['csrf_token'];
?>
<!DOCTYPE html>
<html lang="sq">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Login - <?php echo htmlspecialchars($site_name); ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background: linear-gradient(135deg, #f0f4ff 0%, #e8edf5 100%);
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 20px;
        }
        
        .login-container {
            width: 100%;
            max-width: 420px;
        }
        
        .login-card {
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.12);
            padding: 44px 36px;
            position: relative;
            overflow: hidden;
        }
        
        .login-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: linear-gradient(90deg, #0066cc, #10b981);
        }
        
        .login-header {
            text-align: center;
            margin-bottom: 32px;
        }
        
        .login-logo {
            max-width: 180px;
            max-height: 70px;
            object-fit: contain;
            margin-bottom: 16px;
        }
        
        .login-header h2 {
            font-size: 22px;
            font-weight: 700;
            color: #1a1a2e;
            margin-bottom: 4px;
        }
        
        .login-header p {
            color: #6b7280;
            font-size: 14px;
        }
        
        .form-group {
            margin-bottom: 18px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 6px;
            font-weight: 600;
            color: #374151;
            font-size: 13px;
        }
        
        .form-group label i {
            color: #0066cc;
            width: 18px;
        }
        
        .form-group input {
            width: 100%;
            padding: 12px 14px;
            border: 2px solid #e5e7eb;
            border-radius: 12px;
            font-size: 15px;
            transition: border-color 0.2s, box-shadow 0.2s;
            background: #fafafa;
        }
        
        .form-group input:focus {
            outline: none;
            border-color: #0066cc;
            box-shadow: 0 0 0 4px rgba(0,102,204,0.1);
            background: white;
        }
        
        .form-group input::placeholder {
            color: #a0aec0;
        }
        
        .btn-login {
            width: 100%;
            padding: 14px;
            background: linear-gradient(135deg, #0066cc 0%, #0052a3 100%);
            color: white;
            border: none;
            border-radius: 12px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
        }
        
        .btn-login:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(0,102,204,0.3);
        }
        
        .btn-login:active {
            transform: scale(0.98);
        }
        
        .btn-login:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none !important;
        }
        
        .btn-home {
            width: 100%;
            padding: 12px;
            background: transparent;
            color: #6b7280;
            border: 2px solid #e5e7eb;
            border-radius: 12px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s;
            margin-top: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
            text-decoration: none;
        }
        
        .btn-home:hover {
            background: #f9fafb;
            border-color: #0066cc;
            color: #0066cc;
        }
        
        .btn-home:hover i {
            color: #0066cc;
        }
        
        .btn-home i {
            color: #6b7280;
            transition: color 0.3s;
        }
        
        .error-message {
            background: #fef2f2;
            color: #dc2626;
            padding: 12px 16px;
            border-radius: 12px;
            margin-bottom: 20px;
            font-size: 13px;
            border-left: 4px solid #dc2626;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .error-message i {
            font-size: 18px;
            flex-shrink: 0;
        }
        
        .login-footer {
            margin-top: 24px;
            padding-top: 20px;
            border-top: 1px solid #e5e7eb;
            text-align: center;
        }
        
        .login-footer p {
            font-size: 12px;
            color: #9ca3af;
        }
        
        /* Responsive */
        @media (max-width: 480px) {
            .login-card {
                padding: 32px 20px;
            }
            .login-logo {
                max-width: 140px;
            }
        }
    </style>
</head>
<body>
    <div class="login-container">
        <div class="login-card">
            <div class="login-header">
                <?php if(!empty($logo_url) && file_exists('../' . $logo_url)): ?>
                    <img src="../<?php echo htmlspecialchars($logo_url); ?>" alt="<?php echo htmlspecialchars($site_name); ?>" class="login-logo">
                <?php endif; ?>
                <h2><?php echo htmlspecialchars($site_name); ?></h2>
                <p>Sign in to manage your fleet</p>
            </div>
            
            <?php if(isset($_GET['error']) && $_GET['error'] == 'session'): ?>
                <div class="error-message">
                    <i class="fas fa-exclamation-triangle"></i>
                    Session expired or IP changed. Please login again.
                </div>
            <?php endif; ?>
            
            <?php if(isset($_GET['error']) && $_GET['error'] == 'timeout'): ?>
                <div class="error-message">
                    <i class="fas fa-clock"></i>
                    Session timed out. Please login again.
                </div>
            <?php endif; ?>
            
            <?php if($error): ?>
                <div class="error-message">
                    <i class="fas fa-exclamation-circle"></i>
                    <?php echo htmlspecialchars($error); ?>
                </div>
            <?php endif; ?>
            
            <?php if($show_form): ?>
                <form method="POST" autocomplete="off">
                    <!-- CSRF Token -->
                    <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrf_token); ?>">
                    
                    <div class="form-group">
                        <label><i class="fas fa-user"></i> Username</label>
                        <input type="text" name="username" placeholder="Enter username" required autofocus 
                               value="<?php echo htmlspecialchars($_POST['username'] ?? ''); ?>">
                    </div>
                    <div class="form-group">
                        <label><i class="fas fa-lock"></i> Password</label>
                        <input type="password" name="password" placeholder="Enter password" required>
                    </div>
                    <button type="submit" class="btn-login">
                        <i class="fas fa-sign-in-alt"></i> Sign In
                    </button>
                </form>
            <?php else: ?>
                <div style="text-align: center; padding: 20px 0;">
                    <i class="fas fa-clock" style="font-size: 48px; color: #f59e0b; margin-bottom: 16px; display: block;"></i>
                    <p style="color: #6b7280; font-size: 14px;">
                        Too many failed login attempts.
                    </p>
                    <p style="color: #6b7280; font-size: 13px; margin-top: 4px;">
                        Please try again in 15 minutes.
                    </p>
                </div>
            <?php endif; ?>
            
            <!-- Butoni për në Homepage -->
            <a href="https://rental2b.esc.al/" class="btn-home" target="_blank">
                <i class="fas fa-home"></i> Visit Website
            </a>
            
            <div class="login-footer">
                <p>&copy; <?php echo date('Y'); ?> <?php echo htmlspecialchars($site_name); ?>. All rights reserved.</p>
            </div>
        </div>
    </div>
</body>
</html>