<?php
/**
 * API untuk mengelola data posisi/jabatan
 * Endpoint: /api/positions.php
 */

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

// Set CORS headers
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, 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'];

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

/**
 * GET - Ambil semua data posisi
 */
function handleGetPositions($db) {
    $query = "
        SELECT 
            id,
            name,
            order_index,
            created_at,
            updated_at
        FROM positions
        ORDER BY order_index ASC
    ";
    
    $stmt = $db->prepare($query);
    $stmt->execute();
    
    $positions = $stmt->fetchAll();
    
    jsonResponse([
        'success' => true,
        'data' => $positions
    ]);
}
?>
