# Driver Sales System - Setup Guide

## Overview
This system allows drivers (users with user-level access) to upload physical invoice images with customer phone numbers. Each driver can only see their own data, while managers and directors can view all drivers' data.

## Features Implemented

### 1. Database Migration
- **File**: `database/migrations/2024_01_20_000000_create_driver_sales_table.php`
- **Table**: `driver_sales`
- **Columns**:
  - `id` - Primary key
  - `invoice` - Auto-generated alphanumeric (unique)
  - `customer_phone` - Customer's 10-digit phone number
  - `image_path` - Path to uploaded invoice image
  - `driver_id` - Foreign key to users table
  - `tenant_id` - Foreign key to tenants table
  - `branch_id` - Foreign key to tenant_branches table
  - `timestamps` - Created at and updated at

### 2. Model
- **File**: `app/Models/DriverSales.php`
- **Relationships**:
  - `driver()` - Belongs to User
  - `tenant()` - Belongs to Tenant
  - `branch()` - Belongs to TenantBranch
- **Methods**:
  - `generateInvoice()` - Generates unique alphanumeric invoice (DRV-XXXXXXXXXX)

### 3. Controller
- **File**: `app/Http/Controllers/Tenant/DriverSalesController.php`
- **Methods**:
  - `index()` - Display upload page
  - `store()` - Store driver sales invoice
  - `fetchDriverSales()` - Fetch driver's own sales data
  - `reportIndex()` - Display report page
  - `fetchReport()` - Fetch report with role-based access
  - `downloadInvoice()` - Download invoice image
  - `getDrivers()` - Get all drivers (managers/directors only)

### 4. Routes
- **File**: `routes/tenant.php`
- **Routes Added**:
  - `GET /driver_sales` - Upload page
  - `POST /driver_sales/store` - Store invoice
  - `GET /driver_sales/fetch` - Fetch driver's sales
  - `GET /driver_sales/report` - Report page
  - `POST /driver_sales/report/fetch` - Fetch report data
  - `GET /driver_sales/download/{id}` - Download invoice
  - `GET /driver_sales/drivers` - Get drivers list

### 5. Views
- **File**: `resources/views/tenant/truck_details/driver_sales.blade.php`
  - Customer phone number input (10 digits)
  - Take photo button (live camera capture)
  - Upload image button (for saved images)
  - Image preview
  - DataTable showing driver's own sales records
  - Link to report page

- **File**: `resources/views/tenant/truck_details/driver_report.blade.php`
  - Date range filter
  - Driver filter (managers/directors only)
  - DataTable with all records
  - Role-based data display
  - Download button for each invoice

### 6. Sidebar Update
- **File**: `resources/views/tenant/layouts/sidebar.blade.php`
- Added link to Driver Sales under Truck Sales section
- Controlled by `driver_invoice` privilege

## Setup Instructions

### Step 1: Run Migration
```bash
php artisan migrate
```

### Step 2: Create Upload Directory
The system will automatically create the `public/Driver Sales` directory when the first upload is made. However, you can create it manually:

**Windows:**
```bash
mkdir "public\Driver Sales"
```

**Linux/Mac:**
```bash
mkdir -p "public/Driver Sales"
chmod 755 "public/Driver Sales"
```

### Step 3: Set Permissions (Linux/Mac only)
```bash
chmod 755 public/Driver\ Sales
chown -R www-data:www-data public/Driver\ Sales
```

### Step 4: Update User Privileges
Ensure the `driver_invoice` privilege is set to `1` in the `user_privileges` table for users who should have access:

```sql
UPDATE user_privileges 
SET driver_invoice = 1 
WHERE user_id IN (SELECT id FROM users WHERE role = 'user');
```

## Usage Guide

### For Drivers (User Level)

1. **Access the System**
   - Navigate to: Truck Sales → Driver Sales

2. **Upload Invoice**
   - Enter customer's 10-digit phone number
   - Choose one of two options:
     - Click "Take Photo" to capture live image using camera
     - Click "Choose File" to upload saved image
   - Preview the image
   - Click "Upload Invoice"

3. **View Your Records**
   - All your uploaded invoices appear in the table below
   - Click "Download" to view/download any invoice
   - Click "View Report" for detailed reporting

4. **View Report**
   - Filter by date range
   - View all your sales records
   - Download any invoice

### For Managers/Directors

1. **Access Reports**
   - Navigate to: Truck Sales → Driver Sales → View Report

