# Mobile App Backend Implementation - UdanKhatola

## Overview
This document outlines the backend implementation for the mobile app upgradation as per Google Playstore requirements with location validation and simplified booking flow.

## Database Changes

### 1. Migrations Created

#### `2026_04_12_000001_add_geofencing_to_locations.php`
Adds geofencing capabilities to locations table:
- `latitude` (decimal): Location latitude
- `longitude` (decimal): Location longitude  
- `geofence_radius` (integer): Allowed radius in meters (default: 1000m)
- `region` (string): Region grouping (e.g., "Haridwar")

#### `2026_04_12_000002_add_agent_info_to_ticket_bookings.php`
Adds agent information to ticket bookings:
- `agent_name`: Name of booking agent
- `agent_mobile`: Mobile number of agent
- `agent_id`: Unique agent identifier
- `booking_latitude`: Agent's location at booking time
- `booking_longitude`: Agent's location at booking time
- `location_validated_at`: Timestamp of location validation

#### `2026_04_12_000003_modify_customer_list_table.php`
Makes fields nullable (removed from app):
- `email` - Now optional
- `state_id` - Now optional
- `district_id` - Now optional

#### `2026_04_12_000004_add_persistent_login_to_partners.php`
Enables persistent login:
- `device_id`: For device-specific login
- `fcm_token`: For push notifications
- `last_login_at`: Last login timestamp

### 2. Run Migrations
```bash
php artisan migrate
```

## New Services

### LocationValidationService
**Location:** `app/Services/LocationValidationService.php`

**Methods:**
- `calculateDistance($lat1, $lon1, $lat2, $lon2)` - Haversine formula for distance calculation
- `validateAgentLocation($partnerId, $currentLat, $currentLon)` - Validates agent within geofence
- `getLocationCoordinates($loccode)` - Get location details with geofence info
- `getPartnerRegionLocations($partnerId)` - Get all locations in partner's region

**Features:**
- Dynamic geofence radius per location
- Region-based validation (e.g., Haridwar region includes MNS + CHD)
- Returns detailed violation information

### NotificationService
**Location:** `app/Services/NotificationService.php`

**Methods:**
- `sendTicketWhatsApp($mobile, $customerName, $ticketDetails, $bookingId)` - Send ticket via WhatsApp
- `sendTicketSMS($mobile, $customerName, $ticketDetails, $bookingId)` - Send ticket via SMS
- `sendTicketPDFWhatsApp($mobile, $pdfUrl, $bookingId)` - Send PDF via WhatsApp

## New API Endpoints (V2)

### Authentication APIs

#### 1. Request OTP
```
POST /api/v2/request-otp
```
**Body:**
```json
{
  "mobile_number": "9876543210"
}
```
**Response:**
```json
{
  "success": true,
  "data": {
    "otp_sent": true,
    "mobile": "9876543210",
    "valid_for": "24 hours",
    "message": "OTP sent successfully via WhatsApp and SMS"
  },
  "message": "OTP sent successfully"
}
```

#### 2. Login (Persistent - No repeated OTP)
```
POST /api/v2/login
```
**Body:**
```json
{
  "mobile_number": "9876543210",
  "otp": "123456",
  "device_id": "unique-device-id",
  "fcm_token": "firebase-token"
}
```
**Response:**
```json
{
  "success": true,
  "data": {
    "token": "bearer-token-here",
    "partner": {
      "id": 1,
      "name": "Agent Name",
      "mobile": "9876543210",
      "loccode": "CHD",
      "ticket_quota": 100
    },
    "persistent_login": true,
    "message": "You will remain logged in until you logout"
  },
  "message": "Login successful"
}
```

#### 3. Verify Token
```
GET /api/v2/verify-token
Headers: Authorization: Bearer {token}
```

#### 4. Logout
```
POST /api/v2/logout
Headers: Authorization: Bearer {token}
```

### Location Validation APIs

