HEX
Server: Apache/2.4.41 (Ubuntu)
System: Linux ip-172-31-42-149 5.15.0-1084-aws #91~20.04.1-Ubuntu SMP Fri May 2 07:00:04 UTC 2025 aarch64
User: ubuntu (1000)
PHP: 7.4.33
Disabled: pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_get_handler,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,pcntl_async_signals,pcntl_unshare,
Upload Files
File: /var/www/vhost/disk-apps/agile-selling-wpb/app/Http/Controllers/TicketsController.php
<?php

namespace App\Http\Controllers;

use DB;
use App\Seat;
use App\Door;
use App\Zone;
use App\Team;
use App\Ticket;
use Carbon\Carbon;
use App\Parameter;
use App\TicketLog;
use App\TicketMain;
use App\TicketType;
use App\MatchEvent;
use App\TicketUserBlock;
use App\MatchEventZonePrice;
use Illuminate\Http\Request;
use App\Http\Controllers\UserController;
use Illuminate\Support\Facades\Auth;
use Illuminate\Database\Eloquent\Builder;

class TicketsController extends Controller
{
    private $parameters;

    public function __construct()
    {
        $this->parameters = Parameter::where('id',1)->first();
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $list_events = $this->getMatchEvents();
        $events = [];
        foreach ($list_events as $key => $event) {
            if ($this->validateDate($event->event_start_sale, "start") && $this->validateDate($event->event_end_sale, "end")) {
                $events[] = $event;
            }
        }
        if(Auth::user()->rol->id == 7){
            $types = TicketType::where([['id', '!=', 3],['active', true]])->get();
        }else{
            $types = TicketType::where('active', true)->get();
        }
        return view('tickets.list', compact('events','types'));
    }

    public function getMatchEvents()
    {
        return MatchEvent::where('active', true)->get();
    }

    public function getSeats($zone_id,$event_id)
    {
        try {
            $seats = Seat::where('zone_id', $zone_id)->with('letter')
                        ->orderBy('letter_id', 'desc')
                        ->orderBy('code', 'asc')
                        ->get();
            foreach ($seats as $key => $seat) {
                $seat->ticket = Ticket::where([['seat_id',$seat->id],['match_event_id', $event_id]])->latest()->first();
                $seat->ticket_user_block = TicketUserBlock::where([['seat_id',$seat->id],['match_event_id', $event_id]])->latest()->first();
            }
            return response(array("r" => true, "type" => "success", "title" => "", "m" => "", "data" => $seats));
        } catch (\Throwable $th) {
            return response(array("r" => false, "type" => "error", "title" => "Oops...", "origin" => "getSeats", "m" => __('messages.error_creating'), "data" => $th->getMessage()));
        }
    }

    public function getSeatPrice($zone_id,$event_id)
    {
        try {
            $price = MatchEventZonePrice::where([['zone_id', $zone_id],['match_event_id', $event_id]])->first();
            return response(array("r" => true, "type" => "success", "title" => "", "m" => "", "data" => $price));
        } catch (\Throwable $th) {
            return response(array("r" => false, "type" => "error", "title" => "Oops...", "origin" => "getSeatPrice", "m" => __('messages.error_creating'), "data" => $th->getMessage()));
        }
    }

    public function searchUser(Request $request, $document)
    {
        try {
            $user = new UserController($request);
            $search = $user->searchUser($document);
            return response(array("r" => true, "type" => "success", "title" => "", "m" => "", "data" => $search));
        } catch (\Throwable $th) {
            return response(array("r" => false, "type" => "error", "title" => "Oops...", "origin" => "searchUser", "m" => __('messages.error_creating'), "data" => $th->getMessage()));
        }
    }

