<?php

namespace App\Http\Controllers\Superadmin\Tickets\Pendientes;

use App\Entities\Area;
use App\Entities\Persona;
use App\Entities\Ticket;
use App\Entities\TicketEstado;
use App\Entities\TicketFoto;
use App\Entities\User;
use App\Entities\UserPersona;
use App\Http\Requests\TicketPendiente;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Mail;

class PendientesController extends Controller
{
    protected $userId;
    protected $pendienteId;
    protected $viewController = "superadmin.tickets.pendientes";
    protected $routeController = "superadmin.tickets.pendientes.index";

    /**
     * PendientesController constructor.
     */
    public function __construct()
    {
        $this->pendienteId = getInfoConstanteId('listas.ESTADOTICKETS', 'estadoTickets.PENDIENTE');//Pendiente
    }

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index()
    {
        $styles = ['assets/css/dataTables.bootstrap'];
        $scripts = [
            'assets/js/datatable/jquery.dataTables.min',
            'assets/js/datatable/ZeroClipboard',
            'assets/js/datatable/dataTables.tableTools.min',
            'assets/js/datatable/dataTables.bootstrap.min',
            'assets/js/select2/select2.min',
            'assets/js/select2/select2es'];

        $tickets = TicketEstado::where('pendiente_ticket_id', $this->pendienteId)->whereNull('fecha_fin_pendiente')->orderBy('id', 'ASC')->get();
        foreach ($tickets as $key => $pendiente) {
            $tickets[$key]->ticket = Ticket::with('categoriaTicket', 'tipoTicket')->find($pendiente->ticket_id);
            $userPersona = UserPersona::where('user_id', $pendiente->created_user_id)->first();
            $tickets[$key]->persona = Persona::withTrashed()->find($userPersona->persona_id);
        }

//        dd($tickets);
        return view($this->viewController . '.index', compact('styles', 'scripts', 'tickets'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * @param Request $request
     * @param $codigo
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function show(Request $request, $codigo)
    {
        if ($request->ajax()) {
            $ticket = Ticket::with('categoriaTicket', 'tipoTicket')->where('codigo', $codigo)->first();
            $ticket->ticketFoto = TicketFoto::where('ticket_id', $ticket->id)->first();
            if ($ticket->ticketFoto != null) {
                $ticket->ticketFoto->rutaFotoOriginal = asset('web/tickets/' . $ticket->ticketFoto->foto);
                $ticket->ticketFoto->rutaFotoThumbnail = asset('web/tickets/thumbnail/thumb-' . $ticket->ticketFoto->foto);
            }
            $userPersona = UserPersona::where('user_id', $ticket->created_user_id)->first();
            $persona = Persona::withTrashed()->with('cargo')->find($userPersona->persona_id);
            $persona->area = Area::with('sede')->find($persona->cargo->area_id);
//            $usuarioAsignar = User::where([['soporte', 1], ['id', '!=', 1]])->orderBy('last_first_name', 'ASC')->pluck('last_first_name', 'id')->all();
            $usuarioAsignar = User::where('soporte', 1)->whereNotIn('id', [1, 103])->orderBy('last_first_name', 'ASC')->pluck('last_first_name', 'id')->all(); //103 Luis Romero

            return view($this->viewController . '.show', compact('ticket', 'persona', 'usuarioAsignar'));
        }
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * @param TicketPendiente $request
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(TicketPendiente $request, $id)
    {
        $user = User::find($request->asignado_user_id);

        $ticketEstado = TicketEstado::with('ticket')->where('ticket_id', $id)->first();
        $ticketEstado->fecha_fin_pendiente = date('Y-m-d H:i:s');
        $ticketEstado->asignado_ticket_id = getInfoConstanteId('listas.ESTADOTICKETS', 'estadoTickets.ASIGNADO');//ASIGNADO
        $ticketEstado->mensaje_asignado = "La atención del ticket sera brindada por <strong>" . $user->last_first_name . "</strong>";
        $ticketEstado->asignado_user_id = $request->asignado_user_id;
        $ticketEstado->fecha_inicio_asignado = date('Y-m-d H:i:s');
        $ticketEstado->save();

        //Envio de E-mail Asignado
        $userPersona = UserPersona::where('user_id', $ticketEstado->created_user_id)->first();
        $persona = Persona::find($userPersona->persona_id);
        if ($persona != null && $persona->email != null) {
            $ticket = Ticket::with('categoriaTicket', 'tipoTicket')->find($ticketEstado->ticket_id);
            //Foto
            $ticketFoto = TicketFoto::where('ticket_id', $ticket->id)->first();
            $emails = [$persona->email];

            $data = [];
            $data['numeroTicket'] = $ticket->codigo;
            $data['fechaCreacion'] = $ticketEstado->fecha_inicio_asignado;
            $data['categoria'] = $ticket->categoriaTicket->nombre;
            $data['tipo'] = $ticket->tipoTicket->nombre;
            $data['asunto'] = $ticket->asunto;
            $data['descripcion'] = $ticket->descripcion;
            $data['mensajeAsignado'] = $ticketEstado->mensaje_asignado;

            if ($ticketFoto != null) {
                $data['foto'] = asset('web/tickets/' . $ticketFoto->foto);
            }

            Mail::send('admin.herramientas.email.tickets.asignado', $data, function ($message) use ($ticket, $emails) {
                $message->from('administrador@almoperations.com', 'Sistema de Tickets');
                $message->to($emails);
                $message->subject('👮‍ Asignación del Ticket #' . $ticket->codigo);
            });
        }

        $message = 'Se asigno el ticket ' . $ticketEstado->ticket->codigo . ' al usuario ' . $user->last_first_name . ' correctamente';
        notifyFlash($message, 'success');
        $response = [
            'route' => route($this->routeController)
        ];

        return response()->json($response);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
