> ## Documentation Index
> Fetch the complete documentation index at: https://docs.rocky.global/llms.txt
> Use this file to discover all available pages before exploring further.

# API DOCUMENTATION

# Event Management System API Documentation

## Table of Contents

1. [Overview](#overview)
2. [Authentication](#authentication)
3. [API Endpoints](#api-endpoints)
4. [Models & Data Structures](#models--data-structures)
5. [Helper Functions](#helper-functions)
6. [Frontend Components](#frontend-components)
7. [Usage Examples](#usage-examples)

## Overview

This is a comprehensive Laravel-based event management system that handles event creation, registration, payments, rankings, and merchandise. The system supports multiple user roles including organizers, administrators, and participants.

### Key Features

* Event creation and management
* User registration and authentication
* Payment processing (Redsys integration)
* Event rankings and statistics
* Merchandise catalog management
* Multi-language support
* Discount and promotion management
* Communication system

## Authentication

### Sanctum Authentication

The API uses Laravel Sanctum for authentication. Most endpoints require authentication via the `auth:sanctum` middleware.

```php theme={null}
// Get authenticated user
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});
```

### Session Authentication

Web routes use session-based authentication with the `auth` middleware.

## API Endpoints

### Authentication Endpoints

#### User Login

```http theme={null}
POST /api/user/login
```

**Request Body:**

```json theme={null}
{
    "email": "user@example.com",
    "password": "password"
}
```

**Response:**

```json theme={null}
{
    "success": true,
    "user": {
        "id": 1,
        "name": "John Doe",
        "email": "user@example.com"
    }
}
```

#### User Registration

```http theme={null}
POST /api/user/register
```

**Request Body:**

```json theme={null}
{
    "name": "John Doe",
    "email": "user@example.com",
    "password": "password",
    "password_confirmation": "password"
}
```

### Event Management API

#### Get Events (Filtered)

```http theme={null}
GET /api/v1/events/filter
```

**Query Parameters:**

* `search` (string): Search term for event name
* `category` (integer): Category ID filter
* `date_from` (date): Start date filter
* `date_to` (date): End date filter
* `status` (string): Event status filter

**Response:**

```json theme={null}
{
    "data": [
        {
            "id": 1,
            "name": "Marathon 2024",
            "description": "Annual marathon event",
            "date_from": "2024-06-15T08:00:00Z",
            "date_to": "2024-06-15T18:00:00Z",
            "participants": 1000,
            "enrolled": 750,
            "category": {
                "id": 1,
                "name": "Running"
            }
        }
    ],
    "meta": {
        "current_page": 1,
        "total": 10,
        "per_page": 15
    }
}
```

#### Create Event

```http theme={null}
POST /api/eventos
```

**Request Body:**

```json theme={null}
{
    "name": "New Event",
    "description": "Event description",
    "address": "123 Main St",
    "pagina_web": "https://example.com",
    "date_from": "2024-07-01",
    "time_from": "09:00",
    "date_to": "2024-07-01",
    "time_to": "17:00",
    "date_from_register": "2024-06-01",
    "time_from_register": "00:00",
    "date_to_register": "2024-06-30",
    "time_to_register": "23:59",
    "participants": 500,
    "create_latitude": 40.4168,
    "create_longitude": -3.7038,
    "timezone": "Europe/Madrid"
}
```

#### Update Event

```http theme={null}
POST /api/eventos/{eventoId}
```

**Request Body:** Same as create event

#### Get Event Forms

```http theme={null}
GET /api/eventos/forms/{eventoId}
```

**Response:**

```json theme={null}
{
    "forms": {
        "fields": [
            {
                "type": "text",
                "label": "Full Name",
                "required": true,
                "name": "full_name"
            },
            {
                "type": "email",
                "label": "Email",
                "required": true,
                "name": "email"
            }
        ]
    }
}
```

#### Update Event Forms

```http theme={null}
POST /api/eventos/forms/{eventoId}
```

**Request Body:**

```json theme={null}
{
    "forms": {
        "fields": [
            {
                "type": "text",
                "label": "Full Name",
                "required": true,
                "name": "full_name"
            }
        ]
    }
}
```

### Checkout & Payment API

#### Get Event Products

```http theme={null}
GET /api/event-products/{event_id}
```

**Response:**

```json theme={null}
{
    "products": [
        {
            "id": 1,
            "name": "Event T-Shirt",
            "price": 25.00,
            "stock": 100,
            "variants": [
                {
                    "id": 1,
                    "attributes": {
                        "size": "M",
                        "color": "Blue"
                    },
                    "price": 25.00,
                    "stock": 50
                }
            ]
        }
    ]
}
```

#### Add Product to Cart

```http theme={null}
POST /api/add-product-to-cart
```

**Request Body:**

```json theme={null}
{
    "event_id": 1,
    "product_id": 1,
    "variant_id": 1,
    "quantity": 2
}
```

#### Remove from Cart

```http theme={null}
POST /api/remove-from-cart
```

**Request Body:**

```json theme={null}
{
    "event_id": 1,
    "product_id": 1,
    "variant_id": 1
}
```

#### Get Product Variants

```http theme={null}
GET /api/product-variants/{productId}
```

**Response:**

```json theme={null}
{
    "variants": [
        {
            "id": 1,
            "attributes": {
                "size": "S",
                "color": "Red"
            },
            "price": 25.00,
            "stock": 25
        }
    ]
}
```

#### Find Product Variant

```http theme={null}
POST /api/find-product-variant
```

**Request Body:**

```json theme={null}
{
    "product_id": 1,
    "attributes": {
        "size": "M",
        "color": "Blue"
    }
}
```

### Rankings API

#### Get Event Rankings

```http theme={null}
GET /events/{eventId}/rankings
```

#### Create Ranking

```http theme={null}
POST /events/{eventId}/rankings
```

**Request Body:**

```json theme={null}
{
    "name": "Overall Ranking",
    "description": "Overall event ranking",
    "criteria": [
        {
            "field": "finish_time",
            "weight": 1.0,
            "order": "asc"
        }
    ]
}
```

#### Recalculate Rankings

```http theme={null}
POST /events/{eventId}/rankings/{rankingId}/recalculate
```

#### Export Rankings

```http theme={null}
GET /events/{eventId}/rankings/export
```

### Discounts API

#### Get Discounts

```http theme={null}
GET /api/descuentos
```

#### Create Discount

```http theme={null}
POST /api/descuentos
```

**Request Body:**

```json theme={null}
{
    "name": "Early Bird Discount",
    "code": "EARLYBIRD",
    "amount": 20,
    "type_amount": 1,
    "quantity": 100,
    "evento_id": 1
}
```

#### Update Discount

```http theme={null}
POST /api/descuentos/{discountId}
```

#### Delete Discount

```http theme={null}
GET /api/descuentos/delete/{discountId}
```

### Communications API

#### Get Communications

```http theme={null}
GET /api/eventos/communications
```

#### Send Communication

```http theme={null}
POST /api/eventos/communications/send-email
```

**Request Body:**

```json theme={null}
{
    "event_id": 1,
    "subject": "Event Update",
    "message": "Important information about the event",
    "recipients": ["all", "confirmed", "pending"]
}
```

#### Generate Report

```http theme={null}
GET /api/eventos/generate-report/{eventId}/{type}
```

**Types:** `participants`, `payments`, `rankings`

### Merchandise API

#### Get Catalogs

```http theme={null}
GET /api/catalogos/{id}
```

#### Create Catalog

```http theme={null}
POST /api/merchant/store
```

**Request Body:**

```json theme={null}
{
    "name": "Event Merchandise",
    "description": "Official event merchandise",
    "event_id": 1
}
```

#### Update Catalog

```http theme={null}
PUT /api/catalogos/{id}
```

#### Delete Catalog

```http theme={null}
DELETE /api/catalogos/{id}
```

#### Upload Product Image

```http theme={null}
POST /api/merchant/catalogos/productos/uploadImage
```

**Request:** Multipart form data with image file

#### Get Products

```http theme={null}
GET /api/merchant/productos
```

#### Get Single Product

```http theme={null}
GET /api/merchant/productos/{id}
```

#### Process Checkout

```http theme={null}
POST /api/merchant/checkout
```

**Request Body:**

```json theme={null}
{
    "event_id": 1,
    "items": [
        {
            "product_id": 1,
            "variant_id": 1,
            "quantity": 2
        }
    ],
    "shipping_address": {
        "name": "John Doe",
        "address": "123 Main St",
        "city": "Madrid",
        "postal_code": "28001"
    }
}
```

### Configuration API

#### Create Permission

```http theme={null}
POST /api/createPermission
```

**Request Body:**

```json theme={null}
{
    "name": "manage_events",
    "guard_name": "web"
}
```

#### Delete Permission

```http theme={null}
DELETE /api/permissions/{idPermission}
```

### User Management API

#### Get User Profile

```http theme={null}
GET /user/profile
```

#### Update Profile

```http theme={null}
POST /user/update-profile
```

**Request Body:**

```json theme={null}
{
    "name": "John Doe",
    "email": "john@example.com",
    "phone": "+1234567890"
}
```

#### Update Password

```http theme={null}
POST /user/update-password
```

**Request Body:**

```json theme={null}
{
    "current_password": "oldpassword",
    "password": "newpassword",
    "password_confirmation": "newpassword"
}
```

### Organization Management API

#### Get Organizations

```http theme={null}
GET /api/organizaciones
```

#### Create Organization

```http theme={null}
POST /api/organizaciones
```

**Request Body:**

```json theme={null}
{
    "name": "Sports Club",
    "email": "contact@sportsclub.com",
    "phone": "+1234567890",
    "address": "123 Sports Ave"
}
```

#### Update Organization

```http theme={null}
POST /api/organizaciones/{organizacionId}
```

#### Delete Organization

```http theme={null}
GET /api/organizaciones/delete/{organizacionId}
```

#### Export Organizations

```http theme={null}
GET /api/organizaciones/export-to-xls
```

### Language Management API

#### Get Languages

```http theme={null}
GET /api/idiomas
```

#### Create Language

```http theme={null}
POST /administrar-idiomas
```

**Request Body:**

```json theme={null}
{
    "name": "English",
    "code": "en",
    "url_image": "/flags/en.png"
}
```

#### Update Language

```http theme={null}
POST /editar-idiomas
```

#### Delete Language

```http theme={null}
GET /api/idiomas-delete/{idiomaId}
```

### Tariff Management API

#### Get Tariffs

```http theme={null}
GET /api/tarifas
```

#### Create Tariff

```http theme={null}
POST /api/tarifas
```

**Request Body:**

```json theme={null}
{
    "name": "Standard Registration",
    "description": "Standard event registration",
    "prices": [
        {
            "pricing": 50.00,
            "currency": "EUR"
        }
    ]
}
```

#### Update Tariff

```http theme={null}
POST /api/tarifas/{tarifaId}
```

#### Delete Tariff

```http theme={null}
GET /api/tarifas/delete/{tarifaId}
```

## Models & Data Structures

### Event Model

```php theme={null}
class Evento extends Model
{
    protected $fillable = [
        'name',
        'description',
        'ciudad',
        'pais',
        'pagina_web',
        'date_from',
        'date_to',
        'participants',
        'enrolled',
        'category',
        'date_from_register',
        'date_to_register',
        'facebook',
        'instagram',
        'phone_number',
        'x',
        'organizador_id',
        'created_by',
        'email',
        'latitude',
        'longitude',
        'address',
        'json_forms',
        'flag_active',
        'general_aspect',
        'url_image',
        'timezone'
    ];

    protected $casts = [
        'tarifas' => 'array',
        'general_aspect' => 'array',
        'date_from' => 'datetime',
        'date_to' => 'datetime',
        'date_from_register' => 'datetime',
        'date_to_register' => 'datetime',
        'json_maps' => 'array',
        'json_forms' => 'array',
    ];
}
```

### User Model

```php theme={null}
class User extends Authenticatable
{
    protected $fillable = [
        'name',
        'email',
        'password',
        'organizador_id',
        'phone',
        'address'
    ];

    protected $hidden = [
        'password',
        'remember_token',
    ];
}
```

### Event Registration Model

```php theme={null}
class EventoXUsuario extends Model
{
    protected $fillable = [
        'evento_id',
        'user_id',
        'tarifa_id',
        'status',
        'payment_status',
        'total_amount',
        'discount_amount'
    ];
}
```

## Helper Functions

### Status Management Functions

#### get\_status\_meta()

Returns status metadata including label and CSS class.

```php theme={null}
function get_status_meta($status_key = '')
{
    $metas = [
        'active' => [
            'label' => 'Active',
            'class' => 'success',
        ],
        'inactive' => [
            'label' => 'Inactive',
            'class' => 'warning',
        ],
        'blocked' => [
            'label' => 'Blocked',
            'class' => 'danger',
        ],
    ];

    if (empty($status_key)) {
        return $metas;
    }

    return $metas[$status_key] ?? [];
}
```

**Usage:**

```php theme={null}
$status = get_status_meta('active');
// Returns: ['label' => 'Active', 'class' => 'success']
```

#### get\_status\_class()

Returns CSS class for a status.

```php theme={null}
function get_status_class($status_key = '')
{
    $status_meta = get_status_meta($status_key);
    return $status_meta['class'] ?? '';
}
```

**Usage:**

```php theme={null}
$class = get_status_class('active');
// Returns: 'success'
```

#### get\_status\_label()

Returns human-readable label for a status.

```php theme={null}
function get_status_label($status_key = '')
{
    $status_meta = get_status_meta($status_key);
    return $status_meta['label'] ?? '';
}
```

**Usage:**

```php theme={null}
$label = get_status_label('active');
// Returns: 'Active'
```

## Frontend Components

### JavaScript Dependencies

The application uses several JavaScript libraries:

* **jQuery**: DOM manipulation and AJAX requests
* **Bootstrap**: UI framework
* **DataTables**: Table functionality
* **Swiper**: Carousel/slider functionality
* **Toastr**: Notification system
* **Moment.js**: Date/time manipulation
* **PDFMake**: PDF generation
* **JSZip**: File compression
* **Tabulator**: Advanced table functionality

### Key Frontend Features

#### DataTables Integration

```javascript theme={null}
// Initialize DataTable
$('#events-table').DataTable({
    processing: true,
    serverSide: true,
    ajax: '/api/eventos',
    columns: [
        { data: 'name' },
        { data: 'date_from_format' },
        { data: 'participants' },
        { data: 'actions' }
    ]
});
```

#### AJAX Form Submissions

```javascript theme={null}
// Submit form via AJAX
$.ajax({
    url: '/api/eventos',
    method: 'POST',
    data: formData,
    success: function(response) {
        toastr.success('Event created successfully');
        location.reload();
    },
    error: function(xhr) {
        toastr.error('Error creating event');
    }
});
```

#### File Uploads

```javascript theme={null}
// Upload product image
var formData = new FormData();
formData.append('image', fileInput.files[0]);
formData.append('product_id', productId);

$.ajax({
    url: '/api/merchant/catalogos/productos/uploadImage',
    method: 'POST',
    data: formData,
    processData: false,
    contentType: false,
    success: function(response) {
        toastr.success('Image uploaded successfully');
    }
});
```

## Usage Examples

### Creating an Event

```php theme={null}
// Using the API
$response = Http::post('/api/eventos', [
    'name' => 'Marathon 2024',
    'description' => 'Annual marathon event',
    'address' => 'Central Park, New York',
    'pagina_web' => 'https://marathon2024.com',
    'date_from' => '2024-06-15',
    'time_from' => '08:00',
    'date_to' => '2024-06-15',
    'time_to' => '18:00',
    'date_from_register' => '2024-05-01',
    'time_from_register' => '00:00',
    'date_to_register' => '2024-06-14',
    'time_to_register' => '23:59',
    'participants' => 1000,
    'create_latitude' => 40.7829,
    'create_longitude' => -73.9654,
    'timezone' => 'America/New_York'
]);
```

### Processing a Payment

```php theme={null}
// Using the checkout API
$response = Http::post('/api/merchant/checkout', [
    'event_id' => 1,
    'items' => [
        [
            'product_id' => 1,
            'variant_id' => 1,
            'quantity' => 2
        ]
    ],
    'shipping_address' => [
        'name' => 'John Doe',
        'address' => '123 Main St',
        'city' => 'New York',
        'postal_code' => '10001'
    ]
]);
```

### Managing Rankings

```php theme={null}
// Create a ranking
$response = Http::post('/events/1/rankings', [
    'name' => 'Overall Ranking',
    'description' => 'Overall event ranking based on finish time',
    'criteria' => [
        [
            'field' => 'finish_time',
            'weight' => 1.0,
            'order' => 'asc'
        ]
    ]
]);

// Recalculate rankings
$response = Http::post('/events/1/rankings/1/recalculate');
```

### Sending Communications

```php theme={null}
// Send email to all participants
$response = Http::post('/api/eventos/communications/send-email', [
    'event_id' => 1,
    'subject' => 'Event Update - Important Information',
    'message' => 'Dear participants, please note the following updates...',
    'recipients' => ['all']
]);
```

### Managing Merchandise

```php theme={null}
// Create a product catalog
$response = Http::post('/api/merchant/store', [
    'name' => 'Event Merchandise 2024',
    'description' => 'Official merchandise for the event',
    'event_id' => 1
]);

// Add products to catalog
$response = Http::post('/api/merchant/productos/store', [
    'catalog_id' => 1,
    'name' => 'Event T-Shirt',
    'description' => 'Comfortable cotton t-shirt',
    'price' => 25.00,
    'stock' => 100,
    'variants' => [
        [
            'attributes' => ['size' => 'M', 'color' => 'Blue'],
            'price' => 25.00,
            'stock' => 50
        ]
    ]
]);
```

## Error Handling

### Common HTTP Status Codes

* **200**: Success
* **201**: Created
* **400**: Bad Request
* **401**: Unauthorized
* **403**: Forbidden
* **404**: Not Found
* **422**: Validation Error
* **500**: Internal Server Error

### Error Response Format

```json theme={null}
{
    "message": "The given data was invalid.",
    "errors": {
        "email": [
            "The email field is required."
        ],
        "password": [
            "The password field is required."
        ]
    }
}
```

## Rate Limiting

The API implements rate limiting to prevent abuse. Limits are applied per user/IP address:

* **Authentication endpoints**: 5 requests per minute
* **General API endpoints**: 60 requests per minute
* **File upload endpoints**: 10 requests per minute

## Security Considerations

1. **Authentication**: All sensitive endpoints require authentication
2. **Authorization**: Role-based access control using Spatie Laravel Permission
3. **CSRF Protection**: Web forms include CSRF tokens
4. **Input Validation**: All inputs are validated using Laravel's validation system
5. **SQL Injection Protection**: Uses Eloquent ORM with parameterized queries
6. **XSS Protection**: Output is properly escaped in Blade templates

## Testing

### API Testing Examples

```php theme={null}
// Test event creation
public function test_can_create_event()
{
    $user = User::factory()->create();
    
    $response = $this->actingAs($user)
        ->postJson('/api/eventos', [
            'name' => 'Test Event',
            'description' => 'Test Description',
            'date_from' => '2024-06-15',
            'participants' => 100
        ]);
    
    $response->assertStatus(201);
    $this->assertDatabaseHas('eventos', ['name' => 'Test Event']);
}
```

This documentation covers the main APIs, functions, and components of the event management system. For specific implementation details, refer to the individual controller and model files.
