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

 $action = $_POST['action'] ?? '';

try {
    if ($action === 'add') {
        $nama = $_POST['nama_mesin'];
        $tahun = $_POST['tahun'];
        $stmt = $pdo->prepare("INSERT INTO mesin (nama_mesin, tahun) VALUES (?, ?)");
        $stmt->execute([$nama, $tahun]);
        
        $_SESSION['flash'] = ['msg' => $lang[$current_lang]['success_add_machine'], 'type' => 'success'];
    } 
    elseif ($action === 'edit') {
        $id = $_POST['id'];
        $nama = $_POST['nama_mesin'];
        $tahun = $_POST['tahun'];
        $stmt = $pdo->prepare("UPDATE mesin SET nama_mesin=?, tahun=? WHERE id=?");
        $stmt->execute([$nama, $tahun, $id]);
        
        $_SESSION['flash'] = ['msg' => $lang[$current_lang]['success_edit_machine'], 'type' => 'success'];
    } 
    elseif ($action === 'delete') {
        $id = $_POST['id'];
        // Foreign Key constraint di SQL sudah ON DELETE CASCADE, jadi bagian_mesin akan ikut terhapus otomatis
        $stmt = $pdo->prepare("DELETE FROM mesin WHERE id=?");
        $stmt->execute([$id]);
        
        $_SESSION['flash'] = ['msg' => $lang[$current_lang]['success_delete_machine'], 'type' => 'success'];
    }
} catch (Exception $e) {
    $_SESSION['flash'] = ['msg' => 'Error: ' . $e->getMessage(), 'type' => 'error'];
}

header('Location: ../view/mesin.php');
exit;
?>