    public function createBlockTicket($seat_id,$match_event_id,$user_id,$ticket_type_id,$ticket_main_id,$zone_id,$pin = false,$is_social_distancing = false)
    {
        try {
            $minutesToBlock = 0;
            // Se procesa venta libre
            if($ticket_type_id == 1){
                $minutesToBlock = $this->parameters->maximum_sale_blocking_time;
                $this->processBlockGeneralTicket($seat_id, $match_event_id, $user_id, $minutesToBlock, $ticket_type_id, $ticket_main_id,$zone_id,$is_social_distancing);
            }

            // Se procesa venta abonado
            if($ticket_type_id == 2){
                $minutesToBlock = $this->parameters->maximum_suscription_blocking_time;
                $this->processBlockSubscriptionTicket($seat_id, $match_event_id, $user_id, $minutesToBlock, $ticket_type_id, $ticket_main_id,$zone_id,$is_social_distancing);
            }

            // mensaje mostrando el tiempo limite que tiene para efectuar la compra
            $messageBlockMinutes = Carbon::now()->addMinutes($minutesToBlock)->format('h:i:s A');
            $message = __('messages.create_block',['dateblock' => $messageBlockMinutes]) ;

            if($pin){
                $message = $message . "\n" . __('messages.create_block_2') . $pin;
            }else{
                $message = $message . __('messages.create_block_3');
            }
            return array("r" => true, "type" => "error", "title" => "Oops...", "origin" => "createBlockTicket", "m" => $message, "data" => null);
        } catch (\Throwable $th) {
            return array("r" => false, "type" => "error", "title" => "Oops...", "origin" => "createBlockTicket", "m" => __('messages.error_global'), "data" => $th->getMessage());
        }
    }

    public function getSeatBlockdistancing_x($index_init,$array_search)
    {
        // definimos el index de inicio de bloqueo a la izquierda y derecha deacuerdo al parametro de numero de sillas a bloquear
        $init_block_left = $index_init - $this->parameters->social_distancing_number_seat_x;
        $init_block_right = $index_init + $this->parameters->social_distancing_number_seat_x;

        $list_block_distancing = [];

        foreach ($array_search as $key2 => $id) {
            if($this->parameters->social_distancing_left){
                if($key2 >= $init_block_left && $key2 < $index_init){
                    $list_block_distancing[] = $id;
                }
            }

            if($this->parameters->social_distancing_right){
                if($key2 > $index_init && $key2 <= $init_block_right){
                    $list_block_distancing[] = $id;
                }
            }
        }

        return $list_block_distancing;
    }

    public function getSeatBlockdistancing_y($index_init,$array_search,$array_file_origin)
    {
        $number_differente = 0;
        // definimos el index de inicio de bloqueo de arriba y abajo deacuerdo al parametro de numero de sillas a bloquear
        if(count($array_file_origin) != count($array_search)){
            $number_differente = count($array_search) - count($array_file_origin);
        }
        if($number_differente){
            $index_init = $index_init + ($number_differente/2);
        }

        $init_block_left = $index_init - $this->parameters->social_distancing_number_seat_y;
        $init_block_right = $index_init + $this->parameters->social_distancing_number_seat_y;

        $list_block_distancing = [];

        foreach ($array_search as $key2 => $id) {
            if($key2 == $index_init){
                $list_block_distancing[] = $id;
            }

            if($key2 >= $init_block_left && $key2 < $index_init){
                $list_block_distancing[] = $id;
            }

            if($key2 > $index_init && $key2 <= $init_block_right){
                $list_block_distancing[] = $id;
            }
        }

        return $list_block_distancing;
    }

    public function getGroupSeatByLetter($zone_id,$letter_id)
    {
        $resp = [];
        // $c = Seat::where([['zone_id',$zone_id],['letter_id', $letter_id]])->pluck('code')->toArray();
        $c = Seat::where([['zone_id',$zone_id],['letter_id', $letter_id]])->pluck('id')->toArray();
        if($c){
            $resp = $c;
        }
        return $resp;
    }