#### 1. Validate Location
```
POST /api/v2/validate-location
Headers: Authorization: Bearer {token}
```
**Body:**
```json
{
  "latitude": 30.3165,
  "longitude": 78.0322
}
```
**Success Response:**
```json
{
  "success": true,
  "data": {
    "is_valid": true,
    "message": "Location validated successfully",
    "latitude": 30.3165,
    "longitude": 78.0322
  }
}
```
**Failure Response:**
```json
{
  "success": false,
  "message": "You are outside the allowed booking area",
  "data": {
    "is_valid": false,
    "violations": [
      {
        "location": "Chandi Devi",
        "loccode": "CHD",
        "distance": 1500.25,
        "allowed_radius": 1000,
        "exceeded_by": 500.25
      }
    ],
    "region": "Haridwar"
  }
}
```

#### 2. Get Partner Region Locations
```
GET /api/v2/partner-region-locations
Headers: Authorization: Bearer {token}
```
**Response:**
```json
{
  "success": true,
  "data": [
    {
      "loccode": "CHD",
      "name": "Chandi Devi",
      "latitude": 30.3165,
      "longitude": 78.0322,
      "geofence_radius": 1000,
      "region": "Haridwar"
    },
    {
      "loccode": "MNS",
      "name": "Mansa Devi",
      "latitude": 30.3265,
      "longitude": 78.0422,
      "geofence_radius": 1000,
      "region": "Haridwar"
    }
  ]
}
```

### Booking APIs (Simplified Flow)

#### 1. Book Ticket (No Customer OTP Required)
```
POST /api/v2/book-ticket
Headers: Authorization: Bearer {token}
```
**Body:**
```json
{
  "customer_name": "John Doe",
  "customer_mobile": "9876543210",
  "loccode": "CHD",
  "visit_date": "2026-04-15",
  "slot": 10,
  "tickets": [
    {
      "code": "ADULT001",
      "quantity": 2,
      "amount": 500
    },
    {
      "code": "CHILD001",
      "quantity": 1,
      "amount": 250
    }
  ],
  "total_amount": 750,
  "latitude": 30.3165,
  "longitude": 78.0322
}
```
**Response:**
```json
{
  "success": true,
  "data": {
    "booking_id": "UDK17131234565678",
    "customer_name": "John Doe",
    "customer_mobile": "9876543210",
    "total_tickets": 3,
    "total_amount": 750,
    "location_validated": true,
    "validation_timestamp": "2026-04-12 23:45:00",
    "ticket_booking_ids": [123, 124]
  },
  "message": "Booking created successfully. Proceed to payment."
}
```

#### 2. Confirm Payment (With Location Re-validation)
```
POST /api/v2/confirm-payment
Headers: Authorization: Bearer {token}
```
**Body:**
```json
{
  "booking_id": "UDK17131234565678",
  "payment_reference": "UPI123456789",
  "payment_status": "success",
  "latitude": 30.3165,
  "longitude": 78.0322
}
```
**Response:**
```json
{
  "success": true,
  "data": {
    "booking_id": "UDK17131234565678",
    "status": "confirmed",
    "tickets_sent": true,
    "message": "Booking confirmed! Tickets sent via WhatsApp and SMS."
  },
  "message": "Payment confirmed successfully"
}
```

#### 3. Download Ticket
```
GET /api/v2/download-ticket/{booking_id}
Headers: Authorization: Bearer {token}
```
**Response:** PDF file download

#### 4. Share Ticket
```
POST /api/v2/share-ticket
Headers: Authorization: Bearer {token}
```
**Body:**
```json
{
  "booking_id": "UDK17131234565678",
  "mobile": "9876543210"
}
```

#### 5. Booking History
```
GET /api/v2/booking-history
Headers: Authorization: Bearer {token}
```
**Response:**
```json
{
  "success": true,
  "data": {
    "current_page": 1,
    "data": [
      {
        "booking_id": "UDK17131234565678",
        "customer": {
          "name": "John Doe",
          "mobile": "9876543210"
        },
        "loccode": "CHD",
        "visit_date": "2026-04-15",
        "slot": 10,
        "total_amount": 750,
        "total_tickets": 3,
        "status": 1,
        "agent_name": "Agent Name",
        "agent_mobile": "9876543210",
        "agent_id": "AGENT1",
        "created_at": "2026-04-12 23:45:00"
      }
    ],
    "per_page": 20,
    "total": 50
  }
}
```

