# Phase 2: Admin Panel Implementation

## Overview

This document outlines the comprehensive Laravel admin panel implementation for the Sabok Load Management System (Phase 2). The admin panel includes full CRUD operations, dashboard analytics, reporting, driver location tracking, and app version management.

## Table of Contents

1. [Database Changes](#database-changes)
2. [Models](#models)
3. [Admin Controllers](#admin-controllers)
4. [API Endpoints](#api-endpoints)
5. [Routes](#routes)
6. [Middleware](#middleware)
7. [Features](#features)
8. [Usage Examples](#usage-examples)
9. [Running Migrations](#running-migrations)

---

## Database Changes

### New Tables

#### 1. `app_versions` Table
Manages different versions of the mobile applications (driver and requester apps).

**Columns:**
- `id` - Primary key
- `app_type` - ENUM('driver', 'requester')
- `version` - Version number (e.g., "1.0.0")
- `build_number` - Integer build number
- `min_version` - Minimum required version
- `force_update` - Boolean for mandatory updates
- `release_notes` - Text field for version notes
- `download_url` - URL to download the APK/IPA
- `is_active` - Boolean to mark active version
- `timestamps` - created_at, updated_at
- `deleted_at` - Soft delete timestamp

**Migration File:**
```
database/migrations/2026_01_01_000001_create_app_versions_table.php
```

#### 2. `driver_locations` Table
Tracks real-time and historical location data for drivers.

**Columns:**
- `id` - Primary key
- `driver_id` - Foreign key to users table
- `latitude` - Decimal(10,8)
- `longitude` - Decimal(11,8)
- `accuracy` - Location accuracy in meters
- `speed` - Speed in km/h
- `heading` - Direction in degrees (0-360)
- `is_online` - Boolean online status
- `last_ping_at` - Last location update timestamp
- `timestamps` - created_at, updated_at

**Migration File:**
```
database/migrations/2026_01_01_000002_create_driver_locations_table.php
```

---

## Models

### 1. AppVersion Model
**File:** `app/Models/AppVersion.php`

**Key Features:**
- Soft deletes enabled
- Scopes for active versions and app type filtering
- Static method to get latest version
- Method to check if update is required

**Methods:**
- `scopeActive($query)` - Filter active versions
- `scopeOfType($query, $type)` - Filter by app type
- `getLatestVersion($appType)` - Get latest active version
- `requiresUpdate($currentVersion, $currentBuild)` - Check update requirement

### 2. DriverLocation Model
**File:** `app/Models/DriverLocation.php`

**Key Features:**
- Tracks driver locations in real-time
- Calculates distances using Haversine formula
- Finds nearby drivers within radius
- Determines online/offline status

**Methods:**
- `scopeOnline($query)` - Get online drivers (last ping within 5 minutes)
- `scopeOffline($query)` - Get offline drivers
- `updateDriverLocation($driverId, $data)` - Update/create location
- `calculateDistance($lat1, $lon1, $lat2, $lon2)` - Calculate distance in km
- `findNearbyDrivers($latitude, $longitude, $radiusKm)` - Find nearby drivers

### 3. User Model (Updated)
**File:** `app/Models/User.php`

**New Relations:**
- `location()` - hasOne relation to DriverLocation
- `locationHistory()` - hasMany relation to DriverLocation

---

## Admin Controllers

All admin controllers are located in `app/Http/Controllers/Admin/`

### 1. DashboardController
**Purpose:** Display admin dashboard with comprehensive statistics

**Methods:**
- `index()` - Get dashboard data

**Returns:**
- User statistics (total, drivers, requesters, active)
- Load statistics (by status)
- Bill statistics
- Revenue (this month, monthly chart)
- Active drivers count
- Recent loads and users
- Loads trend (last 7 days)

**Example Response:**
```json
{
  "success": true,
  "data": {
    "users": {
      "total": 150,
      "drivers": 80,
      "requesters": 65,
      "active": 140
    },
    "loads": {
      "total": 320,
      "by_status": {
        "pending": 15,
        "approved": 25,
        "in_transit": 30,
        "delivered": 240,
        "cancelled": 10
      }
    },
    "revenue": {
      "this_month": 125000000,
      "monthly_chart": [...]
    }
  }
}
```

### 2. UserManagementController
**Purpose:** Full CRUD operations for users

**Methods:**
- `index()` - List users with search/filter/pagination
- `create()` - Get data for create form
- `store()` - Create new user
- `show($id)` - Show user details
- `edit($id)` - Get data for edit form
- `update($id)` - Update user
- `destroy($id)` - Soft delete user
- `toggleStatus($id)` - Activate/deactivate user

**Filters:**
- Search (name, email, phone, national_code)
- Role filter
- Active status filter
- Sort and pagination

### 3. LoadManagementController
**Purpose:** Manage loads with advanced filtering

**Methods:**
- `index()` - List loads with filters
- `show($id)` - Show load details
- `update($id)` - Update load
- `destroy($id)` - Delete load (restrictions apply)
- `approve($id)` - Approve pending load
- `assignDriver($id)` - Assign/change driver

**Filters:**
- Search (title, description, addresses)
- Status filter
- Requester/Driver filter
- Date range (created, pickup)
- Sort and pagination

### 4. BillManagementController
**Purpose:** Manage bills/waybills

**Methods:**
- `index()` - List bills with filters
- `show($id)` - Show bill details
- `create()` - Get data for create form (loads without bills)
- `store()` - Create new bill (auto-generates bill number)
- `edit($id)` - Get data for edit form
- `update($id)` - Update bill
- `destroy($id)` - Delete bill (restrictions apply)

**Features:**
- Auto-generate unique bill numbers (BL-YYYYMMDD-XXXXXX)
- Prevent duplicate bills for same load
- Prevent deleting confirmed bills

### 5. DriverManagementController
**Purpose:** Manage drivers and track performance

**Methods:**
- `index()` - List drivers with stats
- `show($id)` - Show driver details with performance
- `activeDrivers()` - List currently online drivers
- `locationHistory($id)` - Get driver location history

**Statistics:**
- Total/completed/active/cancelled loads
- Completion rate
- Total/monthly revenue
- Distance traveled
- Location tracking

### 6. ReportController
**Purpose:** Generate various reports and analytics

**Methods:**
- `index()` - Report dashboard with quick stats
- `financial()` - Detailed financial report
- `loads()` - Loads report with statistics
- `drivers()` - Driver performance report
- `exportExcel()` - Export reports to Excel

**Financial Report Includes:**
- Total/pending revenue
- Loads by status
- Daily revenue chart
- Top requesters
- Top drivers
- Delivery rate

### 7. AppVersionController
**Purpose:** Manage app versions for OTA updates

**Methods:**
- `index()` - List app versions
- `create()` - Get data for create form
- `store()` - Create new version
- `show($id)` - Show version details
- `edit($id)` - Get data for edit form
- `update($id)` - Update version
- `destroy($id)` - Delete version
- `setActive($id)` - Set version as active

**Features:**
- Prevent duplicate versions
- Auto-deactivate other versions when setting active
- Prevent deleting active versions
- Validate version format (X.Y.Z)

---

## API Endpoints

### Location Tracking API
**File:** `app/Http/Controllers/Api/LocationController.php`

#### Driver Endpoints (Require Driver Role)

**POST /api/location/update**
Update driver's current location
```json
{
  "latitude": 35.7219,
  "longitude": 51.3347,
  "accuracy": 10.5,
  "speed": 45.2,
  "heading": 180.0
}
```

**POST /api/location/offline**
Set driver as offline

#### Public Endpoints (All Authenticated Users)

**GET /api/location/drivers**
Get all online driver locations
- Optional query params: `latitude`, `longitude`, `radius`

**GET /api/location/drivers/{driverId}**
Get specific driver's current location

**GET /api/location/drivers/{driverId}/history**
Get driver's location history
- Query params: `start_date`, `end_date`, `limit`, `sort_order`

**POST /api/location/nearby**
Find nearby drivers
```json
{
  "latitude": 35.7219,
  "longitude": 51.3347,
  "radius": 10
}
```

---

## Routes

### Admin Routes (web.php)
**Prefix:** `/admin`
**Middleware:** `auth:sanctum`, `admin`

```
GET  /admin/dashboard
CRUD /admin/users
POST /admin/users/{id}/toggle-status
CRUD /admin/loads
POST /admin/loads/{id}/approve
POST /admin/loads/{id}/assign-driver
CRUD /admin/bills
GET  /admin/drivers
GET  /admin/drivers/{id}
GET  /admin/drivers/active
GET  /admin/drivers/{id}/location-history
GET  /admin/reports
GET  /admin/reports/financial
GET  /admin/reports/loads
GET  /admin/reports/drivers
GET  /admin/reports/export-excel
CRUD /admin/app-versions
POST /admin/app-versions/{id}/set-active
```

### API Routes (api.php)
Location tracking routes added under `/api/location` prefix.

---

## Middleware

### AdminMiddleware
**File:** `app/Http/Middleware/AdminMiddleware.php`

**Purpose:** Restrict access to admin-only routes

**Checks:**
1. User is authenticated
2. User role is 'admin'

**Registered in:** `app/Http/Kernel.php` as `'admin'`

---

## Features

### Dashboard Analytics
- Real-time statistics
- Revenue tracking
- User/driver/load counts
- Status breakdown
- Monthly trends
- Recent activity

### User Management
- Full CRUD operations
- Search and filters
- Role-based access
- Account activation/deactivation
- Prevent self-deletion

### Load Management
- Advanced filtering
- Status workflow
- Driver assignment
- Approval system
- Date range filtering

### Bill Management
- Auto bill number generation
- Load association
- Confirmation tracking
- Signature support

### Driver Tracking
- Real-time location
- Location history
- Distance calculation
- Online/offline status
- Performance metrics

### Reporting
- Financial reports
- Load statistics
- Driver performance
- Excel export (ready for implementation)
- Custom date ranges

### App Version Control
- OTA update management
- Force update capability
- Multi-app support (driver/requester)
- Release notes
- Download URL management

---

## Usage Examples

### 1. Get Dashboard Statistics
```bash
curl -X GET http://localhost:8000/admin/dashboard \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Accept: application/json"
```

### 2. List Users with Filters
```bash
curl -X GET "http://localhost:8000/admin/users?role=driver&is_active=1&search=ali" \
  -H "Authorization: Bearer YOUR_TOKEN"
```

### 3. Assign Driver to Load
```bash
curl -X POST http://localhost:8000/admin/loads/5/assign-driver \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"driver_id": 10}'
```

### 4. Update Driver Location (Mobile App)
```bash
curl -X POST http://localhost:8000/api/location/update \
  -H "Authorization: Bearer DRIVER_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "latitude": 35.7219,
    "longitude": 51.3347,
    "accuracy": 10.5,
    "speed": 45.2,
    "heading": 180.0
  }'
```

### 5. Find Nearby Drivers
```bash
curl -X POST http://localhost:8000/api/location/nearby \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "latitude": 35.7219,
    "longitude": 51.3347,
    "radius": 10
  }'
```

### 6. Get Financial Report
```bash
curl -X GET "http://localhost:8000/admin/reports/financial?start_date=2026-01-01&end_date=2026-01-31" \
  -H "Authorization: Bearer ADMIN_TOKEN"
```

### 7. Create New App Version
```bash
curl -X POST http://localhost:8000/admin/app-versions \
  -H "Authorization: Bearer ADMIN_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "app_type": "driver",
    "version": "1.2.0",
    "build_number": 12,
    "min_version": "1.0.0",
    "force_update": false,
    "release_notes": "Bug fixes and performance improvements",
    "download_url": "https://example.com/app-v1.2.0.apk",
    "is_active": true
  }'
```

---

## Running Migrations

After implementing Phase 2, run the following commands:

```bash
# Navigate to Laravel directory
cd temp-laravel

# Run new migrations
php artisan migrate

# Optional: Seed database with sample data
php artisan db:seed

# Clear cache
php artisan config:clear
php artisan route:clear
php artisan cache:clear
```

---

## Testing

### Create Admin User
```bash
php artisan tinker
```

```php
$admin = new App\Models\User();
$admin->name = 'Admin User';
$admin->email = 'admin@sabok.com';
$admin->phone = '09123456789';
$admin->national_code = '1234567890';
$admin->role = 'admin';
$admin->password = Hash::make('admin123');
$admin->is_active = true;
$admin->save();
```

### Test Admin Access
1. Login as admin to get token
2. Use token to access admin routes
3. Verify middleware restrictions

---

## Security Considerations

1. **Authentication:** All admin routes require valid Sanctum token
2. **Authorization:** AdminMiddleware ensures only admin role can access
3. **Input Validation:** All inputs validated using Laravel validators
4. **Rate Limiting:** API rate limiting configured
5. **SQL Injection Protection:** Eloquent ORM used throughout
6. **Soft Deletes:** Allows data recovery
7. **Password Hashing:** Bcrypt used for passwords

---

## Next Steps (Phase 3)

1. Develop Driver Mobile App (Kotlin)
2. Implement real-time notifications
3. Add push notifications for driver assignment
4. Integrate maps for route tracking
5. Add chat/messaging between drivers and requesters
6. Implement payment gateway
7. Add document upload for bills
8. Create Excel export classes for reports

---

## File Structure

```
temp-laravel/
├── app/
│   ├── Http/
│   │   ├── Controllers/
│   │   │   ├── Admin/
│   │   │   │   ├── DashboardController.php
│   │   │   │   ├── UserManagementController.php
│   │   │   │   ├── LoadManagementController.php
│   │   │   │   ├── BillManagementController.php
│   │   │   │   ├── DriverManagementController.php
│   │   │   │   ├── ReportController.php
│   │   │   │   └── AppVersionController.php
│   │   │   └── Api/
│   │   │       └── LocationController.php
│   │   └── Middleware/
│   │       └── AdminMiddleware.php
│   └── Models/
│       ├── AppVersion.php
│       ├── DriverLocation.php
│       └── User.php (updated)
├── database/
│   └── migrations/
│       ├── 2026_01_01_000001_create_app_versions_table.php
│       └── 2026_01_01_000002_create_driver_locations_table.php
└── routes/
    ├── api.php (updated)
    └── web.php (updated)
```

---

## Support

For issues or questions:
1. Check Laravel logs: `storage/logs/laravel.log`
2. Review this documentation
3. Contact development team

---

**Version:** 2.0.0
**Date:** 2026-01-01
**Status:** Phase 2 - Complete