    public function searchNeighbour($seat_id,$zone_id)
    {
        $list_block_distancing = [];
        $seat = Seat::where('id', $seat_id)->first();
        if($seat){
            $seats_group = Seat::where('zone_id',$zone_id)->distinct()->pluck('letter_id')->toArray();
            $ids_x_group = $this->getGroupSeatByLetter($zone_id,$seat->letter_id);

            // buscamos la fila vecina de arriba y la de abajo
            $letter_id_top = 0;
            $letter_id_bottom = 0;
            foreach ($seats_group as $key => $letter) {
                if($letter == $seat->letter_id){
                    if(isset($seats_group[$key+1]) && $this->parameters->social_distancing_top){
                        $letter_id_top = $seats_group[$key+1];
                    }
                    if(isset($seats_group[$key-1]) && $this->parameters->social_distancing_bottom){
                        $letter_id_bottom = $seats_group[$key-1];
                    }
                }
            }

            // buscamos el index de la silla de la fila origen a comprar por el usuario
            // $index_seat_buy = array_search($seat->code, $ids_x_group);
            $index_seat_buy = array_search($seat->id, $ids_x_group);

            // Consultamos la sillas a bloquear en el eje x basado en el index de la silla a comprar por el cliente
            $list_block_distancing = array_merge($this->getSeatBlockdistancing_x($index_seat_buy,$ids_x_group),$list_block_distancing);

            // Consultamos la sillas a bloquear en el eje y basado en el index de la silla a comprar por el cliente
            if($letter_id_top != 0 && $this->parameters->social_distancing_top){
                $ids_top_group = $this->getGroupSeatByLetter($zone_id,$letter_id_top);
                $list_block_distancing = array_merge($this->getSeatBlockdistancing_y($index_seat_buy,$ids_top_group,$ids_x_group),$list_block_distancing);
            }

            if($letter_id_bottom != 0 && $this->parameters->social_distancing_bottom){
                $ids_bottom_group = $this->getGroupSeatByLetter($zone_id,$letter_id_bottom);
                $list_block_distancing = array_merge($this->getSeatBlockdistancing_y($index_seat_buy,$ids_bottom_group,$ids_x_group),$list_block_distancing);
            }
        }
        return $list_block_distancing;
    }

    public function deleteBlock($seat_id,$match_event_id,$user_id)
    {
        try {
            TicketUserBlock::where([['seat_id', $seat_id],['match_event_id', $match_event_id],['user_id', $user_id]])->delete();
        } catch (\Throwable $th) {
            return response(array("r" => false, "type" => "error", "title" => "Oops...", "origin" => "deleteBlock", "m" => __('messages.error_global'), "data" => $th->getMessage()));
        }
    }

    private function createNewBlock($data)
    {
        TicketUserBlock::create($data);
    }

    private function processBlockGeneralTicket($seat_id, $match_event_id, $user_id, $minutesToBlock, $ticket_type_id,$ticket_main_id,$zone_id,$is_social_distancing)
    {
        $price = 0;
        if(!$is_social_distancing){
            $zonePrice = MatchEventZonePrice::where([['zone_id', $zone_id],['match_event_id', $match_event_id]])->first();
            if($zonePrice){
                $price = $zonePrice->price;
            }
        }
        $data = [
            'seat_id'               =>  $seat_id,
            'match_event_id'        =>  $match_event_id,
            'user_id'               =>  $user_id,
            'zone_id'               =>  $zone_id,
            'start_block'           =>  Carbon::now(),
            'end_block'             =>  Carbon::now()->addMinutes($minutesToBlock),
            'is_social_distancing'  =>  $is_social_distancing,
            'price'                 =>  $price,
            'ticket_type_id'        =>  $ticket_type_id,
            'ticket_main_id'        =>  $ticket_main_id,
        ];
        $this->createNewBlock($data);
    }

