<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Company;
use App\Models\User;

class CompanyContactController extends Controller
{
    public function store(Request $request, Company $company)
    {
        $request->validate([
            'user_id' => 'required|exists:users,id',
            'position' => 'nullable|string|max:100'
        ]);
        
        // Evitar duplicados
        if (!$company->contacts()->where('user_id', $request->user_id)->exists()) {
            $company->contacts()->attach($request->user_id, [
                'position' => $request->position
            ]);
            
            return redirect()->back()
                ->with('success', 'Contacto agregado exitosamente');
        }
        
        return redirect()->back()
            ->with('error', 'Este contacto ya está asociado a la empresa');
    }

    public function update(Request $request, Company $company, User $contact)
    {
        $request->validate([
            'position' => 'nullable|string|max:100'
        ]);
        
        $company->contacts()->updateExistingPivot($contact->id, [
            'position' => $request->position
        ]);
        
        return redirect()->back()
            ->with('success', 'Cargo del contacto actualizado');
    }

    public function destroy(Company $company, User $contact)
    {
        $company->contacts()->detach($contact->id);
        
        return redirect()->back()
            ->with('success', 'Contacto eliminado de la empresa');
    }
}