HEX
Server: Apache/2.4.58 (Ubuntu)
System: Linux Bradford-Sitios 6.14.0-1017-azure #17~24.04.1-Ubuntu SMP Mon Dec 1 20:10:50 UTC 2025 x86_64
User: www-data (33)
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/matriculas_api_dev/app/Http/Controllers/ContractFormatController.php
<?php

namespace App\Http\Controllers;

use App\Models\ContractFormat;
use App\Models\Period;
use Exception;
use Illuminate\Http\Request;

class ContractFormatController extends Controller
{
    /**
     * Listar todos los períodos con su formato de contrato asociado.
     */
    public function list()
    {
        try {
            $periods = Period::where('deleted', 0)
                ->orderBy('period_year', 'desc')
                ->with('contractFormat')
                ->get()
                ->map(function ($period) {
                    return [
                        'id' => $period->id,
                        'period_year' => $period->period_year,
                        'period' => $period->period,
                        'status' => $period->status,
                        'contract_format' => $period->contractFormat ? [
                            'id' => $period->contractFormat->id,
                            'contract_format' => $period->contractFormat->contract_format,
                            'has_template' => !empty($period->contractFormat->description),
                            'updated_at' => $period->contractFormat->updated_at,
                        ] : null,
                    ];
                });

            return genericResponse(['data' => $periods, 'message' => 'ok', 'code' => 200], 200);
        } catch (Exception $e) {
            $errorCode = $e->getCode();
            return genericResponse(['error' => $e->getMessage()], $errorCode ?: 500);
        }
    }

    /**
     * Obtener formato de contrato por period_id.
     */
    public function showByPeriod($periodId)
    {
        try {
            $period = Period::find($periodId);
            if (!$period) {
                throw new Exception("Período no encontrado", 404);
            }

            $format = ContractFormat::where('period_id', $periodId)
                ->where('deleted', 0)
                ->first();

            $data = [
                'period_id' => (int) $periodId,
                'period_year' => $period->period_year,
                'period' => $period->period,
                'id' => $format->id ?? null,
                'contract_format' => $format->contract_format ?? null,
                'description' => $format->description ?? '',
                'updated_at' => $format->updated_at ?? null,
            ];

            return genericResponse(['data' => $data, 'message' => 'ok', 'code' => 200], 200);
        } catch (Exception $e) {
            $errorCode = $e->getCode();
            return genericResponse(['error' => $e->getMessage()], $errorCode ?: 500);
        }
    }

    /**
     * Crear o actualizar formato de contrato para un período.
     */
    public function storeOrUpdate(Request $request)
    {
        try {
            $request->validate([
                'period_id' => 'required|integer|exists:periods,id',
                'description' => 'required|string',
            ], [
                'period_id.required' => 'El período es requerido',
                'period_id.exists' => 'El período no existe',
                'description.required' => 'El template del contrato es requerido',
            ]);

            $period = Period::find($request->period_id);

            $format = ContractFormat::where('period_id', $request->period_id)
                ->where('deleted', 0)
                ->first();

            if ($format) {
                $format->description = $request->description;
                $format->updated_at = now();
                $format->user_updated = auth()->check() ? auth()->id() : null;
                $format->save();
            } else {
                $format = ContractFormat::create([
                    'period_id' => $request->period_id,
                    'contract_format' => 'Contrato ' . ($period->period_year ?? ''),
                    'description' => $request->description,
                    'status' => 1,
                    'user_created' => auth()->check() ? auth()->id() : null,
                    'user_updated' => auth()->check() ? auth()->id() : null,
                ]);
            }

            return genericResponse(['data' => null, 'message' => 'Template de contrato guardado correctamente', 'code' => 200], 200);
        } catch (Exception $e) {
            $errorCode = $e->getCode();
            return genericResponse(['error' => $e->getMessage()], $errorCode ?: 500);
        }
    }

    /**
     * Copiar template de contrato de un periodo a otro.
     */
    public function copy(Request $request)
    {
        try {
            $request->validate([
                'from_period_id' => 'required|integer',
                'to_period_id'   => 'required|integer',
            ]);

            $source = ContractFormat::where('period_id', $request->from_period_id)
                ->where('deleted', 0)
                ->first();

            if (!$source || empty($source->description)) {
                throw new Exception('El período origen no tiene template de contrato', 404);
            }

            $targetPeriod = Period::find($request->to_period_id);
            if (!$targetPeriod) {
                throw new Exception('Período destino no encontrado', 404);
            }

            $existing = ContractFormat::where('period_id', $request->to_period_id)
                ->where('deleted', 0)
                ->first();

            if ($existing) {
                $existing->description = $source->description;
                $existing->updated_at = now();
                $existing->user_updated = auth()->id();
                $existing->save();
            } else {
                ContractFormat::create([
                    'period_id'       => $request->to_period_id,
                    'contract_format' => 'Contrato ' . ($targetPeriod->period_year ?? ''),
                    'description'     => $source->description,
                    'status'          => 1,
                    'user_created'    => auth()->id(),
                ]);
            }

            return genericResponse([
                'data'    => null,
                'message' => 'Template de contrato copiado correctamente',
                'code'    => 200,
            ], 200);
        } catch (Exception $e) {
            $errorCode = $e->getCode();
            return genericResponse(['error' => $e->getMessage()], $errorCode ?: 500);
        }
    }
}