<?php
session_start();
require 'config.php';
header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = sanitize($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';
    $login_type = $_POST['login_type'] ?? 'auto'; // 'auto' = detect automatically
    
    if (empty($username) || empty($password)) {
        echo json_encode(['success' => false, 'message' => 'Username dan password harus diisi']);
        exit();
    }
    
    $stmt = $conn->prepare("SELECT id, username, password, full_name, role, specialization, supervisor_initial, semester FROM users WHERE username = ? AND is_active = TRUE");
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows == 1) {
        $user = $result->fetch_assoc();
        
        $stored_hash = $user['password'];
        $is_valid = password_verify($password, $stored_hash);
        if (!$is_valid && preg_match('/^[a-f0-9]{32}$/i', $stored_hash)) {
            $is_valid = md5($password) === $stored_hash;
        }

        if ($is_valid) {
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['user_role'] = $user['role'];
            $_SESSION['user_data'] = [
                'id' => $user['id'],
                'username' => $user['username'],
                'full_name' => $user['full_name'],
                'role' => $user['role'],
                'specialization' => $user['specialization'] ?? '',
                'supervisor_initial' => $user['supervisor_initial'] ?? '',
                'semester' => $user['semester'] ?? ''
            ];
            
            echo json_encode([
                'success' => true,
                'message' => 'Login berhasil',
                'role' => $user['role']
            ]);
        } else {
            echo json_encode(['success' => false, 'message' => 'Password salah']);
        }
    } else {
        echo json_encode(['success' => false, 'message' => 'Username tidak ditemukan']);
    }
    
    $stmt->close();
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
}
?>
