<?php

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

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\TicketAsignado;
use Illuminate\Http\Request;

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

class AsignadosController extends Controller
{
    protected $userId;
    protected $asignadoId;
    protected $viewController = "superadmin.tickets.asignados";
    protected $routeController = "superadmin.tickets.asignados.index";

    /**
     * AsignadosController constructor.
     */
    public function __construct()
    {
        $this->asignadoId = getInfoConstanteId('listas.ESTADOTICKETS', 'estadoTickets.ASIGNADO');//ASIGNADO
    }

    /**
     * @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('asignado_ticket_id', $this->asignadoId)->whereNull('fecha_fin_asignado')->orderBy('id', 'ASC')->get();
        foreach ($tickets as $key => $asignado) {
            $tickets[$key]->ticket = Ticket::with('categoriaTicket', 'tipoTicket')->find($asignado->ticket_id);
            $userPersona = UserPersona::where('user_id', $asignado->created_user_id)->first();
            $tickets[$key]->persona = Persona::withTrashed()->find($userPersona->persona_id);
            $tickets[$key]->asignado = User::withTrashed()->find($asignado->asignado_user_id);
        }
//        dd($tickets[0]);
        return view($this->viewController . '.index', compact('styles', 'scripts', 'tickets'));
    }

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

    /**
     * @param Request $request
     */
    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);

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

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

    /**
     * @param TicketAsignado $request
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(TicketAsignado $request, $id)
    {
        $ticketEstado = TicketEstado::with('ticket')->where('ticket_id', $id)->first();
        $ticketEstado->fecha_fin_asignado = date('Y-m-d H:i:s');
        $ticketEstado->conincidencia_ticket_id = getInfoConstanteId('listas.ESTADOTICKETS', 'estadoTickets.CONINCIDENCIA');// CONINCIDENCIA
        $ticketEstado->mensaje_conincidencia = $request->mensaje_conincidencia;
        $ticketEstado->fecha_inicio_conincidencia = 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_conincidencia;
            $data['categoria'] = $ticket->categoriaTicket->nombre;
            $data['tipo'] = $ticket->tipoTicket->nombre;
            $data['asunto'] = $ticket->asunto;
            $data['descripcion'] = $ticket->descripcion;
            $data['mensajeConIncidencia'] = $ticketEstado->mensaje_conincidencia;

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

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

        $message = 'Se describio el detalle de la incidencia del ticket <strong>' . $ticketEstado->ticket->codigo . ' </strong>';
        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)
    {
        //
    }
}
