# Own Courier Shipment Status Update - Complete Guide

## Overview
This feature allows manual status updates for own courier shipments. Status updates are recorded in the tracking table and also automatically update the booking table's last_status field.

## Features

✅ **Search Shipments** - By Booking ID, AWB/Waybill No, or Reference ID
✅ **Display Shipment Details** - Complete shipment information including:
- AWB Number
- No. of Boxes
- To Pay (COD Amount)
- Date Added
- Status
- Weight
- Client Name
- Consignor Name
- Consignee Name
- Origin (State => City -> Pincode)
- Destination (State => City -> Pincode)

✅ **Manual Status Update** with:
- Status Selection (Pending, Not Picked, Manifested, Lost, In Transit, Out For Delivery, Delivered, RTO)
- Update Date & Time
- Status Location
- Remarks/Instructions

✅ **Dual Table Updates**:
- Updates `tbl_tracking` with scan details
- Updates `tbl_bookings.last_status` automatically

✅ **Recent Updates Sidebar** - Shows last 10 tracking records
✅ **Own Courier Shipments Table** - Filter and manage all own courier shipments
✅ **Real-time Filtering** - By Status and Branch

## Files Created/Modified

### New Files

#### 1. **shipment-status-update.php** (NEW)
Main page for own courier status updates

**Features:**
- Search form (by ID, Waybill, Reference)
- Shipment details display
- Status update form
- Recent updates sidebar
- All shipments data table with filters
- Inline update buttons

**Form Fields:**
```
Search Section:
- Search Type (Booking ID / AWB / Reference ID)
- Search Input
- Search Button

Shipment Info (Read-only):
- Booking ID, Waybill No, Reference ID
- Consignee, Phone
- Current Status (Badge)
- No. of Boxes, Weight
- Origin, Destination
- Date Added, Client Name

Update Form:
- Select Update Status (required)
- Status Update Date (required)
- Status Location (optional)
- Remarks / Instructions (optional)
- Action Buttons (Update, Reset)
```

#### 2. **api/tracking/create.php** (NEW)
API endpoint to create tracking records

**POST Parameters:**
```
booking_id (required) - Booking ID
status (required) - Status value
status_date (required) - DateTime (format: 2024-01-15T14:30)
location (optional) - Status location
remarks (optional) - Remarks/instructions
```

**Response:**
```json
{
  "status": "success",
  "message": "Tracking updated successfully",
  "tracking_id": 123,
  "booking_id": 456,
  "new_status": "In Transit"
}
```

**What It Does:**
1. Validates required fields
2. Checks if booking exists
3. Checks for duplicate tracking records
4. Inserts tracking record into tbl_tracking
5. Updates tbl_bookings.last_status
6. Uses transactions for data consistency

## Database Schema

### tbl_tracking (Used for storing scans)
```sql
CREATE TABLE IF NOT EXISTS `tbl_tracking` (
  `id` int(11) AUTO_INCREMENT PRIMARY KEY,
  `booking_id` int(11) NOT NULL,
  `waybill_no` varchar(100),
  `scan_type` varchar(100),           -- Status value
  `scan_location` varchar(255),       -- Location
  `scan_datetime` datetime,           -- Date & Time
  `status_code` varchar(100),         -- Status Code
  `remarks` text,                     -- Remarks/Instructions
  `raw_response` json,
  `created_by` int(11),
  `created_at` timestamp,
  KEY `idx_booking_id` (`booking_id`),
  KEY `idx_waybill` (`waybill_no`)
);
```

### tbl_bookings (Updated with new status)
```sql
ALTER TABLE `tbl_bookings` 
ADD COLUMN `last_status` varchar(100) DEFAULT 'Pending',
ADD KEY `idx_last_status` (`last_status`);
```

## Available Status Values

### Standard Status Options:
1. **Pending** - Initial status
2. **Not Picked** - Shipment couldn't be picked
3. **Manifested** - Added to manifest
4. **In Transit** - On the way
5. **Out For Delivery** - Out for final delivery
6. **Delivered** - Successfully delivered
7. **LOST** - Shipment lost
8. **RTO** - Return To Origin

## User Interface

### Main Page Layout

**Top Section:**
- Page Title: "Shipment Status Update (Own Courier)"
- Back to Shipments button

**Left Column (Search & Update):**
1. **Search Card**
   - Search Type dropdown (Booking ID / AWB / Reference ID)
   - Search Input field
   - Search Button

2. **Shipment Details Card** (appears after search)
   - 2-column table showing all shipment details
   - Current Status as badge

3. **Update Status Card** (appears after search)
   - Status dropdown (required)
   - Status Update Date/Time (required)
   - Status Location (optional)
   - Remarks textarea (optional)
   - Update & Reset buttons

**Right Column (Sidebar):**
1. **Recent Status Updates Card**
   - Shows last 10 tracking records
   - Date, Time, Status, Location
   - Auto-refreshes after update

**Bottom Section:**
1. **Own Courier Shipments Table**
   - Filters: Status, Branch
   - Columns: ID, Waybill, Ref ID, Boxes, To Pay, Date, Status, Weight, Client, Consignor, Consignee, Origin, Destination, Action
   - Inline "Update" button per row
   - Sortable, searchable, paginated

## How to Use

### Step 1: Search for Shipment
1. Open `shipment-status-update.php`
2. Select search type (Booking ID / AWB / Reference ID)
3. Enter the value
4. Click "Search Shipment"

### Step 2: View Shipment Details
- Shipment details appear in a table
- Shows all required information
- Current status displayed as badge

