# Feature Development Guide

This document outlines the standard structure and patterns to follow when implementing new features in this Laravel + Inertia.js + Vue 3 application.

## 📋 Table of Contents

- [Project Overview](#project-overview)
- [Standard Feature Structure](#standard-feature-structure)
- [Backend Components](#backend-components)
- [Frontend Components](#frontend-components)
- [Routes Configuration](#routes-configuration)
- [Naming Conventions](#naming-conventions)
- [Code Patterns](#code-patterns)
- [Best Practices](#best-practices)

---

## Project Overview

**Tech Stack:**
- **Backend**: Laravel 12 (PHP 8.2+), Session-based auth, Spatie permissions
- **Frontend**: Vue 3 + Vite + Tailwind CSS 4.0 + Inertia.js + Pinia (for UI state only)
- **Features**: Dark mode, i18n (EN/AR), RTL/LTR, DataTable trait
- **Database**: SQLite, queue system

**Architecture Pattern:**
- **Controllers**: HTTP handling only (thin controllers)
- **Services**: All business logic (fat services)
- **Requests**: Validation rules
- **Resources**: Data transformation for Inertia props
- **Frontend**: Inertia.js for server-driven rendering (no API calls)

---

## Standard Feature Structure

Every new feature/module requires the following components:

### Backend (4 Required Files)

1. **Controller** - `app/Http/Controllers/Web/{Admin|Client}/{Module}Controller.php`
2. **Service** - `app/Services/{Admin|Client}/{Module}Service.php`
3. **Request** - `app/Http/Requests/{Admin|Client}/Store{Module}Request.php` & `Update{Module}Request.php`
4. **Resource** - `app/Http/Resources/{Admin|Client}/{Module}Resource.php`

### Frontend (2+ Required Files)

1. **Index Page** - `resources/js/pages/Modules/{admin|client}/{Module}/{Module}Index.vue`
2. **Form Page** - `resources/js/pages/Modules/{admin|client}/{Module}/{Module}Form.vue`
3. **Additional Pages** - As needed (Detail, Show, etc.)

### Routes

- Add routes in `routes/web.php` with proper middleware and permissions

---

## Backend Components

### 1. Controller Structure

**Location**: `app/Http/Controllers/Web/{Admin|Client}/{Module}Controller.php`

**Pattern:**
```php
<?php

namespace App\Http\Controllers\Web\{Admin|Client};

use App\Http\Controllers\Controller;
use App\Http\Requests\{Admin|Client}\Store{Module}Request;
use App\Http\Requests\{Admin|Client}\Update{Module}Request;
use App\Http\Resources\{Admin|Client}\{Module}Resource;
use App\Services\{Admin|Client}\{Module}Service;
use App\Traits\HasDataTableInertia;
use App\Models\{Module};
use Illuminate\Http\Request;
use Illuminate\Http\RedirectResponse;
use Inertia\Inertia;
use Inertia\Response;

class {Module}Controller extends Controller
{
    use HasDataTableInertia;

    protected {Module}Service ${module}Service;

    public function __construct({Module}Service ${module}Service)
    {
        $this->{module}Service = ${module}Service;
    }

    /**
     * Display a listing of resources
     */
    public function index(Request $request): Response
    {
        return $this->inertiaDataTable(
            page: 'Modules/{admin|client}/{Module}/{Module}Index',
            query: {Module}::with(['relations'])->applyFilters($request->all()),
            request: $request,
            resource: {Module}Resource::class,
            additionalProps: [
                // Additional data to pass to frontend
                'options' => SomeModel::all(['id', 'name'])
            ]
        );
    }

    /**
     * Show the form for creating a new resource
     */
    public function create(): Response
    {
        return Inertia::render('Modules/{admin|client}/{Module}/{Module}Form', [
            // Pass any data needed for the form
            'options' => SomeModel::all(['id', 'name']),
        ]);
    }

    /**
     * Store a newly created resource
     */
    public function store(Store{Module}Request $request): RedirectResponse
    {
        try {
            $this->{module}Service->create{Module}($request->validated());

            return redirect()->route('{admin|client}.{modules}.index')
                ->with('success', __('{modules}.created'));
        } catch (\Exception $e) {
            return redirect()->back()
                ->withInput()
                ->withErrors(['error' => $e->getMessage()]);
        }
    }

    /**
     * Show the form for editing the specified resource
     */
    public function edit(int $id): Response
    {
        try {
            ${module} = $this->{module}Service->get{Module}ById($id);

            return Inertia::render('Modules/{admin|client}/{Module}/{Module}Form', [
                '{module}' => (new {Module}Resource(${module}))->resolve(),
                'options' => SomeModel::all(['id', 'name']),
            ]);
        } catch (\Exception $e) {
            abort(404, $e->getMessage());
        }
    }

    /**
     * Update the specified resource
     */
    public function update(Update{Module}Request $request, int $id): RedirectResponse
    {
        try {
            ${module} = $this->{module}Service->update{Module}($id, $request->validated());

            return redirect()->route('{admin|client}.{modules}.index')
                ->with('success', __('{modules}.updated'));
        } catch (\Exception $e) {
            return redirect()->back()
                ->withInput()
                ->withErrors(['error' => $e->getMessage()]);
        }
    }

    /**
     * Remove the specified resource
     */
    public function destroy(int $id): RedirectResponse
    {
        try {
            $this->{module}Service->delete{Module}($id);

            return redirect()->back()
                ->with('success', __('{modules}.deleted'));
        } catch (\Exception $e) {
            return redirect()->back()
                ->withErrors(['error' => $e->getMessage()]);
        }
    }
}
```

**Key Points:**
- ✅ Use `HasDataTableInertia` trait for index method
- ✅ Inject Service via constructor
- ✅ Use `Inertia::render()` for create/edit
- ✅ Use `redirect()->route()` for store/update/destroy
- ✅ Wrap service calls in try-catch
- ✅ Return `Response` type for render methods
- ✅ Return `RedirectResponse` type for redirect methods
- ✅ **Use `HasMiddleware` interface for permission management** (see below)

---

### 1.1 Permission Middleware Pattern (Modern Laravel Approach)

**IMPORTANT**: As of Laravel 11+, the recommended way to handle permissions is using the `HasMiddleware` interface directly in controllers, NOT in routes.

**Pattern:**
```php
<?php

namespace App\Http\Controllers\Web\{Admin|Client};

use App\Http\Controllers\Controller;
use Illuminate\Routing\Controllers\HasMiddleware;
use Illuminate\Routing\Controllers\Middleware;

class {Module}Controller extends Controller implements HasMiddleware
{
    use HasDataTableInertia;

    /**
     * Define middleware for this controller
     */
    public static function middleware(): array
    {
        return [
            'auth',
            new Middleware('permission:{modules}.view', only: ['index', 'show']),
            new Middleware('permission:{modules}.create', only: ['create', 'store']),
            new Middleware('permission:{modules}.edit', only: ['edit', 'update']),
            new Middleware('permission:{modules}.delete', only: ['destroy']),
        ];
    }

    public function __construct({Module}Service ${module}Service)
    {
        $this->{module}Service = ${module}Service;
    }

    // ... rest of controller methods
}
```

**Routes Configuration (Simplified):**
```php
// routes/web.php

// ❌ OLD WAY (Don't do this anymore)
Route::middleware('permission:users.view')->group(function () {
    Route::resource('users', UserController::class)->middleware([
        'index' => 'permission:users.view',
        'create' => 'permission:users.create',
        // ... redundant middleware
    ]);
});

// ✅ NEW WAY (Clean and simple)
Route::resource('users', UserController::class);
Route::post('users/{id}/toggle-status', [UserController::class, 'toggleStatus'])
    ->name('users.toggle-status');
```

**Permission Naming Convention:**
```
{module}.{action}

Examples:
- users.view
- users.create
- users.edit
- users.delete
- clients.credentials.create
- clients.data.edit
- tasks.assign
- all_users_tasks (special permission)
```

**Benefits:**
- ✅ **Centralized**: All permissions defined in one place (controller)
- ✅ **Type-safe**: Uses modern PHP 8+ attributes
- ✅ **Cleaner routes**: No duplicate permission checks
- ✅ **Easier maintenance**: Update permissions in controller, not routes
- ✅ **Better organization**: Permissions live with the code they protect

**Common Permission Patterns:**

1. **Standard CRUD:**
```php
new Middleware('permission:{modules}.view', only: ['index', 'show']),
new Middleware('permission:{modules}.create', only: ['create', 'store']),
new Middleware('permission:{modules}.edit', only: ['edit', 'update']),
new Middleware('permission:{modules}.delete', only: ['destroy']),
```

2. **With Custom Actions:**
```php
new Middleware('permission:{modules}.view', only: ['index', 'show', 'export', 'print']),
new Middleware('permission:{modules}.edit', only: ['edit', 'update', 'toggleStatus', 'reorder']),
```

3. **Nested Permissions (e.g., Client Credentials):**
```php
new Middleware('permission:clients.credentials.create', only: ['storeCredential']),
new Middleware('permission:clients.credentials.edit', only: ['updateCredential']),
new Middleware('permission:clients.credentials.delete', only: ['destroyCredential']),
```

**Frontend Permission Checks:**

In Vue components, check permissions using the `hasPermission` helper:

```vue
<template>
    <!-- Show button only if user has permission -->
    <Link 
        href="/clients/create" 
        v-if="hasPermission('clients.create')"
        :prefetch="false"
    >
        <Button variant="primary">
            {{ $t('clients.addNew') }}
        </Button>
    </Link>

    <!-- Show edit button -->
    <button 
        v-if="hasPermission('clients.edit')"
        @click="editClient(client)"
    >
        {{ $t('common.edit') }}
    </button>
</template>

<script setup>
import { usePage } from '@inertiajs/vue3'

const page = usePage()

const hasPermission = (permission) => {
    return page.props.auth?.permissions?.includes(permission) || 
           page.props.auth?.user?.permissions?.includes(permission)
}
</script>
```

**IMPORTANT: Inertia Prefetching Issue**

When using `v-if="hasPermission()"` on `Link` components, add `:prefetch="false"` to prevent Inertia from prefetching routes the user doesn't have access to:

```vue
<!-- ❌ BAD: Will trigger 403 errors from prefetching -->
<Link href="/clients/create" v-if="hasPermission('clients.create')">
    Create Client
</Link>

<!-- ✅ GOOD: Prevents prefetching -->
<Link 
    href="/clients/create" 
    v-if="hasPermission('clients.create')"
    :prefetch="false"
>
    Create Client
</Link>
```

**Permission Seeder:**

Define all permissions in `database/seeders/RolesSeeder.php`:

```php
$permissions = [
    // Users
    'users.view', 'users.create', 'users.edit', 'users.delete',
    
    // Clients
    'clients.view', 'clients.create', 'clients.edit', 'clients.delete',
    'clients.credentials.view', 'clients.credentials.create', 
    'clients.credentials.edit', 'clients.credentials.delete',
    'clients.data.view', 'clients.data.create', 
    'clients.data.edit', 'clients.data.delete',
    
    // Special permissions
    'all_users_tasks', // View all users' tasks
    'all_users_reports', // View all users' reports
];

foreach ($permissions as $permission) {
    Permission::firstOrCreate(['name' => $permission, 'guard_name' => 'web']);
}

// Assign to roles
$adminRole->syncPermissions(Permission::all());
$managerRole->syncPermissions([
    'clients.view', 'clients.create', 'clients.edit',
    'all_users_tasks',
    // ... other manager permissions
]);
```

---

### 2. Service Structure

**Location**: `app/Services/{Admin|Client}/{Module}Service.php`

**Pattern:**
```php
<?php

namespace App\Services\{Admin|Client};

use App\Models\{Module};
use Illuminate\Support\Facades\DB;
use Illuminate\Pagination\LengthAwarePaginator;

class {Module}Service
{
    /**
     * Get all resources with optional filters
     * 
     * Note: If your model uses HasDynamicFilters trait, use ->applyFilters($params)
     * Otherwise, implement manual filtering as shown in the alternative example below
     */
    public function getAll{Modules}(array $params = [])
    {
        $query = {Module}::with(['relations']); // Eager load relationships

        // Recommended: Use HasDynamicFilters trait (if model has it)
        $query = $query->applyFilters($params);

        // Pagination
        $perPage = $params['per_page'] ?? $params['perPage'] ?? 15;
        return $query->paginate($perPage);
    }

    /**
     * Alternative: Manual filtering (if model doesn't use HasDynamicFilters)
     */
    public function getAll{Modules}Manual(array $params = [])
    {
        $query = {Module}::with(['relations']);

        // Search functionality
        if (!empty($params['search'])) {
            $search = $params['search'];
            $query->where(function ($q) use ($search) {
                $q->where('field1', 'like', "%{$search}%")
                  ->orWhere('field2', 'like', "%{$search}%");
            });
        }

        // Filter functionality
        if (!empty($params['filter_field'])) {
            $query->where('filter_field', $params['filter_field']);
        }

        // Sort functionality
        $sortBy = $params['sort_by'] ?? $params['sortBy'] ?? 'created_at';
        $sortOrder = $params['sort_order'] ?? $params['sortOrder'] ?? 'desc';
        $query->orderBy($sortBy, $sortOrder);

        // Pagination
        $perPage = $params['per_page'] ?? $params['perPage'] ?? 15;
        return $query->paginate($perPage);
    }

    /**
     * Get resource by ID
     */
    public function get{Module}ById(int $id): {Module}
    {
        return {Module}::with(['relations'])->findOrFail($id);
    }

    /**
     * Create new resource
     */
    public function create{Module}(array $data): {Module}
    {
        return DB::transaction(function () use ($data) {
            // Perform any data transformation
            $processedData = $this->processData($data);
            
            // Create the resource
            ${module} = {Module}::create($processedData);
            
            // Handle relationships if needed
            if (!empty($data['relation_ids'])) {
                ${module}->relations()->sync($data['relation_ids']);
            }
            
            // Return with relationships loaded
            return ${module}->load(['relations']);
        });
    }

    /**
     * Update resource
     */
    public function update{Module}(int $id, array $data): {Module}
    {
        return DB::transaction(function () use ($id, $data) {
            ${module} = {Module}::findOrFail($id);
            
            // Perform any data transformation
            $processedData = $this->processData($data);
            
            // Update the resource
            ${module}->update($processedData);
            
            // Handle relationships if needed
            if (isset($data['relation_ids'])) {
                ${module}->relations()->sync($data['relation_ids']);
            }
            
            // Return with relationships loaded
            return ${module}->load(['relations']);
        });
    }

    /**
     * Delete resource
     */
    public function delete{Module}(int $id): bool
    {
        return DB::transaction(function () use ($id) {
            ${module} = {Module}::findOrFail($id);
            
            // Perform any cleanup (e.g., delete related files)
            // $this->cleanup{Module}(${module});
            
            return ${module}->delete();
        });
    }

    /**
     * Process/transform data before saving
     */
    protected function processData(array $data): array
    {
        // Example: Hash password, format dates, etc.
        // if (isset($data['password'])) {
        //     $data['password'] = Hash::make($data['password']);
        // }
        
        return $data;
    }
}
```

**Key Points:**
- ✅ All business logic goes here (NOT in controllers)
- ✅ Use `DB::transaction()` for operations that modify data
- ✅ Always eager load relationships
- ✅ Return models with relationships loaded
- ✅ Handle data transformation in service methods

---

### 3. Request Structure

**Location**: `app/Http/Requests/{Admin|Client}/Store{Module}Request.php` & `Update{Module}Request.php`

**Store Request Pattern:**
```php
<?php

namespace App\Http\Requests\{Admin|Client};

use Illuminate\Foundation\Http\FormRequest;

class Store{Module}Request extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return true; // Or add permission check: return $this->user()->can('create', {Module}::class);
    }

    /**
     * Get the validation rules that apply to the request.
     */
    public function rules(): array
    {
        return [
            'field1' => ['required', 'string', 'max:255'],
            'field2' => ['required', 'email', 'unique:{modules},email'],
            'field3' => ['nullable', 'integer', 'min:0'],
            'password' => [
                'required',
                'string',
                'min:8',
                'regex:/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]/',
            ],
            'relation_ids' => ['nullable', 'array'],
            'relation_ids.*' => ['exists:relations,id'],
        ];
    }

    /**
     * Get custom messages for validator errors.
     */
    public function messages(): array
    {
        return [
            'field1.required' => 'Field1 is required.',
            'password.regex' => 'Password must contain at least one uppercase letter, one lowercase letter, one number, and one special character.',
        ];
    }
}
```

**Update Request Pattern:**
```php
<?php

namespace App\Http\Requests\{Admin|Client};

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class Update{Module}Request extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     */
    public function rules(): array
    {
        $id = $this->route('id') ?? $this->route('{module}');
        
        return [
            'field1' => ['required', 'string', 'max:255'],
            'field2' => [
                'required',
                'email',
                Rule::unique('{modules}', 'email')->ignore($id),
            ],
            'field3' => ['nullable', 'integer', 'min:0'],
            'password' => [
                'nullable', // Password is optional on update
                'string',
                'min:8',
                'regex:/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]/',
            ],
            'relation_ids' => ['nullable', 'array'],
            'relation_ids.*' => ['exists:relations,id'],
        ];
    }

    /**
     * Get custom messages for validator errors.
     */
    public function messages(): array
    {
        return [
            'field1.required' => 'Field1 is required.',
        ];
    }
}
```

**Key Points:**
- ✅ Separate Store and Update requests
- ✅ Use `Rule::unique()->ignore($id)` for update requests
- ✅ Make password optional in Update requests
- ✅ Provide custom error messages

---

### 4. Resource Structure

**Location**: `app/Http/Resources/{Admin|Client}/{Module}Resource.php`

**Pattern:**
```php
<?php

namespace App\Http\Resources\{Admin|Client};

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class {Module}Resource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'field1' => $this->field1,
            'field2' => $this->field2,
            'field3' => $this->field3,
            
            // Handle relationships with whenLoaded
            'relation' => $this->whenLoaded('relation', function () {
                return [
                    'id' => $this->relation->id,
                    'name' => $this->relation->name,
                ];
            }),
            
            // Handle collections
            'relations' => $this->whenLoaded('relations', function () {
                return $this->relations->map(function ($item) {
                    return [
                        'id' => $item->id,
                        'name' => $item->name,
                    ];
                });
            }),
            
            // Format dates
            'created_at' => $this->created_at->toISOString(),
            'updated_at' => $this->updated_at->toISOString(),
        ];
    }
}
```

**Key Points:**
- ✅ Use `whenLoaded()` for relationships to avoid N+1 queries
- ✅ Format dates consistently (use `toISOString()`)
- ✅ Only include necessary fields
- ✅ Transform nested relationships

---

## Frontend Components

### 1. Index Page Structure

**Location**: `resources/js/pages/Modules/{admin|client}/{Module}/{Module}Index.vue`

**Pattern:**
```vue
<template>
    <Head :title="$t('{modules}.title')" />
    <AppLayout>
        <div class="flex items-center justify-between mb-6">
            <h1 class="text-3xl font-bold transition-colors"
                :class="appStore.darkMode ? 'text-gray-100' : 'text-gray-900'">
                {{ $t('{modules}.title') }}
            </h1>
            <Link :href="`/{admin|client}/{modules}/create`">
                <Button variant="primary">
                    {{ $t('{modules}.addNew') }}
                </Button>
            </Link>
        </div>

        <DataTable
            :data="items"
            :pagination="pagination"
            :filters="filters"
            @search="handleSearch"
            @sort="handleSort"
            @filter="handleFilter"
        >
            <template #row="{ item }">
                <td>{{ item.field1 }}</td>
                <td>{{ item.field2 }}</td>
                <td>
                    <Link :href="`/{admin|client}/{modules}/${item.id}/edit`">
                        <Button variant="secondary" size="sm">
                            {{ $t('common.edit') }}
                        </Button>
                    </Link>
                    <Button 
                        variant="danger" 
                        size="sm"
                        @click="handleDelete(item.id)"
                    >
                        {{ $t('common.delete') }}
                    </Button>
                </td>
            </template>
        </DataTable>
    </AppLayout>
</template>

<script setup>
import { Head, Link, router } from '@inertiajs/vue3'
import AppLayout from '@/components/layout/AppLayout.vue'
import DataTable from '@/components/tables/DataTable.vue'
import Button from '@/components/ui/Button.vue'
import { useAppStore } from '@/store'
import { useToastStore } from '@/store'
import { useI18n } from 'vue-i18n'

const props = defineProps({
    items: {
        type: Object,
        required: true
    },
    pagination: {
        type: Object,
        required: true
    },
    filters: {
        type: Object,
        default: () => ({})
    },
    // Additional props from controller
    options: {
        type: Array,
        default: () => []
    }
})

const appStore = useAppStore()
const toast = useToastStore()
const { t } = useI18n()

const handleSearch = (query) => {
    router.get(`/{admin|client}/{modules}`, { search: query }, {
        preserveState: true,
        preserveScroll: true
    })
}

const handleSort = ({ column, order }) => {
    router.get(`/{admin|client}/{modules}`, {
        ...props.filters,
        sort_by: column,
        sort_order: order
    }, {
        preserveState: true,
        preserveScroll: true
    })
}

const handleFilter = (filters) => {
    router.get(`/{admin|client}/{modules}`, filters, {
        preserveState: true,
        preserveScroll: true
    })
}

const handleDelete = (id) => {
    if (confirm(t('{modules}.confirmDelete'))) {
        router.delete(`/{admin|client}/{modules}/${id}`, {
            onSuccess: () => {
                toast.success(t('{modules}.deleteSuccess'))
            },
            onError: () => {
                toast.error(t('{modules}.deleteError'))
            }
        })
    }
}
</script>
```

**Key Points:**
- ✅ Use `Head` component for page title
- ✅ Use `AppLayout` wrapper
- ✅ Use `Link` component for navigation (not router-link)
- ✅ Use `router.get/post/put/delete` for actions
- ✅ Use `preserveState` and `preserveScroll` for better UX
- ✅ Use i18n for all text
- ✅ Use Pinia stores for app state (dark mode, toast)

---

### 2. Form Page Structure

**Location**: `resources/js/pages/Modules/{admin|client}/{Module}/{Module}Form.vue`

**Pattern:**
```vue
<template>
    <div>
        <Head :title="isEditing ? $t('{modules}.edit') : $t('{modules}.addNew')" />
        <div class="flex items-center gap-4 mb-6">
            <Link :href="`/{admin|client}/{modules}`">
                <button
                    class="p-2 rounded-lg transition-colors"
                    :class="appStore.darkMode
                        ? 'hover:bg-gray-700 text-gray-300'
                        : 'hover:bg-gray-100 text-gray-700'"
                >
                    <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path
                            stroke-linecap="round"
                            stroke-linejoin="round"
                            stroke-width="2"
                            d="M15 19l-7-7 7-7"
                        />
                    </svg>
                </button>
            </Link>
            <h1 class="text-3xl font-bold transition-colors"
                :class="appStore.darkMode ? 'text-gray-100' : 'text-gray-900'">
                {{ isEditing ? $t('{modules}.edit') : $t('{modules}.addNew') }}
            </h1>
        </div>

        <div class="rounded-lg shadow p-6 transition-colors"
             :class="appStore.darkMode
                 ? 'bg-gray-800 border border-gray-700'
                 : 'bg-white'">
            <form @submit.prevent="handleSubmit">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <!-- Field 1 -->
                    <TextInput
                        v-model="form.field1"
                        :label="$t('{modules}.fields.field1')"
                        :placeholder="$t('{modules}.placeholders.field1')"
                        :error="form.errors.field1"
                        required
                    />

                    <!-- Field 2 -->
                    <TextInput
                        v-model="form.field2"
                        type="email"
                        :label="$t('{modules}.fields.field2')"
                        :placeholder="$t('{modules}.placeholders.field2')"
                        :error="form.errors.field2"
                        required
                    />

                    <!-- Password (only show if creating or if user wants to change) -->
                    <TextInput
                        v-model="form.password"
                        type="password"
                        :label="$t('{modules}.fields.password')"
                        :placeholder="$t('{modules}.placeholders.password')"
                        :error="form.errors.password"
                        :required="!isEditing"
                    />

                    <!-- Select Field -->
                    <Select
                        v-model="form.relation_id"
                        :label="$t('{modules}.fields.relation')"
                        :placeholder="$t('{modules}.placeholders.relation')"
                        :options="relationOptions"
                        :error="form.errors.relation_id"
                        required
                    />
                </div>

                <!-- Actions -->
                <div class="flex items-center justify-end gap-4 mt-6 pt-6 border-t transition-colors"
                     :class="appStore.darkMode ? 'border-gray-700' : 'border-gray-200'">
                    <Link :href="`/{admin|client}/{modules}`">
                        <Button type="button" variant="secondary">
                            {{ $t('common.cancel') }}
                        </Button>
                    </Link>
                    <Button type="submit" variant="primary" :loading="form.processing">
                        {{ isEditing ? $t('common.update') : $t('common.create') }}
                    </Button>
                </div>
            </form>
        </div>
    </div>
</template>

<script setup>
import { computed } from 'vue'
import { Head, Link, useForm } from '@inertiajs/vue3'
import { useAppStore } from '@/store'
import { useToastStore } from '@/store'
import { useI18n } from 'vue-i18n'
import TextInput from '@/components/inputs/TextInput.vue'
import Select from '@/components/inputs/Select.vue'
import Button from '@/components/ui/Button.vue'

// Define props received from controller
const props = defineProps({
    {module}: {
        type: Object,
        default: null
    },
    options: {
        type: Array,
        required: true
    }
})

const appStore = useAppStore()
const toast = useToastStore()
const { t } = useI18n()

const isEditing = computed(() => !!props.{module})

const relationOptions = computed(() =>
    props.options.map(option => ({
        value: option.id,
        label: option.name
    }))
)

// Initialize form with Inertia useForm
const form = useForm({
    field1: props.{module}?.field1 || '',
    field2: props.{module}?.field2 || '',
    password: '',
    relation_id: props.{module}?.relation_id || ''
})

const handleSubmit = () => {
    if (isEditing.value) {
        form.put(`/{admin|client}/{modules}/${props.{module}.id}`, {
            onSuccess: () => {
                toast.success(t('{modules}.updateSuccess'))
            }
        })
    } else {
        form.post(`/{admin|client}/{modules}`, {
            onSuccess: () => {
                toast.success(t('{modules}.createSuccess'))
            }
        })
    }
}
</script>
```

**Key Points:**
- ✅ Use `useForm` from `@inertiajs/vue3` for form handling
- ✅ Form automatically handles validation errors
- ✅ Use `form.processing` for loading state
- ✅ Use `form.post/put` for submissions
- ✅ Show password field conditionally (required on create, optional on update)
- ✅ Use computed properties for derived data

---

## Routes Configuration

**Location**: `routes/web.php`

**Pattern:**
```php
// Admin routes
Route::prefix('admin')->name('admin.')->middleware('auth')->group(function () {
    Route::middleware('permission:{modules}.view')->group(function () {
        Route::resource('{modules}', {Module}Controller::class);
    });
});

// Client routes
Route::prefix('client')->name('client.')->middleware('auth')->group(function () {
    Route::middleware('permission:{modules}.view')->group(function () {
        Route::resource('{modules}', {Module}Controller::class);
    });
});
```

**Key Points:**
- ✅ Use resource routes when possible
- ✅ Apply permission middleware
- ✅ Use route names consistently
- ✅ Group by prefix (admin/client)

---

## Naming Conventions

### Backend

- **Controllers**: `{Module}Controller` (e.g., `UserController`, `ProductController`)
- **Services**: `{Module}Service` (e.g., `UserService`, `ProductService`)
- **Requests**: `Store{Module}Request`, `Update{Module}Request`
- **Resources**: `{Module}Resource` (e.g., `UserResource`, `ProductResource`)
- **Models**: Singular PascalCase (e.g., `User`, `Product`)
- **Methods**: camelCase (e.g., `getUserById`, `createUser`)

### Frontend

- **Pages**: `{Module}Index.vue`, `{Module}Form.vue` (PascalCase)
- **Components**: PascalCase (e.g., `DataTable.vue`, `TextInput.vue`)
- **Composables**: camelCase with `use` prefix (e.g., `useImageUpload.js`)
- **Stores**: camelCase (e.g., `useAppStore`, `useToastStore`)

### Routes

- **URLs**: kebab-case, plural (e.g., `/admin/users`, `/client/products`)
- **Route Names**: dot notation (e.g., `admin.users.index`, `client.products.create`)

---

## Code Patterns

### 1. DataTable with HasDataTableInertia Trait

**Note:** Filtering and searching are handled by the `HasDynamicFilters` trait on the model. Configure `$filterable`, `$searchable`, and `$relationshipFilters` properties in your model.

```php
// In Controller
return $this->inertiaDataTable(
    page: 'Modules/admin/Users/UsersIndex',
    query: User::with(['roles'])->applyFilters($request->all()),
    request: $request,
    resource: UserResource::class,
    additionalProps: [
        'roles' => Role::all(['id', 'name'])
    ]
);

// In Model (User.php)
use App\Traits\HasDynamicFilters;

class User extends Authenticatable
{
    use HasDynamicFilters;
    
    protected $filterable = [
        'name', 'email', 'email_verified_at', 'created_at', 'updated_at',
    ];
    
    protected $searchable = [
        'name', 'email',
    ];
    
    protected $relationshipFilters = [
        'role' => 'roles.name',
        'permission' => 'permissions.name',
    ];
}
```

### 2. Error Handling in Controllers

```php
try {
    $this->service->create($request->validated());
    return redirect()->route('admin.{modules}.index')
        ->with('success', __('{modules}.created'));
} catch (\Exception $e) {
    return redirect()->back()
        ->withInput()
        ->withErrors(['error' => $e->getMessage()]);
}
```

### 3. Service Transactions

```php
public function create{Module}(array $data): {Module}
{
    return DB::transaction(function () use ($data) {
        // All operations here are atomic
        ${module} = {Module}::create($data);
        ${module}->relations()->sync($data['relation_ids']);
        return ${module}->load(['relations']);
    });
}
```

### 4. Inertia Form Handling

```vue
const form = useForm({
    field1: '',
    field2: ''
})

form.post('/admin/{modules}', {
    onSuccess: () => {
        toast.success(t('{modules}.createSuccess'))
    },
    onError: () => {
        toast.error(t('{modules}.createError'))
    }
})
```

### 5. Navigation with Inertia

```vue
// Use Link component for navigation
<Link href="/admin/users">Users</Link>

// Use router for programmatic navigation
router.get('/admin/users', { search: query }, {
    preserveState: true,
    preserveScroll: true
})
```

---

## Best Practices

### Backend

1. ✅ **Thin Controllers, Fat Services**: All business logic in services
2. ✅ **Use Transactions**: Wrap data modifications in `DB::transaction()`
3. ✅ **Eager Loading**: Always eager load relationships to avoid N+1 queries
4. ✅ **Type Hints**: Use return type hints (`Response`, `RedirectResponse`)
5. ✅ **Error Handling**: Always wrap service calls in try-catch
6. ✅ **Validation**: Use Form Requests for all validation
7. ✅ **Resources**: Always use Resources to format data for Inertia
8. ✅ **Permissions**: Check permissions in routes, not controllers

### Frontend

1. ✅ **Inertia Components**: Use `Head`, `Link`, `useForm` from Inertia
2. ✅ **No API Calls**: Don't use axios/fetch, use Inertia router
3. ✅ **i18n**: All user-facing text should use i18n
4. ✅ **Dark Mode**: Support dark mode with appStore.darkMode
5. ✅ **Loading States**: Use `form.processing` for loading indicators
6. ✅ **Error Display**: Inertia automatically handles validation errors
7. ✅ **Toast Notifications**: Use toast store for success/error messages
8. ✅ **Preserve State**: Use `preserveState` and `preserveScroll` for better UX

### General

1. ✅ **Consistent Naming**: Follow naming conventions strictly
2. ✅ **Code Organization**: Keep files in correct directories
3. ✅ **Documentation**: Add PHPDoc comments to methods
4. ✅ **Testing**: Write tests for services (business logic)
5. ✅ **Git Commits**: Commit related files together

---

## Quick Checklist

When implementing a new feature, ensure you have:

### Backend
- [ ] Controller with all CRUD methods
- [ ] Service with business logic
- [ ] Store Request (validation)
- [ ] Update Request (validation)
- [ ] Resource (data transformation)
- [ ] Routes configured with permissions
- [ ] Model relationships defined (if needed)

### Frontend
- [ ] Index page (list view)
- [ ] Form page (create/edit)
- [ ] i18n translations added
- [ ] Dark mode support
- [ ] Error handling
- [ ] Loading states
- [ ] Toast notifications

### Testing
- [ ] Test create functionality
- [ ] Test update functionality
- [ ] Test delete functionality
- [ ] Test validation errors
- [ ] Test permissions
- [ ] Test search/filter/sort

---

## Example: Complete Feature Implementation

See existing implementations for reference:
- **Users Module**: `UserController`, `UserService`, `UsersIndex.vue`, `UsersForm.vue`
- **Roles Module**: `RoleController`, `RoleService`, `RolesIndex.vue`, `RolesForm.vue`

---

**Last Updated**: 2025-01-XX
**Version**: 1.0.0

