<?php

namespace App\Http\Controllers\Admin\Tickets;

use App\Entities\Area;
use App\Entities\Persona;
use App\Entities\Sede;
use App\Entities\SubLista;
use App\Entities\Ticket;
use App\Entities\TicketEstado;
use App\Entities\TicketFoto;
use App\Entities\UserPersona;
use App\Http\Requests\TicketRequest;
use Illuminate\Http\Request;

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

class TicketsController extends Controller
{
    protected $userId;
    protected $viewController = "admin.tickets";
    protected $routeController = "admin.tickets.index";

    /**
     * TicketsController constructor.
     */
    public function __construct()
    {
        $this->userId = Auth::guard('admin')->user();
    }

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index()
    {
        $styles = ['vendors/bower_components/bootstrap-select/dist/css/bootstrap-select'];
        $scripts = ['vendors/bower_components/bootstrap-select/dist/js/bootstrap-select',
            'vendors/fileinput/fileinput.min',
            'vendors/bootstrap-growl/bootstrap-growl.min'];
        $categoriaTickets = listaNombre('categoria-tickets');
        $tipoTickets = [];
        $tickets = Ticket::select('tickets.*', 'sub_listas.nombre AS categoria')->leftJoin('sub_listas', 'tickets.categoria_ticket_id', '=', 'sub_listas.id')->where('tickets.created_user_id', $this->userId->id)->get();
        foreach($tickets as $k => $ticket){
            $tickets[$k]->ticketEstado = TicketEstado::where('ticket_id', $ticket->id)->orderBy('updated_at', 'DESC')->first();
            $tickets[$k]->pendiente = SubLista::where('id', $tickets[$k]->ticketEstado->pendiente_ticket_id)->first();
            $tickets[$k]->asignado = SubLista::where('id', $tickets[$k]->ticketEstado->asignado_ticket_id)->first();
            $tickets[$k]->incidencia = SubLista::where('id', $tickets[$k]->ticketEstado->conincidencia_ticket_id)->first();
            $tickets[$k]->atendido = SubLista::where('id', $tickets[$k]->ticketEstado->atendido_ticket_id)->first();
        }
        return view($this->viewController . '.index', compact('styles', 'scripts', 'categoriaTickets', 'tipoTickets', 'tickets'));
    }

    /**
     * @param Request $request
     */
    public function create(Request $request)
    {
    }

    /**
     * @param TicketRequest $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(TicketRequest $request)
    {
        $messageFoto = "";
        $ticket = new Ticket($request->all());
        $ticket->created_user_id = $this->userId->id;
        $ticket->updated_user_id = $this->userId->id;
        $ticket->save();

        $countTicket = Ticket::count();
        $userPersona = UserPersona::where('user_id', $this->userId->id)->first();
        $persona = Persona::with('cargo')->find($userPersona->persona_id);

        $ticketUpdate = Ticket::with('categoriaTicket', 'tipoTicket')->find($ticket->id);
        $ticketUpdate->codigo = date('Ymd') . '-' . $persona->id . '-' . $countTicket;
        $ticketUpdate->save();

        //Ticket Estado
        $ticketPendiente = new TicketEstado();
        $ticketPendiente->ticket_id = $ticket->id;
        $ticketPendiente->pendiente_ticket_id = getInfoConstanteId('listas.ESTADOTICKETS', 'estadoTickets.PENDIENTE');//Pendiente
        $ticketPendiente->fecha_inicio_pendiente = date('Y-m-d H:i:s');
        $ticketPendiente->created_user_id = $this->userId->id;
        $ticketPendiente->updated_user_id = $this->userId->id;
        $ticketPendiente->save();

        $foto = $request->file('foto');
        //Ticket Foto
        if (isset($foto) && $foto != null and is_array($foto)) {
            foreach($foto as $file){
                if(!is_null($file)) {
                    $ticketFoto = new TicketFoto();
                    $ticketFoto->foto = loadImagePersona($file, null, 'tickets');
                    $ticketFoto->ticket_id = $ticket->id;
                    $ticketFoto->save();
                    $messageFoto = 'y se creo la imagen';
                }
            }
        }

        //Envio de E-mail Pendiente
        if ($persona->email != null) {
            $emails = [$persona->email];

            $data = [];
            $data['numeroTicket'] = $ticketUpdate->codigo;
            $data['fechaCreacion'] = $ticketPendiente->fecha_inicio_pendiente;
            $data['categoria'] = $ticketUpdate->categoriaTicket->nombre;
            $data['tipo'] = $ticketUpdate->tipoTicket->nombre;
            $data['asunto'] = $ticketUpdate->asunto;
            $data['descripcion'] = $ticketUpdate->descripcion;

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

            Mail::send('admin.herramientas.email.tickets.pendiente', $data, function ($message) use ($ticketUpdate, $emails) {
                $message->from('administrador@almoperations.com', 'Sistema de Tickets');
                $message->to($emails);
                $message->subject('🔔 Recepción de Ticket #' . $ticketUpdate->codigo);
            });
        }

        $message = 'Se creo el ticket ' . $ticketUpdate->codigo . ' ' . $messageFoto . ' correctamente';
        messageFlash($message, 'success');
        return redirect()->route($this->routeController);
    }

    public function edit()
    {

    }

    public function update()
    {

    }

    public function destroy()
    {

    }

}
