<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\Prospecto;

use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Auth;


class ProspectoController extends Controller
{
    public function __construct() {
        $this->middleware('can:prospecto.index')->only('index','show');
        $this->middleware('can:prospecto.create')->only('create','store');
        $this->middleware('can:prospecto.edit')->only('edit','update');
        $this->middleware('can:prospecto.destroy')->only('destroy');
    }

    public function index()
    {
        $user = Auth::user();
        $plantelesUsuario = $user->plantelUsuarios->pluck('id');

        $prospectos = User::with(['prospectos' => function ($query) use ($user, $plantelesUsuario) {

            $query->where(function ($q) use ($user, $plantelesUsuario) {

                $q->where('usuario_registro', $user->id)
                ->orWhereHas('prospectos.plantelUsuarios', function ($sub) use ($plantelesUsuario) {
                    $sub->whereIn('plantels.id', $plantelesUsuario);
                });

            });

        }])
        ->whereHas('prospectos', function ($query) use ($user, $plantelesUsuario) {

            $query->where(function ($q) use ($user, $plantelesUsuario) {

                $q->where('usuario_registro', $user->id)
                ->orWhereHas('prospectos.plantelUsuarios', function ($sub) use ($plantelesUsuario) {
                    $sub->whereIn('plantels.id', $plantelesUsuario);
                });

            });

        })
        ->get();

        return view('prospecto.index', compact('prospectos'));
    }

    public function destroy(Prospecto $prospecto)
    {
        $user = $prospecto->prospectos()->first();

        if ($user) {
            $user->roles()->detach();

            $user->plantelUsuarios()->detach();

            $prospecto->prospectos()->detach($user->id);

            $user->delete();
        }

            $prospecto->delete();
            session()->flash('swal',[
                'icon'=>'success',
                'title'=>'Eliminado!',
                'text'=>'Se ha eliminado el registro correctamente'
            ]);
        return redirect()->route('prospecto.index');
    }
}