    private function processBlockSubscriptionTicket($seat_id, $match_event_id, $user_id, $minutesToBlock, $ticket_type_id,$ticket_main_id,$zone_id,$is_social_distancing)
    {
        $price = 0;
        $main_match = MatchEvent::find($match_event_id);
        $tournament_id = $main_match->tournament_id;

        // consultamos partidos futuros a partir de la fecha del evento origen y realizamos el bloqueo
        $matches_subscription = MatchEvent::where('tournament_id', $tournament_id)
                                            ->where('event_start', '>', $main_match->event_start)
                                            ->get();

        if(!$is_social_distancing){
            $zonePrice = MatchEventZonePrice::where([['zone_id', $zone_id],['match_event_id', $match_event_id]])->first();
            if($zonePrice){
                $price = $zonePrice->price_suscription;
            }
            if(count($matches_subscription)){
                $price = $price / (count($matches_subscription) + 1);
                $price = number_format($price, 0, ".", "");
            }
        }

        // cramos bloqueo evento origen
        $data = [
            'seat_id'               =>  $seat_id,
            'match_event_id'        =>  $match_event_id,
            'user_id'               =>  $user_id,
            'zone_id'               =>  $zone_id,
            'start_block'           =>  Carbon::now(),
            'end_block'             =>  Carbon::now()->addMinutes($minutesToBlock),
            'is_social_distancing'  =>  $is_social_distancing,
            'price'                 =>  $price,
            'ticket_type_id'        =>  $ticket_type_id,
            'ticket_main_id'        =>  $ticket_main_id,
        ];
        $this->createNewBlock($data);

        foreach($matches_subscription as $m){
            $data = [
                'seat_id'               =>  $seat_id,
                'match_event_id'        =>  $m->id,
                'user_id'               =>  $user_id,
                'zone_id'               =>  $zone_id,
                'start_block'           =>  Carbon::now(),
                'end_block'             =>  Carbon::now()->addMinutes($minutesToBlock),
                'is_social_distancing'  =>  $is_social_distancing,
                'price'                 =>  $price,
                'ticket_type_id'        =>  $ticket_type_id,
                'ticket_main_id'        =>  $ticket_main_id,
            ];
            $this->createNewBlock($data);
        }
    }

    // Genera Pin aleatorio gane.
    public function generatepin()
    {
        $date = Carbon::now();
        return $date->getTimestamp() . rand(10,99) . rand(0,9);
    }

    public function createTicket($seat_id,$match_event_id,$user_id,$ticket_type_id,$ticket_main_id,$price)
    {
        try {
            $current_seat = Seat::select('code','zone_id')->where('id', $seat_id)->first();
            $zone = Zone::select('name','door_id')->where('id', $current_seat->zone_id)->first();
            $event = MatchEvent::select('code')->where('id', $match_event_id)->first();
            $door_name = null;
            if($zone && $zone->door_id){
                $c_q = Door::select('name')->where('id', $zone->door_id)->first();
                if($c_q){
                    $door_name = $c_q->name;
                }
            }

            $ticket = Ticket::create([
                'code_ticket'       => "DIM" . $this->generatepin(),
                'seat_id'           => $seat_id,
                'match_event_id'    => $match_event_id,
                'user_id'           => $user_id,
                'ticket_type_id'    => $ticket_type_id,
                'ticket_status_id'  => 1,
                'price'             => $price,
                'zone'              => $zone->name,
                'code_seat'         => $current_seat->code,
                'code_event'        => $event->code,
                'door'              => $door_name,
                'ticket_main_id'    => $ticket_main_id,
            ]);

            if($ticket){
                $this->createLogTicket(1,$ticket->id);
                $message = __('messages.create_ticket');
                return array("r" => true, "type" => "error", "title" => "Oops...", "origin" => "createTicket", "m" => $message, "data" => null);
            }

            return array("r" => false, "type" => "error", "title" => "Oops...", "origin" => "createTicket", "m" => __('messages.error_global'), "data" => null);
        } catch (\Throwable $th) {
            return array("r" => false, "type" => "error", "title" => "Oops...", "origin" => "createTicket", "m" => __('messages.error_global'), "data" => $th->getMessage());
        }
    }

    public function existsTicket($seat_id,$event_id,$user_id)
    {
        if($this->parameters->is_social_distancing){
            return Ticket::where([['seat_id',$seat_id],['match_event_id', $event_id],['user_id', '!=', $user_id]])->latest()->first();
        }else{
            return Ticket::where([['seat_id',$seat_id],['match_event_id', $event_id]])->latest()->first();
        }
    }

    public function existsBlock($seat_id,$event_id,$user_id)
    {
        if($this->parameters->is_social_distancing){
            return TicketUserBlock::where([['seat_id',$seat_id],['match_event_id', $event_id],['is_social_distancing', false],['user_id', '!=', $user_id]])->latest()->first();
        }else{
            return TicketUserBlock::where([['seat_id',$seat_id],['match_event_id', $event_id]])->latest()->first();
        }
    }

