<?php
/**
 * API untuk autentikasi user
 * Endpoint: /api/auth.php
 */

require_once '../config/database.php';

// Set CORS headers
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

// Handle preflight OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

$database = new Database();
$db = $database->getConnection();

if (!$db) {
    jsonResponse(['error' => 'Database connection failed'], 500);
}

$method = $_SERVER['REQUEST_METHOD'];
$input = json_decode(file_get_contents('php://input'), true);

try {
    switch ($method) {
        case 'POST':
            handleLogin($db, $input);
            break;
        case 'GET':
            handleVerifyToken($db);
            break;
        default:
            jsonResponse(['error' => 'Method not allowed'], 405);
    }
} catch (Exception $e) {
    jsonResponse(['error' => $e->getMessage()], 500);
}

/**
 * POST - Login user
 */
function handleLogin($db, $input) {
    // Validasi input
    $errors = validateInput($input, ['username', 'password']);
    if (!empty($errors)) {
        jsonResponse(['error' => 'Validation failed', 'details' => $errors], 400);
    }
    
    $username = sanitizeInput($input['username']);
    $password = $input['password'];
    
    // Cari user berdasarkan username
    $query = "
        SELECT 
            u.id,
            u.username,
            u.password,
            u.full_name,
            u.is_admin,
            u.is_active,
            p.id as position_id,
            p.name as position_name
        FROM users u
        LEFT JOIN positions p ON u.position_id = p.id
        WHERE u.username = :username AND u.is_active = 1
    ";
    
    $stmt = $db->prepare($query);
    $stmt->bindParam(':username', $username);
    $stmt->execute();
    
    $user = $stmt->fetch();
    
    if (!$user) {
        jsonResponse(['error' => 'Invalid username or password'], 401);
    }
    
    // Verifikasi password (menggunakan password_hash default)
    if (!password_verify($password, $user['password'])) {
        jsonResponse(['error' => 'Invalid username or password'], 401);
    }
    
    // Generate token sederhana (dalam production gunakan JWT)
    $token = base64_encode(json_encode([
        'user_id' => $user['id'],
        'username' => $user['username'],
        'expires' => time() + (24 * 60 * 60) // 24 jam
    ]));
    
    // Hapus password dari response
    unset($user['password']);
    
    jsonResponse([
        'success' => true,
        'message' => 'Login successful',
        'token' => $token,
        'user' => $user
    ]);
}

/**
 * GET - Verifikasi token
 */
function handleVerifyToken($db) {
    $headers = getallheaders();
    $token = $headers['Authorization'] ?? '';
    
    if (empty($token)) {
        jsonResponse(['error' => 'Token required'], 401);
    }
    
    // Decode token
    $tokenData = json_decode(base64_decode($token), true);
    
    if (!$tokenData || $tokenData['expires'] < time()) {
        jsonResponse(['error' => 'Invalid or expired token'], 401);
    }
    
    // Ambil data user terbaru
    $query = "
        SELECT 
            u.id,
            u.username,
            u.full_name,
            u.is_admin,
            u.is_active,
            p.id as position_id,
            p.name as position_name
        FROM users u
        LEFT JOIN positions p ON u.position_id = p.id
        WHERE u.id = :user_id AND u.is_active = 1
    ";
    
    $stmt = $db->prepare($query);
    $stmt->bindParam(':user_id', $tokenData['user_id']);
    $stmt->execute();
    
    $user = $stmt->fetch();
    
    if (!$user) {
        jsonResponse(['error' => 'User not found'], 404);
    }
    
    jsonResponse([
        'success' => true,
        'user' => $user
    ]);
}

/**
 * Fungsi helper untuk mendapatkan token dari header
 */
function getTokenFromHeader() {
    $headers = getallheaders();
    $auth = $headers['Authorization'] ?? '';
    
    if (strpos($auth, 'Bearer ') === 0) {
        return substr($auth, 7);
    }
    
    return $auth;
}
?>
