> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/Braian551/viax/llms.txt
> Use this file to discover all available pages before exploring further.

# Create Trip

> Request a new ride

## Endpoint

```
POST /viajes/create_trip.php
```

Create a new trip request. This initiates the ride-hailing process and matches the passenger with available drivers.

## Headers

<ParamField header="Content-Type" type="string" required>
  Must be `application/json`
</ParamField>

## Request Body

<ParamField body="usuario_id" type="integer" required>
  Passenger user ID making the request
</ParamField>

<ParamField body="tipo_servicio" type="string" required>
  Service type requested

  **Possible values:**

  * `motocicleta` - Motorcycle taxi
  * `auto` - Car service
  * `mototaxi` - Motorcycle taxi with passenger cabin
</ParamField>

<ParamField body="origen" type="object" required>
  Trip origin location

  <Expandable title="origen fields">
    <ParamField body="direccion" type="string" required>
      Origin address
    </ParamField>

    <ParamField body="latitud" type="number" required>
      Origin latitude
    </ParamField>

    <ParamField body="longitud" type="number" required>
      Origin longitude
    </ParamField>

    <ParamField body="referencia" type="string">
      Reference point or additional instructions
    </ParamField>
  </Expandable>
</ParamField>

<ParamField body="destino" type="object" required>
  Trip destination location (same structure as origen)

  <Expandable title="destino fields">
    <ParamField body="direccion" type="string" required>
      Destination address
    </ParamField>

    <ParamField body="latitud" type="number" required>
      Destination latitude
    </ParamField>

    <ParamField body="longitud" type="number" required>
      Destination longitude
    </ParamField>

    <ParamField body="referencia" type="string">
      Reference point or additional instructions
    </ParamField>
  </Expandable>
</ParamField>

## Response

<ResponseField name="success" type="boolean" required>
  Trip creation success status
</ResponseField>

<ResponseField name="message" type="string">
  Success or error message
</ResponseField>

<ResponseField name="trip" type="object">
  Created trip object

  <Expandable title="trip structure">
    <ResponseField name="id" type="integer">
      Unique trip identifier
    </ResponseField>

    <ResponseField name="usuario_id" type="integer">
      Passenger user ID
    </ResponseField>

    <ResponseField name="conductor_id" type="integer" nullable>
      Assigned driver ID (null if not yet assigned)
    </ResponseField>

    <ResponseField name="tipo_servicio" type="string">
      Service type
    </ResponseField>

    <ResponseField name="estado" type="string">
      Trip status: `pendiente`, `aceptado`, `en_ruta`, `en_curso`, `completado`, `cancelado`
    </ResponseField>

    <ResponseField name="origen" type="object">
      Origin location details
    </ResponseField>

    <ResponseField name="destino" type="object">
      Destination location details
    </ResponseField>

    <ResponseField name="precio_estimado" type="number">
      Estimated trip price in COP
    </ResponseField>

    <ResponseField name="distancia_km" type="number">
      Estimated distance in kilometers
    </ResponseField>

    <ResponseField name="duracion_estimada_minutos" type="integer">
      Estimated duration in minutes
    </ResponseField>

    <ResponseField name="fecha_solicitud" type="string">
      Trip request timestamp (ISO 8601)
    </ResponseField>
  </Expandable>
</ResponseField>

