<?php
// api/positions.php
require_once '../config/database.php';
require_once __DIR__ . '/session_auth.php';
rvu_audit_context_from_request($pdo);
header("Content-Type: application/json");

$method = $_SERVER['REQUEST_METHOD'];
$path_info = isset($_SERVER['PATH_INFO']) ? explode('/', trim($_SERVER['PATH_INFO'], '/')) : [];
$id = $path_info[0] ?? null;

$input = json_decode(file_get_contents("php://input"), true) ?? [];

try {
    // 1. GET ROUTE: Fetch all positions
    if ($method === 'GET') {
        echo json_encode($pdo->query("SELECT * FROM positions")->fetchAll(PDO::FETCH_ASSOC));
    } 
    
    // 2. POST ROUTE: Create a new position
    elseif ($method === 'POST') {
        $stmt = $pdo->prepare("INSERT INTO positions (title, status) VALUES (?, ?)");
        // Defaults to "Active" just like the Python logic: position.status or "Active"
        $stmt->execute([$input['title'], $input['status'] ?? "Active"]);
        
        http_response_code(201);
        echo json_encode([
            "title" => $input['title'],
            "status" => $input['status'] ?? "Active",
            "id" => $pdo->lastInsertId()
        ]);
    } 
    
    // 3. PUT ROUTE: Update an existing position
    elseif ($method === 'PUT' && $id) {
        $fields = []; 
        $params = [];
        
        // Dynamically build the update query based on what the frontend sends
        if (isset($input['title'])) {
            $fields[] = "title = ?";
            $params[] = $input['title'];
        }
        if (isset($input['status'])) {
            $fields[] = "status = ?";
            $params[] = $input['status'];
        }
        
        if (empty($fields)) {
            echo json_encode(["message" => "Nothing to update"]);
            exit;
        }
        
        $params[] = $id;
        $sql = "UPDATE positions SET " . implode(', ', $fields) . " WHERE id = ?";
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        
        // Ensure we send back a 404 if the position didn't exist
        if ($stmt->rowCount() === 0) {
            // Optional: You can do a SELECT first to check existence if you want strictly identical 404 behavior,
            // but checking rowCount is faster.
            $check = $pdo->prepare("SELECT id FROM positions WHERE id = ?");
            $check->execute([$id]);
            if (!$check->fetch()) {
                http_response_code(404);
                echo json_encode(["detail" => "Position not found"]);
                exit;
            }
        }
        
        echo json_encode(["message" => "Position updated successfully", "id" => $id]);
    } 
    
    // 4. DELETE ROUTE: Remove a position
    elseif ($method === 'DELETE' && $id) {
        $stmt = $pdo->prepare("DELETE FROM positions WHERE id = ?");
        $stmt->execute([$id]);
        
        if ($stmt->rowCount() === 0) {
            http_response_code(404);
            echo json_encode(["detail" => "Position not found"]);
            exit;
        }
        
        http_response_code(204); // Returns 204 No Content exactly like FastAPI
    } 
    
    else {
        http_response_code(404);
        echo json_encode(["detail" => "Endpoint not found"]);
    }

} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(["detail" => $e->getMessage()]);
}
?>