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

 $action = $_POST['action'] ?? '';
 $current_lang = $_SESSION['lang'] ?? 'id';

// Untuk pesan fallback jika bahasa tidak terload penuh di action file
 $msg_success_add = ($current_lang == 'id') ? 'Grup material berhasil ditambahkan' : 'Material group added successfully';
 $msg_success_edit = ($current_lang == 'id') ? 'Grup material berhasil diperbarui' : 'Material group updated successfully';
 $msg_cannot_delete = ($current_lang == 'id') ? 'Tidak dapat menghapus: Grup sedang digunakan' : 'Cannot delete: Group is in use';

try {
    if ($action === 'add') {
        $stmt = $pdo->prepare("INSERT INTO material_group (code, name, description, status) VALUES (?, ?, ?, ?)");
        $stmt->execute([$_POST['code'], $_POST['name'], $_POST['description'], $_POST['status']]);
        
        $log = $pdo->prepare("INSERT INTO activity_log (user_id, action, description, icon) VALUES (?, ?, ?, ?)");
        $log->execute([$_SESSION['user_id'], 'Add Material Group', "Added group: ".$_POST['name'], 'mdi-group']);
        
        $_SESSION['flash'] = ['type' => 'success', 'msg' => $msg_success_add];
    }
    elseif ($action === 'edit') {
        $stmt = $pdo->prepare("UPDATE material_group SET code=?, name=?, description=?, status=? WHERE id=?");
        $stmt->execute([$_POST['code'], $_POST['name'], $_POST['description'], $_POST['status'], $_POST['id']]);
        
        $log = $pdo->prepare("INSERT INTO activity_log (user_id, action, description, icon) VALUES (?, ?, ?, ?)");
        $log->execute([$_SESSION['user_id'], 'Edit Material Group', "Updated group: ".$_POST['name'], 'mdi-pencil']);
        
        $_SESSION['flash'] = ['type' => 'success', 'msg' => $msg_success_edit];
    }
    elseif ($action === 'delete') {
        $check = $pdo->prepare("SELECT COUNT(*) FROM spareparts WHERE material_group_id = ?");
        $check->execute([$_POST['id']]);
        if ($check->fetchColumn() > 0) {
            $_SESSION['flash'] = ['type' => 'error', 'msg' => $msg_cannot_delete];
        } else {
            $stmt = $pdo->prepare("DELETE FROM material_group WHERE id = ?");
            $stmt->execute([$_POST['id']]);
            
            $log = $pdo->prepare("INSERT INTO activity_log (user_id, action, description, icon) VALUES (?, ?, ?, ?)");
            $log->execute([$_SESSION['user_id'], 'Delete Material Group', "Deleted group ID: ".$_POST['id'], 'mdi-delete']);
            
            $_SESSION['flash'] = ['type' => 'success', 'msg' => 'Material group deleted'];
        }
    }
} catch (PDOException $e) {
    $_SESSION['flash'] = ['type' => 'error', 'msg' => 'Error: ' . $e->getMessage()];
}

header('Location: ../view/material_group.php');
exit;