<?php
require_once '../config/config.php';
if (!isset($_SESSION['user_id'])) { exit; }

header('Content-Type: application/json');
 $action = $_POST['action'] ?? '';
 $response = ['status' => 'error', 'message' => 'Unknown error'];

try {
    if ($action === 'add') {
        $mesin_id = $_POST['mesin_id'];
        $nama_bagian = trim($_POST['nama_bagian']);
        
        if(empty($nama_bagian)) {
            echo json_encode(['status' => 'error', 'message' => 'Nama bagian tidak boleh kosong']);
            exit;
        }

        $stmt = $pdo->prepare("INSERT INTO bagian_mesin (mesin_id, nama_bagian) VALUES (?, ?)");
        $stmt->execute([$mesin_id, $nama_bagian]);
        
        // Gunakan fallback string jika key bahasa tidak ada
        $msg = $lang[$current_lang]['success_add_part'] ?? 'Bagian mesin berhasil ditambahkan';
        $response = ['status' => 'success', 'message' => $msg];
    }
    elseif ($action === 'delete') {
        $id = $_POST['id'];
        $stmt = $pdo->prepare("DELETE FROM bagian_mesin WHERE id=?");
        $stmt->execute([$id]);
        
        $msg = $lang[$current_lang]['success_delete_part'] ?? 'Bagian mesin berhasil dihapus';
        $response = ['status' => 'success', 'message' => $msg];
    }
} catch (Exception $e) {
    $response = ['status' => 'error', 'message' => $e->getMessage()];
}

echo json_encode($response);
?>