    public function infoSeat($seat_id)
    {
        return Seat::where('id', $seat_id)->with('letter')->first();
    }

    public function validateBlockDistancing($ticket_main_id)
    {
        $distancing = TicketUserBlock::where([['ticket_main_id',$ticket_main_id],['is_social_distancing', true]])->get();
        foreach ($distancing as $item) {
            $item->end_block = null;
            $item->update();
        }
    }

    public function validateSell($zone_id, $event_id, $seat_id, $user_id, $ticket_type_id, $ticket_main_id, $type_process, $price, $pin = false, $is_transaction = false)
    {
        if($is_transaction){
            DB::beginTransaction();
        }
        try {
            $zone = Zone::where('id', $zone_id)->first();
            $matchEvents = Ticket::where('match_event_id', $event_id)
                                ->whereHas('seat', function (Builder $query) use ($zone_id){
                                    $query->where('zone_id', $zone_id);
                                })
                                ->get()
                                ->count();

            // se valida la capacidad de la localidad no este superada
            if($matchEvents >= $zone->salable_capacity){
                return response(array("r" => false, "type" => "error", "title" => "Oops...", "origin" => "validateSell", "m" => __('messages.error_validation_8'), "data" => null));
            }

            // se consulta y valida si existe un ticket o un bloqueo para esa silla
            $ticket_current = $this->existsTicket($seat_id,$event_id,$user_id);
            $ticket_block = $this->existsBlock($seat_id,$event_id,$user_id);

            if($ticket_current){
                $seat = $this->infoSeat($seat_id);
                $name_seat = "";
                if($seat){
                    $name_seat = $seat->letter->name . $seat->code;
                }
                return response(array("r" => false, "type" => "error", "title" => "Oops...", "origin" => "validateSell", "m" => __('messages.error_validation_3', ['seat' => $name_seat]), "data" => null));
            }

            if($ticket_block){
                $seat = $this->infoSeat($seat_id);
                $name_seat = "";
                if($seat){
                    $name_seat = $seat->letter->name . $seat->code;
                }
                return response(array("r" => false, "type" => "error", "title" => "Oops...", "origin" => "validateSell", "m" => __('messages.error_validation_4', ['seat' => $name_seat]), "data" => null));
            }

            // $price = MatchEventZonePrice::where([['zone_id', $zone_id],['match_event_id', $event_id]])->first();

            // if($ticket_type_id == 1 && $price->price == 0 || !$price->price){
            //     return response(array("r" => false, "type" => "error", "title" => "Oops...", "origin" => "validateSell", "m" => __('messages.error_validation_1'), "data" => null));
            // }

            // if($ticket_type_id == 2 && $price->price_suscription == 0 || !$price->price_suscription){
            //     return response(array("r" => false, "type" => "error", "title" => "Oops...", "origin" => "validateSell", "m" => __('messages.error_validation_2'), "data" => null));
            // }

            $userTicketsBallosts = Ticket::where([['ticket_type_id', 1],['match_event_id', $event_id],['user_id', $user_id]])->get()->count();
            $userTicketsSuscription = Ticket::where([['ticket_type_id', 2],['match_event_id', $event_id],['user_id', $user_id]])->get()->count();
            $userTicketsBlock = TicketUserBlock::where([['match_event_id', $event_id],['user_id', $user_id],['is_social_distancing', false],['ticket_main_id', '!=', $ticket_main_id]])->get()->count();

            // Valida el numero maximo de boletas que puede comprar el usuario.
            if($ticket_type_id == 1 && $userTicketsBallosts >= $this->parameters->maximum_number_ballots){
                return response(array("r" => false, "type" => "error", "title" => "Oops...", "origin" => "validateSell", "m" => __('messages.error_validation_5'), "data" => null));
            }

            if($ticket_type_id == 1 && $userTicketsBlock + $userTicketsBallosts >= $this->parameters->maximum_number_locks){
                return response(array("r" => false, "type" => "error", "title" => "Oops...", "origin" => "validateSell", "m" => __('messages.error_validation_7'), "data" => null));
            }

            // Valida el numero máximo de abonos.
            if($ticket_type_id == 2 && $userTicketsSuscription >= $this->parameters->maximum_number_suscription){
                return response(array("r" => false, "type" => "error", "title" => "Oops...", "origin" => "validateSell", "m" => __('messages.error_validation_6'), "data" => null));
            }

            if($ticket_type_id == 2 && $userTicketsBlock + $userTicketsSuscription >= $this->parameters->maximum_number_locks){
                return response(array("r" => false, "type" => "error", "title" => "Oops...", "origin" => "validateSell", "m" => __('messages.error_validation_7_2'), "data" => null));
            }

            // si esta activo la logica de compra con distanciamiento social
            if($this->parameters->is_social_distancing){
                // buscamos los vecinos de la silla origen, para validar si pueden ser bloqueadas
                $list_block_distancing = $this->searchNeighbour($seat_id,$zone_id);
                foreach ($list_block_distancing as $item) {
                    $current_block = $this->existsBlock($item,$event_id,$user_id);
                    $current_ticket = $this->existsTicket($item,$event_id,$user_id);
                    if($current_block || $current_ticket){
                        $seat = $this->infoSeat($seat_id);
                        $name_seat = "";
                        if($seat){
                            $name_seat = $seat->letter->name . $seat->code;
                        }
                        return response(array("r" => false, "type" => "error", "title" => "Oops...", "origin" => "validateSell", "m" => __('messages.error_validation_9', ['seat' => $name_seat]), "data" => $item));
                        break;
                    }
                }
            }

            if($type_process == "ticket"){
                $transaction = $this->createTicket($seat_id,$event_id,$user_id,$ticket_type_id,$ticket_main_id,$price);
                if($this->parameters->is_social_distancing){
                    $this->validateBlockDistancing($ticket_main_id);
                }
                if($is_transaction){
                    if($transaction["r"]){
                        DB::commit();
                    }else{
                        DB::rollback();
                    }
                }
                return response($transaction);
            }else{
                $transaction = $this->createBlockTicket($seat_id,$event_id,$user_id,$ticket_type_id,$ticket_main_id,$zone_id,$pin);
                if($this->parameters->is_social_distancing){
                    // se realiza el bloqueo de las sillas vecinas por distanciamiento
                    foreach ($list_block_distancing as $item) {
                        // se consulta si la silla vecina actual en el ciclo es una silla de las que se va a comprar, para no realizar el bloqueo
                        $is_buy_seat = TicketUserBlock::where([['seat_id', $item],['user_id', $user_id],['match_event_id', $event_id],['is_social_distancing', false]])->first();
                        if(!$is_buy_seat){
                            $this->createBlockTicket($item,$event_id,$user_id,$ticket_type_id,$ticket_main_id,$zone_id,$pin,true);
                        }
                    }
                    // se elimina cualquier bloqueo de la silla a comprar si es del mismo usuario y tiene bloqueo por distanciamiento
                    $list_distancing = TicketUserBlock::where([
                            ['seat_id', $seat_id],
                            ['user_id', $user_id],
                            ['match_event_id', $event_id],
                            ['is_social_distancing', true]
                        ])->get();
                    foreach ($list_distancing as $d_seat) {
                        $d_seat->delete();
                    }
                }
                if($is_transaction){
                    if($transaction["r"]){
                        DB::commit();
                    }else{
                        DB::rollback();
                    }
                }
                return response($transaction);
            }

        } catch (\Throwable $th) {
            if($is_transaction){
                DB::rollback();
            }
            return response(array("r" => false, "type" => "error", "title" => "Oops...", "origin" => "validateSell", "m" => __('messages.error_global'), "data" => $th->getMessage()));
        }
    }

