Index: app/Http/Controllers/GenericModelController.php
===================================================================
--- app/Http/Controllers/GenericModelController.php	(revision 118d88fce4f1e1e88092c991a75f3b9bb10e6975)
+++ app/Http/Controllers/GenericModelController.php	(revision f003a24e7d1eb472814b53616f73c655cfa87efa)
@@ -259,4 +259,7 @@
     }
 
+    /**
+     * Get related options for foreign key fields with better field name detection
+     */
     protected function getRelatedOptions($modelInstance): array
     {
@@ -267,4 +270,5 @@
             if (Str::endsWith($field, '_id')) {
                 $relationName = Str::beforeLast($field, '_id');
+
                 if (method_exists($modelInstance, $relationName)) {
                     try {
@@ -272,14 +276,47 @@
                         if ($relation instanceof BelongsTo) {
                             $relatedModel = $relation->getRelated();
+
+                            // Get the first record to check available fields
+                            $sampleRecord = $relatedModel->first();
+                            $nameField = 'name';
+
+                            // Determine the best field to use for display
+                            if ($sampleRecord) {
+                                $fillableFields = $sampleRecord->getFillable();
+
+                                // Look for common display fields
+                                if (in_array('name', $fillableFields)) {
+                                    $nameField = 'name';
+                                } elseif (in_array('title', $fillableFields)) {
+                                    $nameField = 'title';
+                                } elseif (in_array('method', $fillableFields)) {
+                                    $nameField = 'method'; // For Payment model
+                                } elseif (in_array('code', $fillableFields)) {
+                                    $nameField = 'code';
+                                } else {
+                                    // Fallback to ID if no suitable field found
+                                    $nameField = 'id';
+                                }
+                            }
+
                             $relatedItems = $relatedModel->all();
 
-                            $options[$field] = $relatedItems->map(function ($item) {
+                            $options[$field] = $relatedItems->map(function ($item) use ($nameField) {
+                                $displayValue = $item->{$nameField};
+
+                                // If using ID as display field, format it nicely
+                                if ($nameField === 'id') {
+                                    $displayValue = "#{$item->id}";
+                                }
+
                                 return [
                                     'id' => $item->id,
-                                    'name' => $item->name ?? ("#{$item->id}"),
+                                    'name' => $displayValue,
                                 ];
                             })->values();
                         }
                     } catch (\Exception $e) {
+                        // Log the error and continue with other fields
+                        \Log::error("Failed to load related options for {$field}: " . $e->getMessage());
                         continue;
                     }
@@ -291,318 +328,2 @@
     }
 }
-
-//
-//namespace App\Http\Controllers;
-//
-//use Illuminate\Http\Request;
-//use Inertia\Inertia;
-//use Illuminate\Support\Str;
-//use Illuminate\Database\Eloquent\Relations\BelongsTo;
-//use function Laravel\Prompts\error;
-//
-//class GenericModelController extends Controller
-//{
-//    protected function preprocessFormData(array $data, $modelInstance): array
-//    {
-//        $fillable = $modelInstance->getFillable();
-//
-//        foreach ($fillable as $field) {
-//            // hendla nadvoreshni kluchevi
-//            if (Str::endsWith($field, '_id') && isset($data[$field])) {
-//                // ekstrahira id of objektot ako e daden kako objekt
-//                if (is_array($data[$field])) {
-//                    $data[$field] = $data[$field]['id'] ?? null;
-//                }
-//                // konvertira prazen string u null za nadvoreshni kluchevi
-//                if ($data[$field] === '') {
-//                    $data[$field] = null;
-//                }
-//            }
-//
-//            // hendla boolean polinja
-//            if (isset($data[$field]) && is_bool($modelInstance->$field)) {
-//                $data[$field] = (bool) $data[$field];
-//
-//            }
-//
-//            // hendla date polinja
-//            $casts = $modelInstance->getCasts();
-//            if (isset($casts[$field]) && strpos($casts[$field], 'date') !== false && isset($data[$field])) {
-//                if ($data[$field] === '') {
-//                    $data[$field] = null;
-//                }
-//            }
-//
-//            return $data;
-//        }
-//    }
-//
-//    public function store(Request $request, string $model)
-//    {
-//        \Log::info('STORE - raw request payload', $request->all());
-//        \Log::info('STORE - model param: ' . $model);
-//
-//        $modelClass = $this->getModelClass($model);
-//        if (!$modelClass) {
-//            abort(404, 'Model not found.');
-//        }
-//
-//        $modelInstance = new $modelClass();
-//
-//
-//        $data = $request->all();
-//        $data = $this->preprocessFormData($data, $modelInstance);
-//
-//        try {
-//            $valdated = validator($data, $modelClass:getValidationRules()) -> validate();
-//        } catch (\Illuminate\Validation\ValidationException $e) {
-//            log.error('STORE - validation failed', $e->errors());
-//        }
-//
-////        // Re-enable validation but with better error handling
-////        try {
-////            $validated = $request->validate($data, $modelClass::getValidationRules());
-////            \Log::info('STORE - validation passed', $validated);
-////        } catch (\Illuminate\Validation\ValidationException $e) {
-////            \Log::error('STORE - validation failed', $e->errors());
-////
-////            // Return proper Inertia error response
-////            return redirect()->back()
-////                ->withErrors($e->errors())
-////                ->withInput();
-////        }
-//
-//        // Normalize foreign keys
-//        $data = $this->normalizeForeignKeys($validated, $modelInstance);
-//        \Log::info('STORE - normalized payload', $data);
-//
-//        try {
-//            $created = $modelClass::create($data);
-//            \Log::info('STORE - created record', ['id' => $created->id ?? null, 'model' => $model]);
-//
-//            // Proper Inertia redirect after successful creation
-//            return redirect()->route('generic.index', ['model' => $model])
-//                ->with('success', Str::singular($model) . ' created successfully.');
-//
-//        } catch (\Throwable $e) {
-//            \Log::error('STORE - DB error: ' . $e->getMessage(), ['exception' => $e]);
-//
-//            return redirect()->back()
-//                ->withErrors(['error' => 'Failed to create ' . $model . ': ' . $e->getMessage()])
-//                ->withInput();
-//        }
-//    }
-//
-//    public function update(Request $request, string $model, string $id)
-//    {
-//        \Log::info('UPDATE - raw request payload', $request->all());
-//        \Log::info('UPDATE - model param: ' . $model . ' id: ' . $id);
-//
-//        $modelClass = $this->getModelClass($model);
-//        if (!$modelClass) {
-//            abort(404, 'Model not found.');
-//        }
-//
-//        $item = $modelClass::findOrFail($id);
-//
-//        // Re-enable validation
-//        try {
-//            $validated = $request->validate($modelClass::getValidationRules($item->id));
-//            \Log::info('UPDATE - validation passed', $validated);
-//        } catch (\Illuminate\Validation\ValidationException $e) {
-//            \Log::error('UPDATE - validation failed', $e->errors());
-//
-//            return redirect()->back()
-//                ->withErrors($e->errors())
-//                ->withInput();
-//        }
-//
-//        $data = $this->normalizeForeignKeys($validated, $item);
-//        \Log::info('UPDATE - normalized payload', $data);
-//
-//        try {
-//            $item->update($data);
-//            \Log::info('UPDATE - updated record', ['id' => $item->id]);
-//
-//            return redirect()->route('generic.index', ['model' => $model])
-//                ->with('success', Str::singular($model) . ' updated successfully.');
-//
-//        } catch (\Throwable $e) {
-//            \Log::error('UPDATE - DB error: ' . $e->getMessage(), ['exception' => $e]);
-//
-//            return redirect()->back()
-//                ->withErrors(['error' => 'Failed to update ' . $model . ': ' . $e->getMessage()])
-//                ->withInput();
-//        }
-//    }
-//
-//    // Improved normalizeForeignKeys method
-//    protected function normalizeForeignKeys(array $data, $modelInstance): array
-//    {
-//        $fillable = $modelInstance->getFillable();
-//
-//        foreach ($fillable as $field) {
-//            if (Str::endsWith($field, '_id') && isset($data[$field])) {
-//                // Handle various input formats
-//                if (is_array($data[$field])) {
-//                    // Extract ID from object: {id: 'uuid', name: 'Name'}
-//                    $data[$field] = $data[$field]['id'] ?? null;
-//                } elseif (is_string($data[$field]) && empty($data[$field])) {
-//                    // Convert empty strings to null for foreign keys
-//                    $data[$field] = null;
-//                }
-//                // If it's already a valid ID (string/int), leave it as is
-//            }
-//        }
-//
-//        return $data;
-//    }
-//
-//    // Rest of your existing methods remain the same...
-//
-//    protected function getModelClass(string $model)
-//    {
-//        $modelClass = 'App\\Models\\' . Str::studly(Str::singular($model));
-//        if (class_exists($modelClass)) {
-//            return $modelClass;
-//        }
-//        return null;
-//    }
-//
-//    protected function getRelationships($modelInstance): array
-//    {
-//        $relationships = [];
-//        $fillable = $modelInstance->getFillable();
-//
-//        foreach ($fillable as $field) {
-//            if (Str::endsWith($field, '_id')) {
-//                $relationName = Str::beforeLast($field, '_id');
-//
-//                if (method_exists($modelInstance, $relationName)) {
-//                    try {
-//                        $relation = $modelInstance->$relationName();
-//                        if ($relation instanceof BelongsTo) {
-//                            $relationships[] = $relationName;
-//                        }
-//                    } catch (\Exception $e) {
-//                        continue;
-//                    }
-//                }
-//            }
-//        }
-//
-//        return $relationships;
-//    }
-//
-//    protected function getForeignKeyMap($modelInstance): array
-//    {
-//        $fkMap = [];
-//        $fillable = $modelInstance->getFillable();
-//
-//        foreach ($fillable as $field) {
-//            if (Str::endsWith($field, '_id')) {
-//                $relationName = Str::beforeLast($field, '_id');
-//                $tableName = Str::plural($relationName);
-//                $fkMap[$field] = $tableName;
-//            }
-//        }
-//
-//        return $fkMap;
-//    }
-//
-//    protected function getRelatedOptions($modelInstance): array
-//    {
-//        $options = [];
-//        $fillable = $modelInstance->getFillable();
-//
-//        foreach ($fillable as $field) {
-//            if (Str::endsWith($field, '_id')) {
-//                $relationName = Str::beforeLast($field, '_id');
-//                if (method_exists($modelInstance, $relationName)) {
-//                    try {
-//                        $relation = $modelInstance->$relationName();
-//                        if ($relation instanceof BelongsTo) {
-//                            $relatedModel = $relation->getRelated();
-//                            $relatedItems = $relatedModel->all();
-//
-//                            $options[$field] = $relatedItems->map(function ($item) {
-//                                return [
-//                                    'id' => $item->id,
-//                                    'name' => $item->name ?? ("#{$item->id}"),
-//                                ];
-//                            })->values();
-//                        }
-//                    } catch (\Exception $e) {
-//                        continue;
-//                    }
-//                }
-//            }
-//        }
-//
-//        return $options;
-//    }
-//
-//    public function index(Request $request, string $model)
-//    {
-//        $modelClass = $this->getModelClass($model);
-//        if (!$modelClass) {
-//            abort(404, 'Model not found.');
-//        }
-//
-//        $query = $modelClass::query();
-//        $modelInstance = new $modelClass();
-//        $fillable = $modelInstance->getFillable();
-//
-//        $relationships = $this->getRelationships($modelInstance);
-//        if (!empty($relationships)) {
-//            $query->with($relationships);
-//        }
-//
-//        if ($request->has('search') && $request->search) {
-//            $query->where(function ($q) use ($request, $fillable) {
-//                foreach ($fillable as $field) {
-//                    $q->orWhere($field, 'like', '%' . $request->search . '%');
-//                }
-//            });
-//        }
-//
-//        $sortBy = $request->get('sort_by', 'created_at');
-//        $sortDirection = $request->get('sort_direction', 'desc');
-//        $query->orderBy($sortBy, $sortDirection);
-//
-//        $items = $query->paginate(
-//            perPage: $request->get('per_page', 10),
-//            page: $request->get('page', 1)
-//        )->withQueryString();
-//
-//        $relatedOptions = $this->getRelatedOptions($modelInstance);
-//
-//        return Inertia::render('GenericModelPage', [
-//            'model' => Str::singular(Str::studly($model)),
-//            'items' => $items,
-//            'filters' => [
-//                'search' => $request->search,
-//                'sort_by' => $sortBy,
-//                'sort_direction' => $sortDirection,
-//                'per_page' => $request->get('per_page', 10),
-//                'open_id' => $request->get('open_id')
-//            ],
-//            'fkMap' => $this->getForeignKeyMap($modelInstance),
-//            'relatedOptions' => $relatedOptions,
-//        ]);
-//    }
-//
-//    public function destroy(string $model, string $id)
-//    {
-//        $modelClass = $this->getModelClass($model);
-//        if (!$modelClass) {
-//            abort(404, 'Model not found.');
-//        }
-//
-//        $item = $modelClass::findOrFail($id);
-//        $item->delete();
-//
-//        return redirect()->route('generic.index', ['model' => $model])
-//            ->with('success', Str::singular($model) . ' deleted successfully.');
-//    }
-//}
Index: app/Models/Order.php
===================================================================
--- app/Models/Order.php	(revision 118d88fce4f1e1e88092c991a75f3b9bb10e6975)
+++ app/Models/Order.php	(revision f003a24e7d1eb472814b53616f73c655cfa87efa)
@@ -58,5 +58,5 @@
     public function transport(): BelongsTo
     {
-        return $this->belongsTo(Transport::class);
+        return $this->belongsTo(Transport::class, 'transport_id');
     }
 
@@ -65,12 +65,4 @@
         return $this->hasOne(Invoice::class);
     }
-
-    //ova ne mi treba deka ide kroz batches ne products
-//    public function products(): BelongsToMany
-//    {
-//        return $this->belongsToMany(Product::class, 'order_products')
-//            ->withPivot('quantity', 'price_per_unit', 'total_price')
-//            ->withTimestamps();
-//    }
 
     public function batches(): BelongsToMany
Index: resources/js/Pages/GenericModelPage.vue
===================================================================
--- resources/js/Pages/GenericModelPage.vue	(revision 118d88fce4f1e1e88092c991a75f3b9bb10e6975)
+++ resources/js/Pages/GenericModelPage.vue	(revision f003a24e7d1eb472814b53616f73c655cfa87efa)
@@ -2,4 +2,6 @@
 import App from '@/Layout/App.vue';
 import { Button } from '@/components/ui/button';
+import { Calendar } from '@/components/ui/calendar';
+import { Checkbox } from '@/components/ui/checkbox';
 import {
     Dialog,
@@ -12,4 +14,9 @@
 import { Label } from '@/components/ui/label';
 import {
+    Popover,
+    PopoverContent,
+    PopoverTrigger,
+} from '@/components/ui/popover';
+import {
     Select,
     SelectContent,
@@ -18,12 +25,4 @@
     SelectValue,
 } from '@/components/ui/select';
-import { Calendar } from '@/components/ui/calendar';
-import {
-    Popover,
-    PopoverContent,
-    PopoverTrigger,
-} from '@/components/ui/popover';
-import { CalendarIcon } from 'lucide-vue-next'
-import { format } from 'date-fns'
 import {
     Table,
@@ -34,7 +33,10 @@
     TableRow,
 } from '@/components/ui/table';
+import { formatLabel } from '@/lib/utils';
 import { router } from '@inertiajs/vue3';
+import { format } from 'date-fns';
 import { debounce } from 'lodash-es';
 import {
+    CalendarIcon,
     ChevronLeft,
     ChevronRight,
@@ -44,6 +46,4 @@
 } from 'lucide-vue-next';
 import { computed, reactive, ref, watch } from 'vue';
-//import {Textarea} from '@/components/ui/textarea';
-import { formatLabel } from '@/lib/utils';
 
 interface PaginatedData {
@@ -96,142 +96,5 @@
 const perPage = ref(props.filters.per_page);
 
-// Dynamic Fields: This is the core of the generic page
-const fields = computed(() => {
-    if (!props.items.data.length) return [];
-    const allFields = Object.keys(props.items.data[0]);
-    console.log('🔍 All fields from data:', allFields);
-    console.log('🔍 First item data structure:', props.items.data[0]);
-    return allFields;
-});
-
-const foreignKeyMap = computed(() => {
-    const fkMap: Record<string, string> = {
-        product_id: 'products', // Foreign key pointing to `products`
-        buyer_id: 'clients', // Foreign key pointing to `clients`
-        receiver_id: 'clients', // Foreign key pointing to `clients`
-        transport_id: 'transports', // Foreign key pointing to `transports`
-        producer_id: 'producers', // Foreign key pointing to `producers`
-        order_id: 'orders', // Foreign key pointing to `orders`
-        payment_id: 'payments', // Foreign key pointing to `payments`
-    };
-    return fkMap;
-});
-
-// Helper to check if a field is a foreign key
-const isForeignKey = (field: string): boolean => {
-    return field.endsWith('_id') && foreignKeyMap.value[field] !== undefined;
-};
-
-// Helper to get the related model name for display
-// const getRelatedModelName = (item: any, field: string): string => {
-//     const fkInfo = foreignKeyMap.value[field];
-//     if (!fkInfo) return item[field] || 'N/A';
-//
-//     // Check if the related data is loaded (assuming eager loading)
-//     const relationName = field.replace('_id', '');
-//     if (item[relationName] && item[relationName].name) {
-//         return item[relationName].name;
-//     }
-//
-//     // For orders or other models without names, show the ID
-//     if (fkInfo.nameField === 'id') {
-//         return item[field] || 'N/A';
-//     }
-//
-//     // Fallback to the foreign key value
-//     return item[field] || 'N/A';
-// };
-
-// Fixed helper to get the related model name for display
-const getRelatedModelName = (item: any, field: string): string => {
-    const relationName = field.replace('_id', '');
-
-    // Check if the related data is loaded (assuming eager loading)
-    if (item[relationName] && item[relationName].name) {
-        return item[relationName].name; // This returns the name if available
-    }
-
-    // Check if the related data has an id but no name
-    if (item[relationName] && item[relationName].id) {
-        return `#${item[relationName].id}`; // This returns the ID with a hash prefix
-    }
-
-    // Fallback to the foreign key value
-    return item[field] ? item[field].toString() : 'N/A';
-};
-
-// Helper to navigate to the related model
-const navigateToRelatedModel = (field: string, value: any) => {
-    const fkTable = foreignKeyMap.value[field];
-    if (!fkTable) return;
-
-    const targetId = typeof value === 'object' ? value.id : value;
-    if (!targetId) return;
-
-    router.get(`/${fkTable}`, {
-        open_id: targetId,
-    });
-};
-
-// Watch for search changes
-const debouncedSearch = debounce((value: string) => {
-    router.get(
-        `/${props.model.toLowerCase()}s`,
-        {
-            search: value,
-            per_page: perPage.value,
-        },
-        {
-            preserveState: true,
-            replace: true,
-        },
-    );
-}, 300);
-
-watch(search, (newValue) => {
-    debouncedSearch(newValue);
-});
-
-// Watch for changes per page
-watch(perPage, (newValue) => {
-    router.get(
-        `/${props.model.toLowerCase()}s`,
-        {
-            search: search.value,
-            per_page: newValue,
-            page: 1, // Reset to the first page
-        },
-        {
-            preserveState: true,
-            replace: true,
-        },
-    );
-});
-
-// Pagination functions
-const goToPage = (page: number) => {
-    router.get(
-        `/${props.model.toLowerCase()}s`,
-        {
-            search: search.value,
-            per_page: perPage.value,
-            page,
-        },
-        {
-            preserveState: true,
-        },
-    );
-};
-
-const goToFirstPage = () => goToPage(1);
-const goToLastPage = () => goToPage(props.items.last_page);
-const goToPreviousPage = () => goToPage(props.items.current_page - 1);
-const goToNextPage = () => goToPage(props.items.current_page + 1);
-
-// Helper functions
-const canGoPrevious = () => props.items.current_page > 1;
-const canGoNext = () => props.items.current_page < props.items.last_page;
-
-// Expanded rows - check for open_id from URL
+// Expanded rows
 const expandedRows = ref(new Set<string>());
 
@@ -241,145 +104,24 @@
 }
 
-// const toggleRowExpansion = (itemId: string) => {
-//     if (expandedRows.value.has(itemId)) {
-//         expandedRows.value.delete(itemId);
-//     } else {
-//         expandedRows.value.add(itemId);
-//     }
-// };
-
-const toggleRowExpansion = (itemId: string) => {
-    if (expandedRows.value.has(itemId)) {
-        expandedRows.value.delete(itemId);
-    } else {
-        expandedRows.value.add(itemId);
-
-        // Debug the item being expanded
-        const item = props.items.data.find((i) => i.id === itemId);
-        console.log('🔍 Expanding item:', item);
-        console.log('🔍 Item keys:', Object.keys(item));
-
-        // Check specifically for producer-related fields
-        Object.keys(item).forEach((key) => {
-            if (key.toLowerCase().includes('producer')) {
-                console.log(
-                    `🔍 Producer-related field "${key}":`,
-                    typeof item[key],
-                    item[key],
-                );
-            }
-        });
-    }
-};
-
-// Utility to convert camelCase back to snake_case
-// const toSnakeCase = (str: string) =>
-//     str.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
-
-// const transformKeysToSnakeCase = (form: Record<string, any>) => {
-//     const result: Record<string, any> = {};
-//     for (const key in form) {
-//         result[toSnakeCase(key)] = form[key];
-//     }
-//     return result;
-// };
-
-// Submit create form
-// const submitCreate = () => {
-//     console.log('CreateForm payload:', createForm);
-//     router.post(`/${props.model.toLowerCase()}s`, createForm, {
-//         onSuccess: () => {
-//             createDialogOpen.value = false;
-//             resetCreateForm();
-//         },
-//     });
-// };
-const submitCreate = () => {
-    console.log('CreateForm payload:', createForm);
-
-    router.post(`/${props.model.toLowerCase()}s`, createForm, {
-        onSuccess: (page) => {
-            createDialogOpen.value = false;
-            resetCreateForm();
-        },
-        onError: (errors) => {
-            console.error('Create failed:', errors);
-            // Handle validation errors here
-        },
-        preserveState: false, // This helps with state refresh
-    });
-};
-
-// Submit edit form
-// const submitEdit = () => {
-//     if (!currentEditItem.value) return;
-//
-//     router.put(
-//         `/${props.model.toLowerCase()}s/${currentEditItem.value.id}`,
-//         editForm,
-//         {
-//             onSuccess: () => {
-//                 editDialogOpen.value = false;
-//                 currentEditItem.value = null;
-//             },
-//         },
-//     );
-// };
-
-const submitEdit = () => {
-    if (!currentEditItem.value) return;
-
-    router.put(
-        `/${props.model.toLowerCase()}s/${currentEditItem.value.id}`,
-        editForm,
-        {
-            onSuccess: (page) => {
-                editDialogOpen.value = false;
-                currentEditItem.value = null;
-                // Clear the edit form
-                Object.keys(editForm).forEach((key) => delete editForm[key]);
-            },
-            onError: (errors) => {
-                console.error('Update failed:', errors);
-            },
-            preserveState: false,
-        },
-    );
-};
-
-// Delete item
-const deleteItem = (item: any) => {
-    if (confirm(`Are you sure you want to delete this ${props.model}?`)) {
-        router.delete(`/${props.model.toLowerCase()}s/${item.id}`, {
-            preserveScroll: true,
-        });
-    }
-};
-
-const formatValue = (value: any, field?: string) => {
-    if (value === null || value === undefined) {
-        return 'N/A';
-    }
-    if (typeof value === 'boolean') {
-        return value ? 'Yes' : 'No';
-    }
-    if (typeof value === 'number') {
-        return value.toFixed(2);
-    }
-
-    if (typeof value === 'object') {
-        return value.name || value.id || 'N/A';
-    }
-
-    if (typeof value === 'string' && /^\d{4}-\d{2}-\d{2}/.test(value)) {
-        const date = new Date(value);
-        if (!isNaN(date.getTime())) {
-            return date.toLocaleDateString();
-        }
-    }
-    return value;
-};
-
-// Enhanced table fields that handle foreign keys
+// Computed properties
+const fields = computed(() => {
+    if (!props.items.data.length) return [];
+    return Object.keys(props.items.data[0]);
+});
+
+type ForeignKeyMap = {
+    [key: string]: string;
+};
+
+const foreignKeyMap = computed<ForeignKeyMap>(() => ({
+    product_id: 'products',
+    buyer_id: 'clients',
+    receiver_id: 'clients',
+    transport_id: 'transports',
+    producer_id: 'producers',
+    order_id: 'orders',
+    payment_id: 'payments',
+}));
+
 const tableFields = computed(() => {
     return fields.value.filter(
@@ -390,35 +132,8 @@
 });
 
-// Use this computed property to define which fields to show in the detailed view and forms
-// const detailFields = computed(() => {
-//     return fields.value.filter(
-//         (field) => !['id', 'created_at', 'updated_at', 'buyer', 'transport', 'receiver'].includes(field),
-//     );
-// });
-
-// const detailFields = computed(() => {
-//     const filtered = fields.value.filter(
-//         (field) => !['id', 'created_at', 'updated_at', 'buyer', 'transport', 'receiver'].includes(field),
-//     );
-//     console.log('🔍 Detail fields after filtering:', filtered);
-//
-//     // Let's also see what each field contains
-//     if (props.items.data.length > 0) {
-//         filtered.forEach(field => {
-//             const value = props.items.data[0][field];
-//             console.log(`🔍 Field "${field}":`, typeof value, value);
-//         });
-//     }
-//
-//     return filtered;
-// });
-
 const detailFields = computed(() => {
     return fields.value.filter((field) => {
-        // Exclude basic fields we don't want to show
         if (['id', 'created_at', 'updated_at'].includes(field)) return false;
 
-        // Exclude relationship objects (keep only foreign keys ending with _id)
-        // This will exclude the 'producer' object but keep 'producer_id'
         if (props.items.data.length > 0) {
             const value = props.items.data[0][field];
@@ -431,109 +146,119 @@
             }
         }
-
         return true;
     });
 });
 
-const descriptionFields = [
-    'description',
-    'status',
-    'insurance_conditions',
-    'notes',
-];
-
-// returns the first description field if available
 const dialogDescription = computed(() => {
+    const descriptionFields = [
+        'description',
+        'status',
+        'insurance_conditions',
+        'notes',
+    ];
     const hasDescription = detailFields.value.some((f) =>
         descriptionFields.includes(f),
     );
-    if (hasDescription) {
-        return `Please fill in all required fields including the description.`;
+
+    return hasDescription
+        ? `Please fill in all required fields including the description.`
+        : `Fill in the details to create a new ${props.model}.`;
+});
+
+// Helper functions
+const isForeignKey = (field: string): boolean => {
+    return (
+        field.endsWith('_id') &&
+        (foreignKeyMap.value as any)[field] !== undefined
+    );
+};
+
+const getRelatedModelName = (item: any, field: string): string => {
+    const relationName = field.replace('_id', '');
+
+    if (item[relationName]?.name) {
+        return item[relationName].name;
     }
-    return `Fill in the details to create a new ${props.model}.`;
-});
-
-// const getFieldType = (
-//     field: string,
-// ): 'boolean' | 'date' | 'number' | 'foreignKey' | 'string' => {
-//     if (isForeignKey(field)) {
-//         return 'foreignKey';
-//     }
-//     if (props.items.data.length === 0) return 'string';
-//
-//     const value = props.items.data[0][field];
-//
-//     if (typeof value === 'boolean') {
-//         return 'boolean';
-//     }
-//     if (typeof value === 'number') {
-//         return 'number';
-//     }
-//     if (typeof value === 'string' && /^\d{4}-\d{2}-\d{2}/.test(value)) {
-//         return 'date';
-//     }
-//
-//     return 'string';
-// };
-const getFieldType = (field: string): 'boolean' | 'date' | 'number' | 'foreignKey' | 'string' => {
-    if (isForeignKey(field)) {
-        return 'foreignKey';
+
+    if (item[relationName]?.id) {
+        return `#${item[relationName].id}`;
     }
+
+    return item[field] ? item[field].toString() : 'N/A';
+};
+
+const navigateToRelatedModel = (field: string, value: any) => {
+    const fkTable = (foreignKeyMap.value as any)[field];
+    if (!fkTable) return;
+
+    const targetId = typeof value === 'object' ? value.id : value;
+    if (!targetId) return;
+
+    router.get(`/${fkTable}`, { open_id: targetId });
+};
+
+const getFieldType = (
+    field: string,
+): 'boolean' | 'date' | 'number' | 'foreignKey' | 'string' => {
+    if (isForeignKey(field)) return 'foreignKey';
     if (props.items.data.length === 0) return 'string';
 
     const value = props.items.data[0][field];
 
-    if (typeof value === 'boolean') {
-        return 'boolean';
+    if (typeof value === 'boolean') return 'boolean';
+    if (typeof value === 'number') return 'number';
+    if (typeof value === 'string' && /^\d{4}-\d{2}-\d{2}/.test(value))
+        return 'date';
+
+    return 'string';
+};
+
+const formatValue = (value: any): string => {
+    if (value === null || value === undefined) return 'N/A';
+    if (typeof value === 'boolean') return value ? 'Yes' : 'No';
+    if (typeof value === 'number') return value.toFixed(2);
+    if (typeof value === 'object') return value.name || value.id || 'N/A';
+    if (typeof value === 'string' && /^\d{4}-\d{2}-\d{2}/.test(value)) {
+        const date = new Date(value);
+        return !isNaN(date.getTime()) ? date.toLocaleDateString() : value;
     }
-    if (typeof value === 'number') {
-        return 'number';
-    }
-    if (typeof value === 'string' && /^\d{4}-\d{2}-\d{2}/.test(value)) {
-        return 'date';
-    }
-
-    return 'string';
-};
-
-const formatDateForInput = (val: any) => {
+    return value;
+};
+
+const formatDateForInput = (val: any): string => {
     if (!val) return '';
     const d = new Date(val);
-    if (isNaN(d.getTime())) return '';
-    return d.toISOString().slice(0, 10);
-};
-
-// const resetCreateForm = () => {
-//   Object.keys(createForm).forEach(key => delete createForm[key]);
-//   detailFields.value.forEach(field => {
-//     const camel = toCamelCase(field);
-//     if (getFieldType(field) === 'boolean') {
-//       createForm[camel] = false;
-//     } else if (getFieldType(field) === 'date') {
-//       createForm[camel] = '';
-//     } else {
-//       createForm[camel] = '';
-//     }
-//   });
-// };
-
-// const resetCreateForm = () => {
-//     Object.keys(createForm).forEach((key) => delete createForm[key]);
-//     detailFields.value.forEach((field) => {
-//         if (getFieldType(field) === 'boolean') {
-//             createForm[field] = false;
-//         } else if (getFieldType(field) === 'date') {
-//             createForm[field] = '';
-//         } else {
-//             createForm[field] = '';
-//         }
-//     });
-// };
-
+    return isNaN(d.getTime()) ? '' : d.toISOString().slice(0, 10);
+};
+
+const isDateField = (field: string): boolean => {
+    return /date$/i.test(field);
+};
+
+const formatDateForSubmit = (date: any): string => {
+    if (!date) return '';
+
+    // If it's a Date object
+    if (date instanceof Date) {
+        return date.toISOString().split('T')[0]; // YYYY-MM-DD
+    }
+
+    // If it's an array from calendar, take first element
+    if (Array.isArray(date) && date.length > 0) {
+        const firstDate = date[0];
+        if (firstDate instanceof Date) {
+            return firstDate.toISOString().split('T')[0];
+        }
+        return String(firstDate);
+    }
+
+    // If it's already a string, return as-is (assuming it's already YYYY-MM-DD)
+    return String(date);
+};
+
+// Form management
 const resetCreateForm = () => {
-    // Clear existing form data
     Object.keys(createForm).forEach((key) => delete createForm[key]);
 
-    // Initialize form with default values
     detailFields.value.forEach((field) => {
         const fieldType = getFieldType(field);
@@ -549,5 +274,5 @@
                 break;
             case 'foreignKey':
-                createForm[field] = null; // Use null instead of empty string
+                createForm[field] = null;
                 break;
             default:
@@ -557,47 +282,9 @@
 };
 
-resetCreateForm();
-
-// const openEditDialog = (item: any) => {
-//   currentEditItem.value = item;
-//   Object.keys(editForm).forEach(key => delete editForm[key]);
-//
-//   for (const field of detailFields.value) {
-//     const camel = toCamelCase(field);
-//     if (getFieldType(field) === 'date') {
-//       editForm[camel] = formatDateForInput(item[field]);
-//     } else if (getFieldType(field) === 'boolean') {
-//       editForm[camel] = Boolean(item[field]);
-//     } else {
-//       editForm[camel] = item[field];
-//     }
-//   }
-//   editDialogOpen.value = true;
-// };
-
-// const openEditDialog = (item: any) => {
-//     currentEditItem.value = item;
-//     Object.keys(editForm).forEach((key) => delete editForm[key]);
-//
-//     for (const field of detailFields.value) {
-//         if (getFieldType(field) === 'date') {
-//             editForm[field] = formatDateForInput(item[field]);
-//         } else if (getFieldType(field) === 'boolean') {
-//             editForm[field] = Boolean(item[field]);
-//         } else {
-//             editForm[field] = item[field];
-//         }
-//     }
-//     editDialogOpen.value = true;
-// };
-
 const openEditDialog = (item: any) => {
     currentEditItem.value = item;
-
-    // Clear existing form data
     Object.keys(editForm).forEach((key) => delete editForm[key]);
 
-    // Populate form with item data
-    for (const field of detailFields.value) {
+    detailFields.value.forEach((field) => {
         const fieldType = getFieldType(field);
         switch (fieldType) {
@@ -609,5 +296,4 @@
                 break;
             case 'foreignKey':
-                // Handle foreign key values properly
                 editForm[field] = item[field] || null;
                 break;
@@ -615,8 +301,125 @@
                 editForm[field] = item[field] || '';
         }
+    });
+
+    editDialogOpen.value = true;
+};
+
+// Initialize create form
+resetCreateForm();
+
+// Row expansion
+const toggleRowExpansion = (itemId: string) => {
+    if (expandedRows.value.has(itemId)) {
+        expandedRows.value.delete(itemId);
+    } else {
+        expandedRows.value.add(itemId);
     }
-
-    console.log('Edit form populated:', editForm);
-    editDialogOpen.value = true;
+};
+
+// Search and pagination
+const debouncedSearch = debounce((value: string) => {
+    router.get(
+        `/${props.model.toLowerCase()}s`,
+        { search: value, per_page: perPage.value },
+        { preserveState: true, replace: true },
+    );
+}, 300);
+
+watch(search, debouncedSearch);
+
+watch(perPage, (newValue) => {
+    router.get(
+        `/${props.model.toLowerCase()}s`,
+        { search: search.value, per_page: newValue, page: 1 },
+        { preserveState: true, replace: true },
+    );
+});
+
+// Pagination functions
+const goToPage = (page: number) => {
+    router.get(
+        `/${props.model.toLowerCase()}s`,
+        { search: search.value, per_page: perPage.value, page },
+        { preserveState: true },
+    );
+};
+
+const goToFirstPage = () => goToPage(1);
+const goToLastPage = () => goToPage(props.items.last_page);
+const goToPreviousPage = () => goToPage(props.items.current_page - 1);
+const goToNextPage = () => goToPage(props.items.current_page + 1);
+
+const canGoPrevious = computed(() => props.items.current_page > 1);
+const canGoNext = computed(
+    () => props.items.current_page < props.items.last_page,
+);
+
+// Form submissions
+const submitCreate = () => {
+    const payload: Record<string, any> = {};
+
+    // Convert all form data, handling dates specifically
+    Object.keys(createForm).forEach(key => {
+        const value = createForm[key];
+        const fieldType = getFieldType(key);
+
+        if (fieldType === 'date') {
+            payload[key] = formatDateForSubmit(value);
+        } else {
+            payload[key] = value;
+        }
+    });
+
+    console.log('CreateForm payload with normalized dates:', payload);
+    router.post(`/${props.model.toLowerCase()}s`, payload, {
+        onSuccess: () => {
+            createDialogOpen.value = false;
+            resetCreateForm();
+        },
+        onError: (errors) => console.error('Create failed:', errors),
+        preserveState: false,
+    });
+};
+
+const submitEdit = () => {
+    if (!currentEditItem.value) return;
+
+    const payload: Record<string, any> = {};
+
+    // Convert all form data, handling dates specifically
+    Object.keys(editForm).forEach(key => {
+        const value = editForm[key];
+        const fieldType = getFieldType(key);
+
+        if (fieldType === 'date') {
+            payload[key] = formatDateForSubmit(value);
+        } else {
+            payload[key] = value;
+        }
+    });
+
+    console.log('EditForm payload with normalized dates:', payload);
+    router.put(
+        `/${props.model.toLowerCase()}s/${currentEditItem.value.id}`,
+        payload,
+        {
+            onSuccess: () => {
+                editDialogOpen.value = false;
+                currentEditItem.value = null;
+                Object.keys(editForm).forEach(key => delete editForm[key]);
+            },
+            onError: (errors) => console.error('Update failed:', errors),
+            preserveState: false,
+        },
+    );
+};
+
+const deleteItem = (item: any) => {
+    if (confirm(`Are you sure you want to delete this ${props.model}?`)) {
+        router.delete(`/${props.model.toLowerCase()}s/${item.id}`, {
+            preserveScroll: true,
+        });
+    }
 };
 </script>
@@ -664,7 +467,7 @@
                         </SelectContent>
                     </Select>
-                    <Button @click="createDialogOpen = true"
-                        >Create {{ model }}</Button
-                    >
+                    <Button @click="createDialogOpen = true">
+                        Create {{ model }}
+                    </Button>
                 </div>
 
@@ -701,5 +504,4 @@
                                         class="max-w-[200px] truncate overflow-hidden font-medium whitespace-nowrap"
                                     >
-                                        <!-- Handle foreign keys with clickable links -->
                                         <template
                                             v-if="
@@ -726,9 +528,6 @@
                                             </span>
                                         </template>
-                                        <!-- Handle regular fields -->
                                         <template v-else>
-                                            {{
-                                                formatValue(item[field], field)
-                                            }}
+                                            {{ formatValue(item[field]) }}
                                         </template>
                                     </TableCell>
@@ -790,6 +589,6 @@
                                                     :key="field"
                                                 >
-                                                    <strong
-                                                        >{{
+                                                    <strong>
+                                                        {{
                                                             formatLabel(
                                                                 field.replace(
@@ -798,7 +597,6 @@
                                                                 ),
                                                             )
-                                                        }}:</strong
-                                                    >
-                                                    <!-- Handle foreign keys in detail view -->
+                                                        }}:
+                                                    </strong>
                                                     <template
                                                         v-if="
@@ -832,5 +630,4 @@
                                                             formatValue(
                                                                 item[field],
-                                                                field,
                                                             )
                                                         }}
@@ -879,5 +676,5 @@
                         variant="outline"
                         size="sm"
-                        :disabled="!canGoPrevious()"
+                        :disabled="!canGoPrevious"
                         @click="goToFirstPage"
                     >
@@ -888,5 +685,5 @@
                         variant="outline"
                         size="sm"
-                        :disabled="!canGoPrevious()"
+                        :disabled="!canGoPrevious"
                         @click="goToPreviousPage"
                     >
@@ -897,5 +694,5 @@
                         variant="outline"
                         size="sm"
-                        :disabled="!canGoNext()"
+                        :disabled="!canGoNext"
                         @click="goToNextPage"
                     >
@@ -906,5 +703,5 @@
                         variant="outline"
                         size="sm"
-                        :disabled="!canGoNext()"
+                        :disabled="!canGoNext"
                         @click="goToLastPage"
                     >
@@ -916,4 +713,5 @@
         </div>
 
+        <!-- Create Dialog -->
         <Dialog v-model:open="createDialogOpen">
             <DialogContent class="aria-dialog-description sm:max-w-3xl">
@@ -933,9 +731,9 @@
                         class="space-y-2"
                     >
-                        <Label :for="field">{{
-                            formatLabel(field.replace('_id', ''))
-                        }}</Label>
-
-                        <!-- Dynamic input types for create form -->
+                        <Label :for="field">
+                            {{ formatLabel(field.replace('_id', '')) }}
+                        </Label>
+
+                        <!-- Dynamic form fields -->
                         <div v-if="getFieldType(field) === 'foreignKey'">
                             <Select
@@ -961,10 +759,4 @@
 
                         <div v-else-if="getFieldType(field) === 'boolean'">
-<!--                            <input-->
-<!--                                type="checkbox"-->
-<!--                                :id="field"-->
-<!--                                v-model="createForm[field]"-->
-<!--                                class="checkbox"-->
-<!--                            />-->
                             <Checkbox
                                 :id="field"
@@ -973,21 +765,28 @@
                         </div>
 
-<!--                        <div v-else-if="getFieldType(field) === 'date'">-->
-<!--                            <input-->
-<!--                                type="date"-->
-<!--                                :id="field"-->
-<!--                                v-model="createForm[field]"-->
-<!--                                class="input"-->
-<!--                            />-->
-<!--                        </div>-->
                         <div v-else-if="getFieldType(field) === 'date'">
                             <Popover>
                                 <PopoverTrigger as-child>
-                                    <Button variant="outline" class="w-full justify-start text-left font-normal">
+                                    <Button
+                                        variant="outline"
+                                        class="w-full justify-start text-left font-normal"
+                                    >
                                         <CalendarIcon class="mr-2 h-4 w-4" />
-                                        {{ createForm[field] ? format(new Date(createForm[field]), 'PPP') : 'Pick a date' }}
+                                        {{
+                                            createForm[field]
+                                                ? format(
+                                                      new Date(
+                                                          createForm[field],
+                                                      ),
+                                                      'PPP',
+                                                  )
+                                                : 'Pick a date'
+                                        }}
                                     </Button>
                                 </PopoverTrigger>
-                                <PopoverContent class="w-auto p-0" align="start">
+                                <PopoverContent
+                                    class="w-auto p-0"
+                                    align="start"
+                                >
                                     <Calendar
                                         v-model="createForm[field]"
@@ -1000,10 +799,4 @@
 
                         <div v-else-if="getFieldType(field) === 'number'">
-<!--                            <input-->
-<!--                                type="number"-->
-<!--                                :id="field"-->
-<!--                                v-model.number="createForm[field]"-->
-<!--                                class="input"-->
-<!--                            />-->
                             <Input
                                 type="number"
@@ -1019,10 +812,10 @@
                 </div>
                 <DialogFooter>
-                    <Button variant="outline" @click="createDialogOpen = false"
-                        >Cancel</Button
-                    >
-                    <Button type="submit" @click="submitCreate"
-                        >Create {{ model }}</Button
-                    >
+                    <Button variant="outline" @click="createDialogOpen = false">
+                        Cancel
+                    </Button>
+                    <Button type="submit" @click="submitCreate">
+                        Create {{ model }}
+                    </Button>
                 </DialogFooter>
             </DialogContent>
@@ -1047,9 +840,9 @@
                         class="space-y-2"
                     >
-                        <Label :for="`edit_${field}`">{{
-                            formatLabel(field.replace('_id', ''))
-                        }}</Label>
-
-                        <!-- Dynamic input types for edit form -->
+                        <Label :for="`edit_${field}`">
+                            {{ formatLabel(field.replace('_id', '')) }}
+                        </Label>
+
+                        <!-- Dynamic form fields -->
                         <div v-if="getFieldType(field) === 'foreignKey'">
                             <Select
@@ -1075,10 +868,4 @@
 
                         <div v-else-if="getFieldType(field) === 'boolean'">
-<!--                            <input-->
-<!--                                type="checkbox"-->
-<!--                                :id="`edit_${field}`"-->
-<!--                                v-model="editForm[field]"-->
-<!--                                class="checkbox"-->
-<!--                            />-->
                             <Checkbox
                                 :id="`edit_${field}`"
@@ -1087,21 +874,26 @@
                         </div>
 
-<!--                        <div v-else-if="getFieldType(field) === 'date'">-->
-<!--                            <input-->
-<!--                                type="date"-->
-<!--                                :id="`edit_${field}`"-->
-<!--                                v-model="editForm[field]"-->
-<!--                                class="input"-->
-<!--                            />-->
-<!--                        </div>-->
                         <div v-else-if="getFieldType(field) === 'date'">
                             <Popover>
                                 <PopoverTrigger as-child>
-                                    <Button variant="outline" class="w-full justify-start text-left font-normal">
+                                    <Button
+                                        variant="outline"
+                                        class="w-full justify-start text-left font-normal"
+                                    >
                                         <CalendarIcon class="mr-2 h-4 w-4" />
-                                        {{ editForm[field] ? format(new Date(editForm[field]), 'PPP') : 'Pick a date' }}
+                                        {{
+                                            editForm[field]
+                                                ? format(
+                                                      new Date(editForm[field]),
+                                                      'PPP',
+                                                  )
+                                                : 'Pick a date'
+                                        }}
                                     </Button>
                                 </PopoverTrigger>
-                                <PopoverContent class="w-auto p-0" align="start">
+                                <PopoverContent
+                                    class="w-auto p-0"
+                                    align="start"
+                                >
                                     <Calendar
                                         v-model="editForm[field]"
@@ -1114,16 +906,9 @@
 
                         <div v-else-if="getFieldType(field) === 'number'">
-<!--                            <input-->
-<!--                                type="number"-->
-<!--                                :id="`edit_${field}`"-->
-<!--                                v-model.number="editForm[field]"-->
-<!--                                class="input"-->
-<!--                            />-->
                             <Input
                                 type="number"
-                                :id="field"
-                                v-model.number="createForm[field]"
+                                :id="`edit_${field}`"
+                                v-model.number="editForm[field]"
                             />
-
                         </div>
 
@@ -1137,10 +922,10 @@
                 </div>
                 <DialogFooter>
-                    <Button variant="outline" @click="editDialogOpen = false"
-                        >Cancel</Button
-                    >
-                    <Button type="submit" @click="submitEdit"
-                        >Save Changes</Button
-                    >
+                    <Button variant="outline" @click="editDialogOpen = false">
+                        Cancel
+                    </Button>
+                    <Button type="submit" @click="submitEdit">
+                        Save Changes
+                    </Button>
                 </DialogFooter>
             </DialogContent>
Index: resources/js/components/ui/checkbox/Checkbox.vue
===================================================================
--- resources/js/components/ui/checkbox/Checkbox.vue	(revision f003a24e7d1eb472814b53616f73c655cfa87efa)
+++ resources/js/components/ui/checkbox/Checkbox.vue	(revision f003a24e7d1eb472814b53616f73c655cfa87efa)
@@ -0,0 +1,34 @@
+<script setup lang="ts">
+import type { CheckboxRootEmits, CheckboxRootProps } from "reka-ui"
+import type { HTMLAttributes } from "vue"
+import { reactiveOmit } from "@vueuse/core"
+import { Check } from "lucide-vue-next"
+import { CheckboxIndicator, CheckboxRoot, useForwardPropsEmits } from "reka-ui"
+import { cn } from "@/lib/utils"
+
+const props = defineProps<CheckboxRootProps & { class?: HTMLAttributes["class"] }>()
+const emits = defineEmits<CheckboxRootEmits>()
+
+const delegatedProps = reactiveOmit(props, "class")
+
+const forwarded = useForwardPropsEmits(delegatedProps, emits)
+</script>
+
+<template>
+  <CheckboxRoot
+    data-slot="checkbox"
+    v-bind="forwarded"
+    :class="
+      cn('peer border-input data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground data-[state=checked]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive size-4 shrink-0 rounded-[4px] border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50',
+         props.class)"
+  >
+    <CheckboxIndicator
+      data-slot="checkbox-indicator"
+      class="flex items-center justify-center text-current transition-none"
+    >
+      <slot>
+        <Check class="size-3.5" />
+      </slot>
+    </CheckboxIndicator>
+  </CheckboxRoot>
+</template>
Index: resources/js/components/ui/checkbox/index.ts
===================================================================
--- resources/js/components/ui/checkbox/index.ts	(revision f003a24e7d1eb472814b53616f73c655cfa87efa)
+++ resources/js/components/ui/checkbox/index.ts	(revision f003a24e7d1eb472814b53616f73c655cfa87efa)
@@ -0,0 +1,1 @@
+export { default as Checkbox } from "./Checkbox.vue"
