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

// Generate CSRF token untuk form login
$csrf_token = generateCSRFToken();

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

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

// Tambahkan fungsi logging di bagian login yang berhasil
function logUserLogin($user_id, $username, $role) {
    global $db_auth;
    try {
        $stmt = $db_auth->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 {
        $db_auth->exec("USE " . DB_AUTH_NAME);
        
        // Debug input
        error_log("Login attempt - Username: " . $username);
        error_log("Password length: " . strlen($password));
        
        // Cek di tabel superadmin dulu
        $user = checkUserLogin('superadmin', $username);
        
        if ($user && password_verify($password, $user['password'])) {
            error_log("Superadmin login successful");
            // Set session
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['username'] = $user['username'];
            $_SESSION['role'] = 'superadmin';
            $_SESSION['nama_lengkap'] = $user['nama_lengkap'];
            
            // Panggil fungsi logging setelah login berhasil
            logUserLogin($user['id'], $user['username'], $_SESSION['role']);
            
            header("Location: dashboard.php");
            exit();
        } else {
            // Cek di tabel lain
            $other_tables = ['supervisor', 'developer'];
            foreach ($other_tables as $table) {
                error_log("Checking table: " . $table);
                $user = checkUserLogin($table, $username);
                
                if ($user) {
                    error_log("User found in $table");
                    error_log("Stored hash: " . $user['password']);
                    error_log("Password verify result: " . (password_verify($password, $user['password']) ? 'true' : 'false'));
                    
                    if (password_verify($password, $user['password'])) {
                        error_log("$table login successful");
                        $_SESSION['user_id'] = $user['id'];
                        $_SESSION['username'] = $user['username'];
                        $_SESSION['role'] = $table;
                        $_SESSION['nama_lengkap'] = $user['nama_lengkap'];
                        
                        // Panggil fungsi logging setelah login berhasil
                        logUserLogin($user['id'], $user['username'], $_SESSION['role']);
                        
                        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();
    }
}

// Tambahkan ini di bagian paling bawah file untuk memastikan database sudah dibuat
if (isset($_GET['debug']) && $_GET['debug'] == 1) {
    try {
        $result = $db_auth->query("SHOW TABLES");
        echo "<pre>";
        print_r($result->fetchAll());
        echo "</pre>";
        exit;
    } catch(PDOException $e) {
        echo "Error: " . $e->getMessage();
        exit;
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login - System</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">
    <link href="https://fonts.googleapis.com/css2?family=Doto:wght@400;700&display=swap" rel="stylesheet">
</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>
                                    <h3 class="fw-bold" style="font-family: 'Doto', sans-serif; font-size: 1.8rem;">Miracle-TECH<br>Phone Call System</h3>
                                    <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>
