# Multi-Language Implementation Guide (EN & JP)

## Overview
This project supports multiple languages: **English (en)** and **Japanese (jp)** with automatic locale detection via HTTP request headers.

---

## How It Works

### 1. **Localization Middleware**
The `Localization` middleware (`app/Http/Middleware/Localization.php`) automatically:
- Reads the `lang` header from incoming requests
- Sets the application locale based on the header value
- Defaults to Japanese (`jp`) if no header or invalid locale is provided
- Supported values: `en`, `jp`

### 2. **Request Example**
```bash
# English Request
curl -H "lang: en" https://api.example.com/api/v1/brand/list

# Japanese Request (or default)
curl -H "lang: jp" https://api.example.com/api/v1/brand/list
```

---

## Configuration

### Language Configuration (`config/constant.php`)
```php
'langs' => ['en', 'jp'],  // Supported languages
```

### Middleware Registration (`bootstrap/app.php`)
The middleware is already registered and appended to the application middleware stack.

---

## Using Translations in Code

### 1. **In Controllers & Services**
Use the `__()` helper function to fetch translated strings:

```php
namespace App\Http\Service;

class BrandService
{
    public function add($data)
    {
        // Fetch translated message
        return $this->sendResponse(
            $brand,
            __('messages.add')  // Translates to "Successfully added" or "正常に追加されました"
        );
    }
}
```

### 2. **In Responses**
```php
return response()->json([
    'message' => __('messages.success'),
    'data' => $result
], 200);
```

### 3. **In Validation Rules**
```php
public function rules()
{
    return [
        'username' => 'required|string|unique:users',
        'email' => 'required|email',
    ];
}

// Error messages are automatically localized
```

---

## Translation Files Structure

### English Translations
`resources/lang/en/messages.php`
```php
return [
    'welcome' => 'Welcome to our application',
    'add' => 'Successfully added',
    'notFound' => 'The data with the specified ID cannot be found',
    // ... more translations
];
```

### Japanese Translations
`resources/lang/jp/messages.php`
```php
return [
    'welcome' => '私たちのアプリケーションへようこそ',
    'add' => '正常に追加されました',
    'notFound' => '指定されたIDのデータが見つかりません',
    // ... more translations
];
```

---

## Available Translation Keys

| Key | English | Japanese |
|-----|---------|----------|
| `welcome` | Welcome to our application | 私たちのアプリケーションへようこそ |
| `success` | Operation successful | 操作成功 |
| `add` | Successfully added | 正常に追加されました |
| `update` | Successfully updated | 正常に更新されました |
| `notFound` | Data not found | データが見つかりません |
| `username_required` | Username is required | ユーザー名は必須です |
| `password_required` | Password is required | パスワードが必要 |
| `confirmPassword` | Password does not match | パスワードが一致しません |
| `invalidJson` | Invalid JSON data | 無効なJSONデータ |
| `exist` | Already exist | すでに存在します |

---

## Example Implementation: Brand Service

```php
<?php

namespace App\Http\Service;

use App\Http\Repository\BrandRepository;
use App\Traits\ResponsWithHttpStatus;

class BrandService
{
    use RespondsWithHttpStatus;

    public function add($data)
    {
        try {
            $brand = BrandRepository::store($data);
            
            return $this->sendResponse(
                $brand,
                __('messages.add')  // Automatically translates based on locale
            );
        } catch (\Exception $e) {
            return $this->sendError(
                __('messages.failed_common_message'),
                500
            );
        }
    }

    public function index()
    {
        try {
            $brands = BrandRepository::all();
            
            return $this->sendResponse(
                $brands,
                __('messages.view')
            );
        } catch (\Exception $e) {
            return $this->sendError(
                __('messages.notFound'),
                404
            );
        }
    }
}
```

---

## Testing Localization

### Using Tinker REPL
```bash
php artisan tinker
```

Then in tinker:
```php
app()->setLocale('en');
echo __('messages.welcome');  // "Welcome to our application"

app()->setLocale('jp');
echo __('messages.welcome');  // "私たちのアプリケーションへようこそ"
```

### Using API Client (Postman/cURL)
```bash
# English request
curl -X GET "http://localhost:8000/api/v1/brand/list" \
  -H "lang: en"

# Japanese request
curl -X GET "http://localhost:8000/api/v1/brand/list" \
  -H "lang: jp"
```

---

## Adding New Translations

1. Add the key to both language files:

**English** (`resources/lang/en/messages.php`):
```php
'newKey' => 'New message in English',
```

**Japanese** (`resources/lang/jp/messages.php`):
```php
'newKey' => '日本語の新しいメッセージ',
```

2. Use in code:
```php
__('messages.newKey')
```

---

## Best Practices

1. **Always add translations to both languages** - Maintain consistency
2. **Use the `__()` helper** - Never hardcode messages
3. **Group related translations** - Use message files for clarity
4. **Keep keys descriptive** - Use snake_case for key names
5. **Test both languages** - Verify translations work correctly

---

## Troubleshooting

### Locale not changing
- Ensure the `lang` header is being sent with valid values (`en` or `jp`)
- Check that the Localization middleware is registered in `bootstrap/app.php`

### Missing translations
- Verify the translation key exists in both `messages.php` files
- Use the fallback locale (default is `jp`) if a key is missing

### Validation messages in wrong language
- Laravel's validation messages are automatically translated if translation files exist
- Ensure custom validation messages are wrapped with `__()` helper

---

## Summary

Your application now supports:
- ✅ Automatic locale detection via `lang` header
- ✅ Fallback to Japanese (jp) as default
- ✅ Synchronized English/Japanese translations
- ✅ Easy-to-use `__()` helper for translations
- ✅ Consistent message keys across both languages
