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

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

// Pesan fallback
 $msg_success_add = ($current_lang == 'id') ? 'Kategori berhasil ditambahkan' : 'Category added successfully';
 $msg_success_edit = ($current_lang == 'id') ? 'Kategori berhasil diperbarui' : 'Category updated successfully';
 $msg_cannot_delete = ($current_lang == 'id') ? 'Tidak dapat menghapus: Kategori sedang digunakan' : 'Cannot delete: Category is in use';

try {
    if ($action === 'add') {
        $stmt = $pdo->prepare("INSERT INTO category (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 Category', "Added category: ".$_POST['name'], 'mdi-folder']);
        
        $_SESSION['flash'] = ['type' => 'success', 'msg' => $msg_success_add];
    }
    elseif ($action === 'edit') {
        $stmt = $pdo->prepare("UPDATE category 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 Category', "Updated category: ".$_POST['name'], 'mdi-pencil']);
        
        $_SESSION['flash'] = ['type' => 'success', 'msg' => $msg_success_edit];
    }
    elseif ($action === 'delete') {
        // Cek apakah kategori digunakan di spareparts
        $check = $pdo->prepare("SELECT COUNT(*) FROM spareparts WHERE category_id = ?");
        $check->execute([$_POST['id']]);
        if ($check->fetchColumn() > 0) {
            $_SESSION['flash'] = ['type' => 'error', 'msg' => $msg_cannot_delete];
        } else {
            $stmt = $pdo->prepare("DELETE FROM category 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 Category', "Deleted category ID: ".$_POST['id'], 'mdi-delete']);
            
            $_SESSION['flash'] = ['type' => 'success', 'msg' => 'Category deleted'];
        }
    }
} catch (PDOException $e) {
    $_SESSION['flash'] = ['type' => 'error', 'msg' => 'Error: ' . $e->getMessage()];
}

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