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

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

try {
    if ($action === 'add') {
        $nama_line = $_POST['nama_line'];
        $nama_product = $_POST['nama_product'];
        $mesin_id = !empty($_POST['mesin_id']) ? $_POST['mesin_id'] : NULL;

        $stmt = $pdo->prepare("INSERT INTO lines (nama_line, nama_product, mesin_id) VALUES (?, ?, ?)");
        $stmt->execute([$nama_line, $nama_product, $mesin_id]);
        
        $_SESSION['flash'] = ['msg' => $lang[$current_lang]['success_add_line'], 'type' => 'success'];
    } 
    elseif ($action === 'edit') {
        $id = $_POST['id'];
        $nama_line = $_POST['nama_line'];
        $nama_product = $_POST['nama_product'];
        $mesin_id = !empty($_POST['mesin_id']) ? $_POST['mesin_id'] : NULL;

        $stmt = $pdo->prepare("UPDATE lines SET nama_line=?, nama_product=?, mesin_id=? WHERE id=?");
        $stmt->execute([$nama_line, $nama_product, $mesin_id, $id]);
        
        $_SESSION['flash'] = ['msg' => $lang[$current_lang]['success_edit_line'], 'type' => 'success'];
    } 
    elseif ($action === 'delete') {
        $id = $_POST['id'];
        $stmt = $pdo->prepare("DELETE FROM lines WHERE id=?");
        $stmt->execute([$id]);
        
        $_SESSION['flash'] = ['msg' => $lang[$current_lang]['success_delete_line'], 'type' => 'success'];
    }
} catch (Exception $e) {
    $_SESSION['flash'] = ['msg' => 'Error: ' . $e->getMessage(), 'type' => 'error'];
}

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