### Step 3: Update Status
1. Select status from dropdown
2. Set update date & time
3. Enter location (optional)
4. Add remarks if needed
5. Click "Update Status"

### Step 4: Verify Update
- Success message appears
- Recent updates sidebar refreshes
- Shipment table updates
- Tracking history shows new entry

## Data Flow

```
User fills form
    ↓
Submit via AJAX
    ↓
api/tracking/create.php
    ↓
Validate data
    ↓
Insert into tbl_tracking
    ↓
Update tbl_bookings.last_status
    ↓
Commit transaction
    ↓
Return success response
    ↓
Refresh UI (table, sidebar, alerts)
```

## API Integration

### Create Tracking Record
**Endpoint:** `api/tracking/create.php`
**Method:** POST
**Required Fields:**
- booking_id
- status
- status_date

**Optional Fields:**
- location
- remarks

**Example Request:**
```javascript
$.post('api/tracking/create.php', {
    booking_id: 123,
    status: 'In Transit',
    status_date: '2024-01-15T14:30',
    location: 'Delhi Hub',
    remarks: 'Shipment received at hub'
}, function(response) {
    console.log(response);
});
```

### Read Tracking Records
**Endpoint:** `api/tracking/read.php`
**Method:** GET
**Parameters:**
- id: booking_id
- waybill: waybill_no
- live: 1 (to fetch from courier and update)

**Example Request:**
```javascript
$.get('api/tracking/read.php?id=123', function(response) {
    console.log(response.data.Scans); // Array of tracking records
});
```

## Features in Detail

### Search Functionality
- **By Booking ID:** Searches tbl_bookings.id
- **By Waybill No:** Searches tbl_bookings.waybill_no
- **By Reference ID:** Searches tbl_bookings.booking_ref_id

### Shipment Details Display
Shows all relevant shipment information:
- Booking ID, Waybill No, Reference ID
- Consignee name and phone
- Current status with badge
- No. of boxes and weight
- Origin location (State => City -> Pincode)
- Destination location (State => City -> Pincode)
- Date added and client name

### Status Update Form
- **Status Selection:** 8 predefined status values
- **DateTime Picker:** Full date and time control
- **Location Input:** Free text for scan location
- **Remarks Textarea:** Additional instructions/notes
- **Validation:** Client-side and server-side

### Recent Updates Sidebar
- Displays last 10 tracking records for the shipment
- Shows date, time, status, and location
- Auto-refreshes after each update
- Helps track update history

### Shipments Table
- Lists all own courier shipments
- Real-time filtering by status and branch
- All shipment details visible
- Inline "Update" button for quick access
- Responsive and sortable columns

## Validation Rules

### Client-Side:
- Status field is required
- Status Date field is required
- Date format validation
- Location: optional but recommended

### Server-Side:
- Booking ID must exist
- Status cannot be empty
- Status date must be valid MySQL datetime
- Duplicate check: Same booking + status + datetime
- Transaction rollback on any error

## Response Messages

### Success:
```json
{
  "status": "success",
  "message": "Tracking updated successfully",
  "tracking_id": 123,
  "booking_id": 456,
  "new_status": "In Transit"
}
```

### Error Examples:
```json
{
  "status": "error",
  "message": "Status is required"
}
```

```json
{
  "status": "error",
  "message": "Booking not found"
}
```

```json
{
  "status": "error",
  "message": "This tracking record already exists"
}
```

## Testing Checklist

- [ ] Search by Booking ID
- [ ] Search by Waybill No
- [ ] Search by Reference ID
- [ ] Verify shipment details load correctly
- [ ] Update status successfully
- [ ] Verify tracking record created in database
- [ ] Verify booking.last_status updated
- [ ] Verify recent updates sidebar refreshes
- [ ] Verify shipments table updates
- [ ] Test all status values
- [ ] Test with different dates and times
- [ ] Test with and without location/remarks
- [ ] Test duplicate prevention
- [ ] Test error handling
- [ ] Verify table filtering works
- [ ] Test inline update buttons
- [ ] Verify responsive design

## Navigation

Add link to sidebar/navigation:
```php
<li class="nav-item">
    <a href="shipment-status-update.php" class="nav-link">
        <i class="ti ti-package"></i> Status Update (Own Courier)
    </a>
</li>
```

## Permission Check

If using permissions, add to middleware:
```php
// require_permission('shipment', 'is_update');
// require_permission('tracking', 'is_create');
```

## Notes

⚠️ **Important:**
- Status updates are permanent and tracked in database
- Each status update creates a tracking record
- Booking.last_status is automatically updated
- Uses transactions for data consistency
- Duplicate status updates are prevented

✅ **Features:**
- Real-time UI refresh after updates
- Complete shipment details visible
- Recent history sidebar for reference
- Filter and search capabilities
- Responsive design
- Proper error handling

## Future Enhancements

1. Bulk status updates
2. CSV/Excel import for multiple shipments
3. Status update templates
4. Automated notifications to consignee
5. Status history export
6. Analytics/reports
7. Integration with SMS/Email alerts
8. Mobile app compatibility

## Support

For issues or questions:
1. Check database schema is correct
2. Verify API endpoint is accessible
3. Check browser console for errors
4. Verify user permissions
5. Check transaction logs

## File Locations

- **Frontend:** `/steve/shipment-status-update.php`
- **API:** `/steve/api/tracking/create.php`
- **Documentation:** `/steve/OWN_COURIER_STATUS_UPDATE.md`
- **Related APIs:** `/steve/api/tracking/read.php`
- **Related APIs:** `/steve/api/booking/readone.php`