## Request Example

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST https://76.13.114.194/viajes/create_trip.php \
    -H "Content-Type: application/json" \
    -d '{
      "usuario_id": 456,
      "tipo_servicio": "motocicleta",
      "origen": {
        "direccion": "Carrera 15 #85-30, Bogotá",
        "latitud": 4.6814,
        "longitud": -74.0479,
        "referencia": "Frente al Centro Comercial"
      },
      "destino": {
        "direccion": "Calle 72 #10-20, Bogotá",
        "latitud": 4.6533,
        "longitud": -74.0602,
        "referencia": "Edificio de oficinas"
      }
    }'
  ```

  ```dart Dart theme={null}
  import 'package:http/http.dart' as http;
  import 'dart:convert';

  Future<Map<String, dynamic>> createTrip({
    required int usuarioId,
    required String tipoServicio,
    required Map<String, dynamic> origen,
    required Map<String, dynamic> destino,
  }) async {
    final response = await http.post(
      Uri.parse('https://76.13.114.194/viajes/create_trip.php'),
      headers: {'Content-Type': 'application/json'},
      body: jsonEncode({
        'usuario_id': usuarioId,
        'tipo_servicio': tipoServicio,
        'origen': origen,
        'destino': destino,
      }),
    );

    if (response.statusCode == 200) {
      final data = jsonDecode(response.body);
      if (data['success'] == true) {
        return data['trip'];
      } else {
        throw Exception(data['message']);
      }
    }
    throw Exception('Failed to create trip');
  }

  // Usage:
  final trip = await createTrip(
    usuarioId: 456,
    tipoServicio: 'motocicleta',
    origen: {
      'direccion': 'Carrera 15 #85-30, Bogotá',
      'latitud': 4.6814,
      'longitud': -74.0479,
      'referencia': 'Frente al Centro Comercial',
    },
    destino: {
      'direccion': 'Calle 72 #10-20, Bogotá',
      'latitud': 4.6533,
      'longitud': -74.0602,
      'referencia': 'Edificio de oficinas',
    },
  );
  ```

  ```javascript JavaScript theme={null}
  async function createTrip(tripData) {
    const response = await fetch('https://76.13.114.194/viajes/create_trip.php', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(tripData),
    });
    
    const data = await response.json();
    if (data.success) {
      return data.trip;
    }
    throw new Error(data.message);
  }

  // Usage:
  const trip = await createTrip({
    usuario_id: 456,
    tipo_servicio: 'motocicleta',
    origen: {
      direccion: 'Carrera 15 #85-30, Bogotá',
      latitud: 4.6814,
      longitud: -74.0479,
      referencia: 'Frente al Centro Comercial',
    },
    destino: {
      direccion: 'Calle 72 #10-20, Bogotá',
      latitud: 4.6533,
      longitud: -74.0602,
      referencia: 'Edificio de oficinas',
    },
  });
  ```
</CodeGroup>

## Response Example

<CodeGroup>
  ```json Success (200) theme={null}
  {
    "success": true,
    "message": "Viaje creado exitosamente",
    "trip": {
      "id": 789,
      "usuario_id": 456,
      "conductor_id": null,
      "tipo_servicio": "motocicleta",
      "estado": "pendiente",
      "origen": {
        "direccion": "Carrera 15 #85-30, Bogotá",
        "latitud": 4.6814,
        "longitud": -74.0479,
        "referencia": "Frente al Centro Comercial"
      },
      "destino": {
        "direccion": "Calle 72 #10-20, Bogotá",
        "latitud": 4.6533,
        "longitud": -74.0602,
        "referencia": "Edificio de oficinas"
      },
      "precio_estimado": 18500,
      "precio_final": null,
      "distancia_km": 4.2,
      "duracion_estimada_minutos": 15,
      "fecha_solicitud": "2024-03-15T14:30:00.000Z",
      "fecha_aceptacion": null,
      "fecha_inicio": null,
      "fecha_fin": null
    }
  }
  ```

  ```json No Drivers Available (200) theme={null}
  {
    "success": false,
    "message": "No hay conductores disponibles en esta área"
  }
  ```

  ```json Invalid Location (400) theme={null}
  {
    "success": false,
    "message": "Coordenadas de origen inválidas"
  }
  ```
</CodeGroup>

## Trip Status Flow

After creation, a trip goes through the following states:

<Steps>
  <Step title="pendiente">
    Trip created, waiting for driver acceptance
  </Step>

  <Step title="aceptado">
    Driver accepted the trip
  </Step>

  <Step title="en_ruta">
    Driver is on the way to pick up passenger
  </Step>

  <Step title="en_curso">
    Passenger picked up, trip in progress
  </Step>

  <Step title="completado">
    Trip successfully completed
  </Step>
</Steps>

Alternatively, the trip can be cancelled at any point before completion.

## Service Types

<CardGroup cols={3}>
  <Card title="Motocicleta" icon="motorcycle">
    Standard motorcycle taxi for quick trips
  </Card>

  <Card title="Auto" icon="car">
    Car service for comfort and multiple passengers
  </Card>

  <Card title="Mototaxi" icon="van-shuttle">
    Motorcycle taxi with passenger cabin
  </Card>
</CardGroup>

## Pricing

The estimated price is calculated based on:

* **Base fare**: Starting price
* **Distance**: Price per kilometer
* **Duration**: Price per minute (peak hours)
* **Service type**: Different rates for moto/auto
* **Demand**: Dynamic pricing during high demand

## Error Responses

<ResponseField name="400" type="Bad Request">
  Invalid request data or coordinates
</ResponseField>

<ResponseField name="404" type="Not Found">
  User not found
</ResponseField>

<ResponseField name="500" type="Internal Server Error">
  Server error during trip creation
</ResponseField>

## Notes

<Note>
  After creating a trip, use the [Trip Status](/api/trips/status) endpoint to monitor the trip state and driver assignment.
</Note>

<Warning>
  Ensure the origin and destination coordinates are accurate. Invalid coordinates will result in failed trip requests.
</Warning>

## See Also

* [Trip Status](/api/trips/status) - Get trip status and updates
* [Cancel Trip](/api/trips/status#cancel-trip) - Cancel a trip
* [Trip History](/api/trips/history) - View past trips
* [Trip Pricing](/api/trips/pricing) - Calculate trip estimates
