# 🌿 Branch Management System Integration Guide

## 📊 System Overview

The application now supports a **multi-branch structure** where:
- Each branch is independent with its own vehicles, employees, rentals, and finances
- Users are assigned to specific branches (except admins who see all)
- All data is automatically filtered by the user's branch
- Complete financial tracking per branch

---

## 🗄️ Database Structure

### New Tables Created:
1. **`branches`** - Main branch information
2. **Foreign Keys Added To:**
   - `users` → `branch_id`
   - `cars` → `branch_id`
   - `rentals` → `branch_id`
   - `expenses` → `branch_id`
   - `maintenance_records` → `branch_id`

---

## 🔐 Access Control

### Middleware: `EnsureBranchAccess`
- Admins can access all branches
- Non-admin users can only access their assigned branch
- Automatic 403 error if accessing unauthorized branch

### Usage in Routes:
```php
Route::get('/branches/{branch}/cars', [CarController::class, 'index'])
    ->middleware('EnsureBranchAccess');
```

---

## 🔄 Global Query Scoping

### `BranchScoped` Trait
Added to models: `Car`, `Rental`, `Expense`, `MaintenanceRecord`

**Automatic Filtering:**
- All queries automatically filter by `auth()->user()->branch_id`
- Admins see all records via `withoutGlobalScope('branch')`

**Available Methods:**
```php
Car::forBranch($branchId)        // Filter specific branch
Car::allBranches()               // Bypass scope (admin only)
Car::all()                       // Auto-filtered by user's branch
```

---

## 🚀 Feature Integration

### 1. **Car Management**
- ✅ Cars are assigned to branches
- ✅ Branch managers see only their cars
- ✅ Car creation automatically uses user's branch

### 2. **Rental System**
- ✅ Rentals linked to branch at creation
- ✅ `RentalService::createRental()` uses `auth()->user()->branch_id`
- ✅ Revenue tracked per branch

### 3. **Expenses & Maintenance**
- ✅ All expenses assigned to branch
- ✅ Maintenance records per branch
- ✅ Cost analysis per branch

### 4. **Customer Risk Assessment**
- ✅ Violations tracked globally (shared customers)
- ✅ Payment delays per rental/branch
- ✅ Customer risk calculation remains global

### 5. **Vehicle Documents & Insurance**
- ✅ Documents linked via car → branch
- ✅ Insurance per vehicle (inherited from car's branch)

### 6. **Maintenance Schedule**
- ✅ Service records per branch
- ✅ Oil change alerts per vehicle

---

## 🏢 Branch Management

### Controller: `BranchController`
**Available Methods:**
```php
index()          // List all branches with stats
create()         // Show creation form
store()          // Create new branch
show()           // Branch details & stats
edit()           // Edit branch
update()         // Save changes
destroy()        // Delete (if no cars/employees)
stats()          // JSON API for branch stats
```

### Branch Statistics Available:
```php
$branch->total_cars              // Count
$branch->available_cars          // Count
$branch->rented_cars             // Count
$branch->maintenance_cars        // Count
$branch->total_employees         // Count
$branch->today_revenue           // Decimal
$branch->month_revenue           // Decimal
```

---

## 📋 Branch Model Relationships

```php
$branch->manager()               // Branch manager (User)
$branch->employees()             // All branch employees
$branch->cars()                  // All vehicles
$branch->rentals()               // All contracts
$branch->expenses()              // All costs
$branch->maintenanceRecords()    // All maintenance
```

---

## 🔧 Implementation Checklist

- [x] **Database Migrations** - All branch_id columns added
- [x] **Models** - Relationships & BranchScoped trait
- [x] **Middleware** - EnsureBranchAccess for routing
- [x] **Controllers** - BranchController created
- [x] **Services** - RentalService updated
- [ ] **Views** - Create branch management views
- [ ] **Routes** - Add branch routes to web.php
- [ ] **Dashboard** - Add branch selector & stats
- [ ] **Tests** - Add branch-specific tests

---

## 📝 Routes Structure (To Be Added)

```php
// Branch Management
Route::resource('branches', BranchController::class)->middleware(['auth', 'admin']);
Route::get('/branches/{branch}/stats', [BranchController::class, 'stats']);

// Branch-Scoped Resources
Route::group(['prefix' => 'branches/{branch}', 'middleware' => ['auth', 'EnsureBranchAccess']], function() {
    Route::resource('cars', CarController::class);
    Route::resource('rentals', RentalController::class);
    Route::resource('expenses', ExpenseController::class);
    Route::resource('maintenance', MaintenanceController::class);
});

// User Branch Assignment
Route::patch('/users/{user}/assign-branch', [UserController::class, 'assignBranch']);
```

---

## 💡 Usage Examples

### Creating a Rental (Auto-Assigns Branch)
```php
$rental = RentalService::createRental([
    'car_id' => 1,
    'customer_id' => 5,
    // ... other data
]);
// $rental->branch_id = auth()->user()->branch_id (automatic)
```

### Filtering by Branch
```php
// Automatically filtered by user's branch
$cars = Car::all();              // Only user's branch cars

// Admin override
$allCars = Car::allBranches()->get();

// Specific branch
$branchCars = Car::forBranch(2)->get();
```

### Branch Statistics
```php
$branch = Branch::find(1);
echo $branch->available_cars;    // 5
echo $branch->today_revenue;     // 15000.00
```

---

## 🔒 Security Notes

1. **Global Scope** - BranchScoped trait prevents accidental data leaks
2. **Middleware Check** - Route-level verification
3. **Admin Bypass** - `isAdmin()` check allows full access
4. **Audit Trail** - All `created_by` still links to user for accountability

---

## 📊 Next Steps

1. Create branch management views
2. Add branch selector to navigation
3. Update dashboard for branch-specific KPIs
4. Create branch performance reports
5. Add branch-level user role assignment
6. Implement branch transfer workflows (if needed)

---

## 🚀 Production Ready Features

✅ Multi-branch support  
✅ Automatic data isolation  
✅ Role-based access control  
✅ Financial tracking per branch  
✅ Scalable database indexes  
✅ Admin oversight capabilities  