    public function createBlock(Request $request)
    {
        DB::beginTransaction();
        try {
            $userController = new UserController($request);
            $user = $userController->searchUser($request->document,$request->email,$request->first_name,$request->last_name,$request->phone);
            if(!$user){
                $current_user = $userController->createClient($request,true);
                if($current_user["r"]){
                    $user = $current_user["d"];
                }else{
                    DB::rollback();
                    return response($current_user);
                }
            }

            $pin = $this->generatepin();
            $main = TicketMain::create([
                'total'         => $request->input('amount'),
                'pin_tercero'   => $pin,
            ]);

            foreach ($request->input('tickets') as $key => $ticket) {
                $zone_id = $ticket["seat"]["zone_id"];
                $event_id = $ticket["match_event_id"];
                $seat_id = $ticket["seat"]["id"];
                $user_id = $user->id;

                // creamos los bloqueos
                $data = $this->validateSell($zone_id,$event_id,$seat_id,$user_id,$ticket["ticket_type_id"],$main->id,$request->input('type_process'),0,$pin);
                $response = json_decode($data->getContent());
                if(!$response->r){
                    DB::rollback();
                    return $data;
                    break;
                }
            }
            DB::commit();
            return $data;
        } catch (\Throwable $th) {
            DB::rollback();
            return response(array("r" => false, "type" => "error", "title" => "Oops...", "origin" => "createBlock", "m" => __('messages.error_global'), "data" => $th->getMessage()));
        }
    }