## Admin Panel Changes

### Location Geofencing Management

**Route:** `/locations/geofencing`

**Features:**
1. View all locations with current geofence settings
2. Update latitude, longitude, and radius for each location
3. Set region grouping (e.g., "Haridwar", "Uttarakhand")
4. Bulk update regions for multiple locations
5. Dynamic radius configuration (0m to 50km)

**Controller:** `LocationManagementController`

**Routes:**
```php
Route::get('/locations/geofencing', 'LocationManagementController@index');
Route::patch('/locations/{id}/geofencing', 'LocationManagementController@updateGeofencing');
Route::post('/locations/bulk-region-update', 'LocationManagementController@bulkUpdateRegion');
```

## Key Features Implemented

### 1. Persistent Login ✅
- OTP required only on first login or after logout
- Token-based authentication with device tracking
- Automatic token validation on app startup

### 2. Location Validation & Geo-fencing ✅
- Real-time location validation before booking
- Dynamic geofence radius per location (configurable by admin)
- Region-based validation (agent validated against all units in region)
- Location re-validation before payment (timeout protection)
- Haversine formula for accurate distance calculation

### 3. Simplified Booking Flow ✅
- Removed customer OTP verification step
- Simplified customer data: Only name and mobile required
- Removed fields: state, district, email, first_visit flag
- Location validation mandatory before booking

### 4. Agent Information Tracking ✅
- Agent name, mobile, and ID stored with each booking
- Agent's location (lat/long) captured at booking time
- Location validation timestamp recorded

### 5. Ticket Delivery ✅
- Automatic WhatsApp notification with ticket details
- Automatic SMS notification
- Download ticket as PDF
- Share ticket via WhatsApp to any number

### 6. Payment Flow ✅
- Location validated before payment initiation
- Location re-validated at payment confirmation
- Timeout protection (prevents location spoofing)
- Payment reference tracking

## Configuration

### Environment Variables Required

```env
# Existing
API_URL=https://your-api-url/
WHATSAPP_KEY=your-whatsapp-api-key

# New (if needed)
GEOFENCE_DEFAULT_RADIUS=1000
LOCATION_VALIDATION_TIMEOUT=300
```

## Testing Checklist

### Location Validation
- [ ] Agent within allowed radius can book
- [ ] Agent outside radius gets error with distance details
- [ ] Region-based validation works (multiple locations)
- [ ] Admin can update geofence radius dynamically
- [ ] Distance calculation is accurate

### Booking Flow
- [ ] Booking created without customer OTP
- [ ] Only name and mobile required for customer
- [ ] Location validated before booking creation
- [ ] Location re-validated before payment
- [ ] Agent info saved correctly

### Notifications
- [ ] WhatsApp message sent on successful booking
- [ ] SMS sent on successful booking
- [ ] Ticket PDF can be downloaded
- [ ] Ticket can be shared via WhatsApp

### Persistent Login
- [ ] OTP required on first login
- [ ] Token persists across app restarts
- [ ] No OTP required after first login
- [ ] Logout clears device info

## Migration Steps

1. **Run migrations:**
   ```bash
   php artisan migrate
   ```

2. **Update location coordinates:**
   - Go to `/locations/geofencing`
   - Add latitude, longitude for each location
   - Set geofence radius (in meters)
   - Group locations by region

3. **Test location validation:**
   - Use `/api/v2/validate-location` endpoint
   - Verify distance calculations
   - Test with different radii

4. **Update mobile app:**
   - Integrate new v2 API endpoints
   - Implement location permission request
   - Add persistent login flow
   - Remove customer OTP screens

## Backward Compatibility

All V1 API endpoints remain functional at their original paths:
- `/api/location-list`
- `/api/price-card-by-location`
- `/api/app-ticket-booking`
- etc.

New V2 endpoints are prefixed with `/api/v2/`

## Support

For issues or questions, contact the development team.

---

**Version:** 2.0  
**Last Updated:** April 12, 2026  
**Status:** Ready for Testing