2. **Filter Data**
   - Select date range
   - Select specific driver or view all
   - Click "Filter"

3. **View All Driver Data**
   - See all drivers' sales records
   - Download any invoice
   - Export data if needed

## Validation Rules

### Customer Phone
- Required
- Must be exactly 10 digits
- Only numeric characters allowed

### Invoice Image
- Required
- Accepted formats: JPEG, JPG, PNG
- Maximum size: 10MB
- Can be captured via camera or uploaded

## Security Features

1. **Role-Based Access Control**
   - Drivers can only see their own data
   - Managers/Directors can see all data
   - Enforced at controller level

2. **File Access Control**
   - Download links check user permissions
   - Drivers can only download their own invoices
   - Managers/Directors can download any invoice

3. **Data Isolation**
   - All queries filtered by tenant_id and branch_id
   - Prevents cross-tenant data access

4. **Input Validation**
   - Server-side validation for all inputs
   - File type and size validation
   - Phone number format validation

## Database Schema

```sql
CREATE TABLE driver_sales (
    id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
    invoice VARCHAR(255) UNIQUE NOT NULL,
    customer_phone VARCHAR(15) NOT NULL,
    image_path VARCHAR(255) NOT NULL,
    driver_id BIGINT UNSIGNED NOT NULL,
    tenant_id BIGINT UNSIGNED NOT NULL,
    branch_id BIGINT UNSIGNED NOT NULL,
    created_at TIMESTAMP NULL,
    updated_at TIMESTAMP NULL,
    FOREIGN KEY (driver_id) REFERENCES users(id) ON DELETE CASCADE,
    FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
    FOREIGN KEY (branch_id) REFERENCES tenant_branches(id) ON DELETE CASCADE,
    INDEX idx_driver_id (driver_id),
    INDEX idx_tenant_id (tenant_id),
    INDEX idx_branch_id (branch_id),
    INDEX idx_created_at (created_at)
);
```

## API Endpoints

### Store Invoice
```
POST /{domain}/driver_sales/store
Content-Type: multipart/form-data

Parameters:
- customer_phone: string (10 digits)
- invoice_image: file (image, max 10MB)

Response:
{
    "success": true,
    "message": "Invoice uploaded successfully!",
    "invoice": "DRV-ABC1234567"
}
```

### Fetch Driver Sales
```
GET /{domain}/driver_sales/fetch

Response:
{
    "success": true,
    "data": [
        {
            "count": 1,
            "invoice": "DRV-ABC1234567",
            "customer_phone": "0241234567",
            "file": "Driver Sales/DRV-ABC1234567_1234567890.jpg",
            "date_time": "20-Jan-2024 10:30 AM",
            "id": 1
        }
    ]
}
```

### Fetch Report
```
POST /{domain}/driver_sales/report/fetch

Parameters:
- date_from: date (optional)
- date_to: date (optional)
- driver_id: integer (optional, managers/directors only)

Response:
{
    "success": true,
    "data": [...],
    "total_count": 10
}
```

## Troubleshooting

### Issue: Camera not working
**Solution**: Ensure the application is served over HTTPS or localhost. Modern browsers require secure context for camera access.

### Issue: Upload fails with "File too large"
**Solution**: Check that the image is under 10MB. Compress the image if necessary.

### Issue: Permission denied when creating directory
**Solution**: 
```bash
# Linux/Mac
sudo chmod 755 public
sudo chown -R www-data:www-data public

# Windows
# Run as Administrator
icacls "public" /grant Users:F /T
```

### Issue: Driver can see other drivers' data
**Solution**: Check that the user's role is correctly set to 'user' in the users table.

## Activity Logging

All driver sales uploads are logged in the `activity_logs` table:
- Action: "Driver Sales Invoice Uploaded"
- Description: Includes driver name, invoice number, and customer phone
- Department: "Driver Sales"

## Future Enhancements

Potential improvements for future versions:
1. Bulk upload capability
2. Invoice editing/deletion
3. Customer name field
4. Sales amount tracking
5. Commission calculation
6. SMS notifications to customers
7. Invoice status tracking (pending, verified, paid)
8. Export to Excel/PDF
9. Dashboard analytics
10. Mobile app integration

## Support

For issues or questions, contact the development team or refer to the main application documentation.

---

**Version**: 1.0.0  
**Last Updated**: January 2024  
**Author**: Development Team
