<?php

namespace App\Http\Traits;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\RedirectResponse;

/**
 * Trait for toggling active status on models.
 * 
 * Use this trait in controllers that need to toggle is_active field.
 * 
 * @example
 * use App\Http\Traits\TogglesActiveStatus;
 * 
 * class ExampleController extends Controller
 * {
 *     use TogglesActiveStatus;
 * 
 *     public function toggle(Example $example): RedirectResponse
 *     {
 *         return $this->toggleActive($example, 'El ejemplo');
 *     }
 * }
 */
trait TogglesActiveStatus
{
    /**
     * Toggle the is_active status of a model.
     *
     * @param Model $model The model to toggle
     * @param string $resourceName The name of the resource for the flash message
     * @param string $field The field to toggle (default: 'is_active')
     * @return RedirectResponse
     */
    protected function toggleActive(Model $model, string $resourceName = 'Recurso', string $field = 'is_active'): RedirectResponse
    {
        $model->update([$field => !$model->{$field}]);

        $status = $model->{$field} ? 'activado' : 'desactivado';

        return back()->with('success', "{$resourceName} {$status} correctamente.");
    }

    /**
     * Toggle a boolean field on a model with custom messages.
     *
     * @param Model $model
     * @param string $field
     * @param string $activatedMessage
     * @param string $deactivatedMessage
     * @return RedirectResponse
     */
    protected function toggleField(
        Model $model, 
        string $field, 
        string $activatedMessage = 'Activado correctamente.', 
        string $deactivatedMessage = 'Desactivado correctamente.'
    ): RedirectResponse {
        $model->update([$field => !$model->{$field}]);

        $message = $model->{$field} ? $activatedMessage : $deactivatedMessage;

        return back()->with('success', $message);
    }
}
