<?php

namespace App\Http\Controllers;

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

class ClientController extends Controller
{
    public function index()
    {
        $user = auth()->user();

        $clients = $user->hasRole('super-admin')
            ? Client::with('company')->get()
            : Client::where('company_id', $user->company_id)
                    ->with('company')
                    ->get();

        return view('clients.index', compact('clients'));
    }

    public function create()
    {
        $companies = auth()->user()->hasRole('super-admin')
            ? Company::where('activo', true)->get()
            : Company::where('id', auth()->user()->company_id)->get();

        return view('clients.create', compact('companies'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'nombre' => 'required|string|max:255',
            'email' => 'required|email|unique:clients,email',
            'telefono' => 'nullable|string|max:20',
            'direccion' => 'nullable|string|max:255',
            'company_id' => 'required|exists:companies,id',
        ]);

        Client::create($request->all());

        return redirect()->route('clients.index')
            ->with('success', 'Cliente creado correctamente.');
    }

    public function edit(Client $client)
    {
        //$companies = Company::where('activo', true)->get();
         $companies = auth()->user()->hasRole('super-admin')
            ? Company::where('activo', true)->get()
            : Company::where('id', auth()->user()->company_id)->get();

        return view('clients.edit', compact('client', 'companies'));
    }

    public function update(Request $request, Client $client)
    {
        $request->validate([
            'nombre' => 'required|string|max:255',
            'email' => 'required|email|unique:clients,email,' . $client->id,
            'telefono' => 'nullable|string|max:20',
            'direccion' => 'nullable|string|max:255',
            'company_id' => 'required|exists:companies,id',
        ]);

        $client->update($request->all());

        return redirect()->route('clients.index')
            ->with('success', 'Cliente actualizado.');
    }

    public function destroy(Client $client)
    {
        $client->delete();

        return redirect()->route('clients.index')
            ->with('success', 'Cliente eliminado.');
    }
}
