# 📚 LangueCandidat - Table de Liaison (Pivot Table)

## 🎯 Concept

`langue_candidats` est une **table de liaison** pour une relation **Many-to-Many**:

```
┌────────────────────────────────────────────┐
│                                            │
│  Un Candidat parle PLUSIEURS Langues      │
│  Une Langue est parlée par PLUSIEURS      │
│  Candidats                                 │
│                                            │
└────────────────────────────────────────────┘
```

## 📊 Structure

### Table: `langue_candidats`

```sql
id               INT PRIMARY KEY
langue_id        INT FOREIGN KEY → langues.id
candidat_id      INT FOREIGN KEY → candidats.id
created_at       TIMESTAMP
updated_at       TIMESTAMP
```

### Exemple de données

```
id | langue_id | candidat_id | created_at
---|-----------|-------------|---------------------
1  | 1         | 5           | 2026-06-06 10:00:00
2  | 2         | 5           | 2026-06-06 10:05:00
3  | 3         | 7           | 2026-06-06 10:10:00
4  | 1         | 7           | 2026-06-06 10:15:00
```

**Interprétation:**
- Candidat #5 parle Français (langue_id=1) et Anglais (langue_id=2)
- Candidat #7 parle Allemand (langue_id=3) et Français (langue_id=1)

## 🔄 Relations Eloquent

### Modèle LangueCandidat

```php
class LangueCandidat extends Model
{
    protected $table = 'langue_candidats';
    protected $fillable = ['langue_id', 'candidat_id'];

    // Relation vers une Langue
    public function langue()
    {
        return $this->belongsTo(Langue::class, 'langue_id');
    }

    // Relation vers un Candidat
    public function candidat()
    {
        return $this->belongsTo(Candidat::class, 'candidat_id');
    }
}
```

### Modèle Candidat (à créer dans Modules/Candidat)

```php
class Candidat extends Model
{
    // Récupérer toutes les langues d'un candidat
    public function langues()
    {
        return $this->hasMany(LangueCandidat::class, 'candidat_id');
    }
}
```

### Modèle Langue

```php
class Langue extends Model
{
    // Récupérer tous les candidats parlant cette langue
    public function candidats()
    {
        return $this->hasMany(LangueCandidat::class, 'langue_id');
    }
}
```

## 📝 API - Utilisation

### 1. Créer l'association (ajouter une langue à un candidat)

```bash
POST /api/referentiel/candidate-languages
{
  "langue_id": 1,
  "candidat_id": 5
}
```

**Réponse:**
```json
{
  "success": true,
  "message": "Candidate language created successfully",
  "data": {
    "id": 1,
    "langue_id": 1,
    "candidat_id": 5,
    "created_at": "2026-06-06T10:00:00.000000Z",
    "updated_at": "2026-06-06T10:00:00.000000Z"
  }
}
```

### 2. Récupérer toutes les associations

```bash
GET /api/referentiel/candidate-languages?page=1&per_page=15
```

**Réponse:**
```json
{
  "success": true,
  "data": [
    {
      "id": 1,
      "langue_id": 1,
      "candidat_id": 5,
      "created_at": "2026-06-06T10:00:00.000000Z",
      "updated_at": "2026-06-06T10:00:00.000000Z"
    },
    {
      "id": 2,
      "langue_id": 2,
      "candidat_id": 5,
      "created_at": "2026-06-06T10:05:00.000000Z",
      "updated_at": "2026-06-06T10:05:00.000000Z"
    }
  ],
  "pagination": {...}
}
```

### 3. Récupérer une association spécifique

```bash
GET /api/referentiel/candidate-languages/1
```

### 4. Mettre à jour une association

```bash
PUT /api/referentiel/candidate-languages/1
{
  "langue_id": 2,
  "candidat_id": 5
}
```

### 5. Supprimer une association

```bash
DELETE /api/referentiel/candidate-languages/1
```

## 💻 Utilisation côté code

### En PHP - Récupérer les langues d'un candidat

```php
use Modules\Referentiel\Services\LangueCandidatService;

class CandidatService
{
    public function __construct(private LangueCandidatService $langueService) {}

    public function getLanguesOfCandidat($candidatId)
    {
        // Récupérer toutes les associations
        $associations = $this->langueService->getBy('candidat_id', $candidatId);
        
        // Avec relations chargées
        return $associations->map(function ($assoc) {
            return $assoc->langue;  // Retourne l'objet Langue
        });
    }
}
```

### En PHP - Ajouter une langue à un candidat

```php
class CandidatLanguageController
{
    public function addLanguage($candidatId, $langueId)
    {
        $this->langueService->create([
            'candidat_id' => $candidatId,
            'langue_id' => $langueId
        ]);
    }
}
```

### En JavaScript - Récupérer les langues d'un candidat

```javascript
// Récupérer toutes les langues du candidat #5
const response = await fetch(
  '/api/referentiel/candidate-languages?page=1&per_page=100'
);
const data = await response.json();

const candidat5Languages = data.data.filter(
  item => item.candidat_id === 5
);

console.log(candidat5Languages);
// [
//   { id: 1, langue_id: 1, candidat_id: 5, ... },
//   { id: 2, langue_id: 2, candidat_id: 5, ... }
// ]
```

### En JavaScript - Ajouter une langue

```javascript
const response = await fetch('/api/referentiel/candidate-languages', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
        langue_id: 1,      // Français
        candidat_id: 5     // Candidat #5
    })
});

const data = await response.json();
console.log(data); // ✅ Langue ajoutée au candidat
```

## 🔒 Validations

```php
'langue_id' => 'required|integer|exists:langues,id',
'candidat_id' => 'required|integer|exists:candidats,id'
```

### Signification

| Validation | Signification |
|-----------|--------------|
| `required` | Le champ est obligatoire |
| `integer` | Doit être un nombre |
| `exists:langues,id` | Doit exister dans la table `langues`, colonne `id` |
| `exists:candidats,id` | Doit exister dans la table `candidats`, colonne `id` |

### Erreurs possibles

```json
{
  "success": false,
  "message": "Validation failed",
  "errors": {
    "langue_id": ["The selected langue_id is invalid."],
    "candidat_id": ["The selected candidat_id is invalid."]
  }
}
```

## 🔄 Migration correcte

```php
Schema::create('langue_candidats', function (Blueprint $table) {
    $table->id();
    
    // Clés étrangères
    $table->unsignedBigInteger('langue_id');
    $table->unsignedBigInteger('candidat_id');
    
    // Ajouter les contraintes (optionnel mais recommandé)
    $table->foreign('langue_id')->references('id')->on('langues')->onDelete('cascade');
    $table->foreign('candidat_id')->references('id')->on('candidats')->onDelete('cascade');
    
    // Éviter les doublons (un candidat parle une langue une seule fois)
    $table->unique(['langue_id', 'candidat_id']);
    
    $table->timestamps();
});
```

## 📋 Checklist

- ✅ Table `langue_candidats` créée avec migrations
- ✅ Contrôleur avec validations `langue_id` et `candidat_id`
- ✅ Modèle avec `$fillable = ['langue_id', 'candidat_id']`
- ✅ Relations Eloquent configurées
- ✅ API endpoints pour CRUD
- ✅ Validations de clés étrangères

## 💡 Cas d'usage

1. **Afficher les compétences linguistiques d'un candidat**
2. **Trouver tous les candidats parlant une langue donnée**
3. **Ajouter/Retirer une langue d'un candidat**
4. **Filtrer les candidats par langues**

---

**Note:** Cette table est une **Pivot Table** pour la relation Many-to-Many entre Candidats et Langues.
