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/demo.sports-crowd.com/app/Http/Controllers/AcademyPeriodController.php
<?php

namespace App\Http\Controllers;

use DataTables;
use App\Parameter;
use App\AcademyPeriod;
use App\AcademyPeriodErp;
use App\AcademyLocationPeriod;
use App\AcademyLocationUser;
use App\AcademyUser;
use App\Services\AcademyLocationsService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class AcademyPeriodController extends Controller
{
    private $start_months = [
        'Enero',
        'Febrero',
        'Marzo',
        'Abril',
        'Mayo',
        'Junio',
        'Julio',
        'Agosto',
        'Septiembre',
        'Octubre',
        'Noviembre',
        'Diciembre'
    ];

    private $end_months = [
        'Enero',
        'Febrero',
        'Marzo',
        'Abril',
        'Mayo',
        'Junio',
        'Julio',
        'Agosto',
        'Septiembre',
        'Octubre',
        'Noviembre',
        'Diciembre',
        'Siguiente Año Enero',
        'Siguiente Año Febrero',
        'Siguiente Año Marzo',
        'Siguiente Año Abril',
        'Siguiente Año Mayo',
        'Siguiente Año Junio',
        'Siguiente Año Julio',
        'Siguiente Año Agosto',
        'Siguiente Año Septiembre',
        'Siguiente Año Octubre',
        'Siguiente Año Noviembre',
        'Siguiente Año Diciembre'
    ];

    public function index()
    {
        $academyLocationsService = new AcademyLocationsService;
        $showFranchises = $academyLocationsService->showFranchises();
        return view('academy.periods.list', compact('showFranchises'));
    }

    public function indexAdd()
    {
        $syncERP = Parameter::select('sync_siesa')->first()->sync_siesa;
        return view('academy.periods.create')
            ->with('start_months', $this->start_months)
            ->with('end_months', $this->end_months)
            ->with('syncERP', $syncERP);
    }

    public function indexEdit($id)
    {
        $object = AcademyPeriod::with('academy_period_erp')->findOrFail($id);
        $syncERP = Parameter::select('sync_siesa')->first()->sync_siesa;
        return view('academy.periods.edit', compact('object'))
            ->with('start_months', $this->start_months)
            ->with('end_months', $this->end_months)
            ->with('syncERP', $syncERP);
    }

    public function tableFilter()
    {
        $obj = AcademyPeriod::select(
            'academy_periods.id',
            'academy_periods.name',
            'academy_periods.annual_installments',
            'academy_periods.discount',
            'academy_periods.active',
            'academy_periods.default',
            'academy_periods.init_month',
            'academy_periods.end_month',
            DB::raw('GROUP_CONCAT(DISTINCT(academy_locations.name) SEPARATOR ", ") AS locations')
        )->leftjoin('academy_location_periods', 'academy_location_periods.academy_period_id', '=', 'academy_periods.id')
            ->leftjoin('academy_locations', 'academy_locations.id', '=', 'academy_location_periods.academy_location_id');

        $academyLocationsService = new AcademyLocationsService;
        if (!$academyLocationsService->validateAuthorizedLocations()) {
            $authorizedLocations = $academyLocationsService->getAuthorizedLocations();
            $obj = $obj->whereIn('academy_location_periods.academy_location_id', $authorizedLocations);
        }

        $obj = $obj->groupBy(
            'academy_periods.id',
            'academy_periods.name',
            'academy_periods.annual_installments',
            'academy_periods.discount',
            'academy_periods.active',
            'academy_periods.default',
            'academy_periods.init_month',
            'academy_periods.end_month',
        )->orderBy('academy_periods.id', 'DESC');

        return DataTables::of($obj)
            ->addColumn('actions', function ($obj) {
                return '
                    <i class="fa fa-pencil iconMini" onClick="clickEdit(' . $obj->id . ')" data-id="' . $obj->id . '" data-toggle="tooltip" data-placement="bottom" title="Editar" style="cursor:pointer;"></i>
                    <i class="fa fa-trash iconMini" onClick="clickDelete(' . $obj->id . ')" data-id="' . $obj->id . '" data-toggle="tooltip" data-placement="bottom" title="Eliminar" style="cursor:pointer;"></i>
                ';
            })
            ->editColumn('init_month', function ($obj) {
                return $this->start_months[$obj->init_month - 1];
            })
            ->editColumn('end_month', function ($obj) {
                return $this->end_months[$obj->end_month - 1];
            })
            ->editColumn('active', function ($obj) {
                if ($obj->active == 0) {
                    return '<div class="switch"><label><div class="checkbox checbox-switch switch-success"> <label> ' . __('messages.no') . ' <input type="checkbox" onChange="chk(' . $obj->id . ')" data-id="' . $obj->id . '" id="Checkactive' . $obj->id . '" name="Checkactivo" /> <span></span>' . __('messages.yes') . ' </label></div> </label> </div>';
                } else {
                    return '<div class="switch"><label> <div class="checkbox checbox-switch switch-success"> <label>   ' . __('messages.no') . ' <input type="checkbox" onChange="chk(' . $obj->id . ')" data-id="' . $obj->id . '" id="Checkactive' . $obj->id . '" name="Checkactivo" checked="" />
                        <span></span> ' . __('messages.yes') . ' </label> </div>  </label> </div>';
                }
            })
            ->editColumn('default', function ($obj) {
                if ($obj->default == 0) {
                    return '<div class="switch"><label><div class="checkbox checbox-switch switch-success"> <label> ' . __('messages.no') . ' <input type="checkbox" onChange="setDefault(' . $obj->id . ')" data-id="' . $obj->id . '" id="Checkdefaul' . $obj->id . '" name="Checkactivo" /> <span></span>' . __('messages.yes') . ' </label></div> </label> </div>';
                } else {
                    return '<div class="switch"><label> <div class="checkbox checbox-switch switch-success"> <label>   ' . __('messages.no') . ' <input type="checkbox" onChange="setDefault(' . $obj->id . ')" data-id="' . $obj->id . '" id="Checkdefaul' . $obj->id . '" name="Checkactivo" checked="" />
                        <span></span> ' . __('messages.yes') . ' </label> </div>  </label> </div>';
                }
            })
            ->editColumn('locations', function ($obj) {
                if ($obj->locations) {
                    $locations = explode(',', $obj->locations);
                    $data = '';
                    foreach ($locations as $location) {
                        $data .= ('<li>' . $location . '</li>');
                    }
                    return $data;
                }
                return '';
            })
            ->rawColumns(['actions', 'init_month', 'end_month', 'active', 'default', 'locations'])
            ->make(true);
    }

    public function create(Request $request)
    {
        try {
            $academyLocationUserIds = AcademyLocationUser::select('academy_location_id')
                ->where('user_id', Auth::user()->id)
                ->pluck('academy_location_id');

            $academyPeriodId = AcademyPeriod::select('id')
                ->where([
                    ['name', $request->input('name')],
                    ['active', true]
                ])
                ->value('id');

            $existingLocationPeriod = AcademyLocationPeriod::whereIn('academy_location_id', $academyLocationUserIds)
                ->where('academy_period_id', $academyPeriodId)
                ->exists();

            if ($existingLocationPeriod) {
                return response(array("r" => false, "type" => "error", "title" => "Oops...", "m" => __('messages.already_exists', ['name' => $request->input('name')]), "data" => null));
            }
            if ($model = AcademyPeriod::create($request->all())) {
                if ($request->input('service_item_code')) {
                    AcademyPeriodErp::updateOrCreate(
                        ['academy_period_id' => $model->id],
                        [
                            'service_item_code' => $request->input('service_item_code'),
                            'academy_period_id' => $model->id
                        ]
                    );
                }

                $academyLocationsService = new AcademyLocationsService;
                if (!$academyLocationsService->validateAuthorizedLocations()) {
                    $authorizedLocations = $academyLocationsService->getAuthorizedLocations();
                    foreach ($authorizedLocations as $location) {
                        $data = new AcademyLocationPeriod;
                        $data->academy_location_id = $location;
                        $data->academy_period_id = $model->id;
                        $data->save();
                    }
                }

                $this->registerLog(Auth::user()->id, 'Crear periodo academia', json_encode($request->all()), "Create", $this->getModule($request));
                return response(array("r" => true, "type" => "success", "title" => "", "m" => __('messages.created_successfully'), "data" => $model->id));
            } else {
                return response(array("r" => false, "type" => "error", "title" => "Oops...", "m" => __('messages.error_creating'), "data" => null));
            }
        } catch (\Exception $e) {
            return response(
                array(
                    "r" => false,
                    "type" => "error",
                    "title" => "Oops...",
                    "m" => __($e->getMessage()),
                    "data" => null
                )
            );
        }
    }

    public function update(Request $request, $id)
    {
        try {
            $request['id'] = $id;
            $academyLocationUserIds = AcademyLocationUser::select('academy_location_id')
                ->where('user_id', $request['id'])
                ->pluck('academy_location_id');

            $academyPeriodId = AcademyPeriod::select('id')
                ->where([
                    ['name', $request->input('name')],
                    ['active', true]
                ])
                ->value('id');

            $existingLocationPeriod = AcademyLocationPeriod::whereIn('academy_location_id', $academyLocationUserIds)
                ->where('academy_period_id', $academyPeriodId)
                ->exists();

            if ($existingLocationPeriod) {
                return response(array("r" => false, "type" => "error", "title" => "Oops...", "m" => __('messages.already_exists', ['name' => $request->input('name')]), "data" => null));
            }
            $data = $request->except(['service_item_code']);
            if (AcademyPeriod::where('id', $id)->update($data)) {
                if ($request->input('service_item_code')) {
                    AcademyPeriodErp::updateOrCreate(
                        ['academy_period_id' => $id],
                        [
                            'service_item_code' => $request->input('service_item_code'),
                            'academy_period_id' => $id
                        ]
                    );
                }

                $academyLocationsService = new AcademyLocationsService;
                if (!$academyLocationsService->validateAuthorizedLocations()) {
                    AcademyLocationPeriod::where('academy_period_id', $id)->delete();
                    $authorizedLocations = $academyLocationsService->getAuthorizedLocations();
                    foreach ($authorizedLocations as $location) {
                        $data = new AcademyLocationPeriod;
                        $data->academy_location_id = $location;
                        $data->academy_period_id = $id;
                        $data->save();
                    }
                }

                $this->registerLog(Auth::user()->id, 'Editar periodo academia', json_encode($request->all()), "Update", $this->getModule($request));
                return response(array("r" => true, "type" => "success", "title" => "", "m" => __('messages.updated_successfully'), "data" => $id));
            } else {
                return response(array("r" => false, "type" => "error", "title" => "Oops...", "m" => __('messages.error_updating'), "data" => null));
            }
        } catch (\Exception $e) {
            return response(
                array(
                    "r" => false,
                    "type" => "error",
                    "title" => "Oops...",
                    "m" => __($e->getMessage()),
                    "data" => null
                )
            );
        }
    }

    public function delete(Request $request, $id)
    {
        try {
            $period = AcademyPeriod::find($id);

            // Elimina datos relacionados primero
            AcademyLocationPeriod::where('academy_period_id', $id)->delete();
            AcademyPeriodErp::where('academy_period_id', $id)->delete();

            if ($period && $period->delete()) {
                $this->registerLog(Auth::user()->id, 'Eliminó periodo academia', json_encode($period), "Delete", $this->getModule($request));
                return response(array("r" => true, "type" => "success", "title" => "", "m" => __('messages.deleted_successfully'), "data" => null));
            } else {
                return response(array("r" => false, "type" => "error", "title" => "Oops...", "m" => __('messages.error_removing'), "data" => null));
            }
        } catch (\Illuminate\Database\QueryException $e) {
            return response(array("r" => false, "type" => "error", "title" => "Oops...", "m" => __('messages.delete_relation_data') . ': ' . $e->getMessage(), "data" => null));
        }
    }

    public function activate(Request $request)
    {
        try {
            $id = $request['id'];
            $state = $request['state'];

            $period = AcademyPeriod::find($id);
            $period->active = $state;
            $period->update();

            $this->registerLog(Auth::user()->id, 'Activar/Desactivar periodo academia', json_encode($period), "Update", $this->getModule($request));
            return array('r' => true, 'd' => null, 'm' => __('messages.updated_successfully'));
        } catch (\Throwable $th) {
            return array('r' => false, 'd' => null, 'm' => __('messages.error_updating'));
        }
    }

    public function default(Request $request)
    {
        try {
            $id = $request['id'];
            $state = $request['state'];

            $obj = AcademyPeriod::where('default', 1)
                ->leftjoin('academy_location_periods', 'academy_location_periods.academy_period_id', '=', 'academy_periods.id');

            $academyLocationsService = new AcademyLocationsService;
            if (!$academyLocationsService->validateAuthorizedLocations()) {
                $authorizedLocations = $academyLocationsService->getAuthorizedLocations();
                $obj = $obj->whereIn('academy_location_periods.academy_location_id', $authorizedLocations);
            }
            $obj = $obj->update(['default' => 0]);

            $period = AcademyPeriod::find($id);
            $period->default = $state;
            $period->update();

            $this->registerLog(Auth::user()->id, 'Default periodo academia', json_encode($period), "Update", $this->getModule($request));
            return array('r' => true, 'd' => null, 'm' => __('messages.updated_successfully'));
        } catch (\Throwable $th) {
            return array('r' => false, 'd' => null, 'm' => __('messages.error_updating'));
        }
    }

    public function validateDefaultPeriod($academyUserId)
    {
        // Obtener franquicia del usuario de academia
        $academyUserLocation = AcademyUser::select('academy_categories.academy_location_id')
            ->join('academy_categories', 'academy_categories.id', '=', 'academy_users.academy_category_id')
            ->where('academy_users.id', $academyUserId)->first();

        if (!$academyUserLocation) {
            return false;
        }

        $academyLocationsService = new AcademyLocationsService;
        $showFranchises = $academyLocationsService->enableFranchises() == 'true';

        // Obtener periodo por defecto
        $academyDefaultPeriod = AcademyPeriod::select('academy_periods.*')
            ->when($showFranchises, function ($query) use ($academyUserLocation) {
                $query
                    ->leftjoin('academy_location_periods', 'academy_location_periods.academy_period_id', '=', 'academy_periods.id')
                    ->where('academy_location_periods.academy_location_id', $academyUserLocation->academy_location_id);
            })
            ->where('default', 1)->where('active', 1);

        return $academyDefaultPeriod->first() ?: false;
    }
}