    public function getMatchEventsSuscription($match_event_id,$is_data = false)
    {
        try {
            $current_match = MatchEvent::where('id', $match_event_id)->first();
            $list_match_events = MatchEvent::where([
                                                ['tournament_id', $current_match->tournament_id],
                                                ['event_start', '>', $current_match->event_start]
                                            ])
                                            ->with('team')
                                            ->get();
            if($is_data){
                return $list_match_events;
            }
            $team_main = Team::where([['is_main', true],['active', true]])->first();
            return response(array("r" => true, "type" => "success", "title" => "", "m" => "", "data" => array('list_match_events' => $list_match_events, 'team_main' => $team_main)));
        } catch (\Throwable $th) {
            return response(array("r" => false, "type" => "error", "title" => "Oops...", "origin" => "getMatchEventsSuscription", "m" => __('messages.error_global'), "data" => $th->getMessage()));
        }
    }

    /*
        @tickets Type TicketUserBlock listado de bloqueos.
        @ticket_main_id Type int id de la cabecera de ticketes.
    */
    public function generateTickets($tickets,$ticket_main_id)
    {
        DB::beginTransaction();
        try {
            foreach ($tickets as $key => $t) {
                // eliminamos el bloqueo.
                $this->deleteBlock($t->seat_id,$t->match_event_id,$t->user_id);
                // Validamos la silla y creamos el ticket
                $data = $this->validateSell($t->zone_id,$t->match_event_id,$t->seat_id,$t->user_id,$t->ticket_type_id,$ticket_main_id,'ticket',$t->price);
                $response = json_decode($data->getContent());
                if(!$response->r){
                    DB::rollback();
                    return false;
                    break;
                }
            }
            DB::commit();
            return true;
        } catch (\Throwable $th) {
            DB::rollback();
            return false;
        }
    }

    public function createLogTicket($state_id,$ticket_id)
    {
        try {
            TicketLog::create(['ticket_id' => $ticket_id, 'ticket_status_id' => $state_id]);
            return response(array("r" => true, "type" => "success", "title" => "", "m" => "", "data" => null));
        } catch (\Throwable $th) {
            return response(array("r" => false, "type" => "error", "title" => "Oops...", "origin" => "createLogTicket", "m" => __('messages.error_global'), "data" => $th->getMessage()));
        }
    }

    public function changeStateTicket(Request $request)
    {
        try {
            if(Ticket::where('id',$request->ticket_id)->update(['ticket_status_id' => $request->state_id, 'created_at' => Carbon::now()])){
                $this->createLogTicket($request->state_id,$request->ticket_id);
            }
            return response(array("r" => true, "type" => "success", "title" => "Ok", "m" => __('messages.updated_successfully'), "data" => null));
        } catch (\Throwable $th) {
            return response(array("r" => false, "type" => "error", "title" => "Oops...", "m" => __('messages.error_global'), "data" => $th->getMessage()));
        }
    }

    // public function generateMassiveTickets($event_id,$start,$end)
    // {
    //     for ($i=$start; $i < $end; $i++) {
    //         $this->createTicket($i,$event_id,2,rand(1,2),1,130000);
    //     }
    //     dd("Oki :)");
    // }
}