<?php
session_start();
require_once 'includes/config.php';

// Redirect jika sudah login dan role adalah marketing
if (isset($_SESSION['user_id']) && $_SESSION['role'] === 'marketing') {
    header("Location: dashboard.php");
    exit();
}

// Generate CSRF token untuk form login
if (!isset($_SESSION['csrf_token'])) {
    $csrf_token = generateCSRFToken();
} else {
    $csrf_token = $_SESSION['csrf_token'];
}

// Ambil pesan error dari session jika ada
$error = isset($_SESSION['login_error']) ? $_SESSION['login_error'] : null;
unset($_SESSION['login_error']);

// Fungsi untuk logging login
function logUserLogin($user_id, $username, $role) {
    global $db;
    try {
        $stmt = $db->prepare("
            INSERT INTO login_logs (user_id, username, role, ip_address, user_agent) 
            VALUES (?, ?, ?, ?, ?)
        ");
        return $stmt->execute([
            $user_id,
            $username,
            $role,
            $_SERVER['REMOTE_ADDR'],
            $_SERVER['HTTP_USER_AGENT']
        ]);
    } catch(PDOException $e) {
        error_log("Login log error: " . $e->getMessage());
        return false;
    }
}

if(isset($_POST['login'])) {
    // Verifikasi CSRF token
    if (!verifyCSRFToken($_POST['csrf_token'])) {
        $_SESSION['login_error'] = "Invalid security token!";
        header("Location: login.php");
        exit();
    }
    
    $username = sanitize_input($_POST['username']);
    $password = $_POST['password'];
    
    try {
        // Debug input
        error_log("Login attempt - Username: " . $username);
        
        // Cek di tabel marketing
        $user = checkUserLogin('marketing', $username);
        
        if ($user && password_verify($password, $user['password'])) {
            error_log("Marketing login successful");
            // Set session
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['username'] = $user['username'];
            $_SESSION['role'] = 'marketing';
            $_SESSION['nama_lengkap'] = $user['nama_lengkap'];
            
            // Log login berhasil
            logUserLogin($user['id'], $user['username'], 'marketing');
            
            header("Location: dashboard.php");
            exit();
        }
        
        error_log("Login failed for username: " . $username);
        $_SESSION['login_error'] = "Username atau password tidak valid!";
        header("Location: login.php");
        exit();
        
    } catch(PDOException $e) {
        error_log("Login error: " . $e->getMessage());
        $_SESSION['login_error'] = "Terjadi kesalahan sistem. Silakan coba lagi.";
        header("Location: login.php");
        exit();
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login - Marketing Panel</title>
    <link rel="stylesheet" href="css/style.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/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-gradient">
    <div class="container">
        <div class="row justify-content-center min-vh-100 align-items-center">
            <div class="col-md-9">
                <div class="card shadow-lg">
                    <div class="row g-0">
                        <div class="col-md-6 bg-primary rounded-start d-none d-md-block">
                            <div class="d-flex align-items-center justify-content-center h-100 p-5">
                                <div class="text-center text-white">
                                    <i class="fas fa-user-shield fa-5x mb-3"></i>
                                    <h2 class="fw-bold">Marketing Panel</h2>
                                    <p class="lead">Please login to access the system</p>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="card-body p-5">
                                <div class="text-center mb-4">
                                    <i class="fas fa-lock fa-2x text-primary mb-2"></i>
                                    <h3 class="fw-bold">Login</h3>
                                    <p class="text-muted">Enter your credentials</p>
                                </div>

                                <?php if(isset($error)): ?>
                                    <div class="alert alert-danger d-flex align-items-center" role="alert">
                                        <i class="fas fa-exclamation-circle me-2"></i>
                                        <?php echo $error; ?>
                                    </div>
                                <?php endif; ?>

                                <form method="POST" action="">
                                    <input type="hidden" name="csrf_token" value="<?php echo $csrf_token; ?>">
                                    <div class="mb-4">
                                        <div class="input-group">
                                            <span class="input-group-text bg-light">
                                                <i class="fas fa-user text-primary"></i>
                                            </span>
                                            <input type="text" class="form-control" id="username" name="username" placeholder="Username" required>
                                        </div>
                                    </div>

                                    <div class="mb-4">
                                        <div class="input-group">
                                            <span class="input-group-text bg-light">
                                                <i class="fas fa-key text-primary"></i>
                                            </span>
                                            <input type="password" class="form-control" id="password" name="password" placeholder="Password" required>
                                        </div>
                                    </div>

                                    <div class="mb-4 form-check">
                                        <input type="checkbox" class="form-check-input" id="remember">
                                        <label class="form-check-label" for="remember">Remember me</label>
                                    </div>

                                    <div class="d-grid">
                                        <button type="submit" name="login" class="btn btn-primary btn-lg">
                                            <i class="fas fa-sign-in-alt me-2"></i>Sign In
                                        </button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
