# Customer Management System Implementation

## Overview
This implementation adds a comprehensive customer management system to the Limoofood project, following the existing project patterns and best practices. The system uses Livewire for the panel interface and follows proper design patterns for the API.

## Architecture

### Panel (limoofood-panel)
- **Livewire Components**: Modern reactive UI components
- **Repository Pattern**: API communication layer with caching
- **Role-based Access**: Only restaurant users (role 3) can access

### API (limoofood-api)
- **Service Layer**: Business logic separation
- **Request Validation**: Dedicated validation classes
- **Repository Pattern**: Data access abstraction
- **Proper Error Handling**: Consistent error responses

## Database Changes

### New Table: `customer_branches`
- **Purpose**: Links customers to specific restaurants/branches
- **Fields**:
  - `id` - Primary key
  - `name` - Customer's first name
  - `family` - Customer's last name
  - `user_id` - Reference to users table
  - `branch_id` - Reference to branches table
  - `mobile` - Customer's mobile number
  - `email` - Customer's email (optional)
  - `address` - Customer's address (optional)
  - `status` - Active/Inactive status
  - `created_at`, `updated_at`, `deleted_at` - Timestamps

### Database Relationships
- **User** ↔ **CustomerBranch**: One-to-Many (a user can be a customer at multiple restaurants)
- **Branch** ↔ **CustomerBranch**: One-to-Many (a restaurant can have multiple customers)

## Panel Implementation

### Livewire Components
1. **Customer\Index** - Customer list with search and pagination
2. **Customer\Create** - Add new customer form
3. **Customer\Edit** - Edit existing customer form

### Repository Layer
- **CustomerRepository**: Handles API communication with caching
- **Error Handling**: Proper error logging and user feedback
- **Cache Management**: Intelligent cache invalidation

### Features
- **Real-time Search**: Livewire-powered search functionality
- **Form Validation**: Client and server-side validation
- **Responsive Design**: Bootstrap-based modern UI
- **Success/Error Messages**: User feedback for all operations

## API Implementation

### Service Layer
- **CustomerService**: Business logic and data operations
- **Transaction Management**: Database transaction handling
- **Error Logging**: Comprehensive error tracking

### Request Validation
- **CustomerRequest**: Dedicated validation class
- **Custom Messages**: Persian language support
- **Unique Constraints**: Mobile number uniqueness validation

### Endpoints
- `GET /api/v1/customer` - List customers for a branch
- `POST /api/v1/customer` - Create new customer
- `GET /api/v1/customer/{id}` - Get customer details
- `PUT /api/v1/customer/{id}` - Update customer
- `DELETE /api/v1/customer/{id}` - Delete customer
- `GET /api/v1/customer/search` - Search customers
- `GET /api/v1/customer/stats` - Get customer statistics

### Features
- **Validation**: Comprehensive input validation
- **Error Handling**: Proper error responses with status codes
- **Search**: Search by name, family, or mobile number
- **Pagination**: Configurable pagination
- **Soft Deletes**: Maintains data integrity
- **Statistics**: Customer count analytics

## Models

### CustomerBranch Model
- **Relationships**: User, Branch
- **Scopes**: Active, ForBranch
- **Soft Deletes**: Maintains data history

### Updated User Model
- **New Relationship**: `customerBranches()`
- **Maintains**: Existing functionality

### Updated Branch Model
- **New Relationships**: `customerBranches()`, `customers()`
- **Maintains**: Existing functionality

## Security Features

### Access Control
- **Role-based Access**: Only restaurant users can access
- **Branch Isolation**: Users can only see their own customers
- **Session Validation**: Proper authentication checks

### Data Validation
- **Input Sanitization**: Prevents malicious input
- **Unique Constraints**: Prevents duplicate customers per branch
- **Foreign Key Constraints**: Maintains referential integrity

## Installation & Setup

### 1. Run Migration
```bash
php artisan migrate
```

### 2. Update Environment Variables
Add to `.env`:
```
API_BASE_URL=http://your-api-domain.com/api/v1
```

### 3. Clear Cache
```bash
php artisan config:clear
php artisan cache:clear
```

## Usage Examples

### Creating a Customer via API
```bash
curl -X POST http://your-api-domain.com/api/v1/customer \
  -H "Content-Type: application/json" \
  -d '{
    "name": "علی",
    "family": "احمدی",
    "mobile": "09123456789",
    "email": "ali@example.com",
    "address": "تهران، خیابان ولیعصر",
    "branch_id": 1
  }'
```

### Getting Customers for a Branch
```bash
curl "http://your-api-domain.com/api/v1/customer?branch_id=1"
```

### Getting Customer Statistics
```bash
curl "http://your-api-domain.com/api/v1/customer/stats?branch_id=1"
```

## Benefits

### For Restaurants
- **Customer Management**: Organize and track customers
- **Contact Information**: Maintain customer details
- **Status Tracking**: Active/inactive customer management
- **Search Capability**: Quick customer lookup
- **Statistics**: Customer count insights

### For System
- **Data Integrity**: Proper relationships and constraints
- **Scalability**: Efficient database design
- **Security**: Role-based access control
- **Maintainability**: Clean, organized code structure
- **Performance**: Caching and optimization

### Technical Benefits
- **Modern UI**: Livewire reactive components
- **Clean Architecture**: Service layer separation
- **Validation**: Dedicated request classes
- **Error Handling**: Comprehensive error management
- **Caching**: Intelligent cache management

## Future Enhancements

### Potential Features
- **Customer Analytics**: Order history, preferences
- **Loyalty Program**: Points, rewards system
- **Communication**: SMS/Email notifications
- **Import/Export**: Bulk customer management
- **Customer Categories**: VIP, regular, etc.
- **Advanced Search**: Filter by multiple criteria

### Technical Improvements
- **Caching**: Redis for better performance
- **API Rate Limiting**: Prevent abuse
- **Audit Logs**: Track customer changes
- **Webhooks**: Real-time notifications
- **API Documentation**: Swagger/OpenAPI

## Troubleshooting

### Common Issues
1. **Migration Errors**: Check database connection and permissions
2. **API 404**: Verify route registration and API base URL
3. **Permission Denied**: Check user role and session
4. **Validation Errors**: Review input data format
5. **Livewire Issues**: Check component registration

### Debug Steps
1. Check Laravel logs (`storage/logs/laravel.log`)
2. Verify database table creation
3. Test API endpoints with Postman
4. Check panel authentication and sessions
5. Verify Livewire component registration

## Code Quality

### Standards Followed
- **PSR-12**: PHP coding standards
- **Laravel Best Practices**: Framework conventions
- **SOLID Principles**: Clean architecture
- **Error Handling**: Comprehensive exception management
- **Documentation**: Inline code documentation

### Testing Considerations
- **Unit Tests**: Service layer testing
- **Feature Tests**: API endpoint testing
- **Browser Tests**: Livewire component testing
- **Database Tests**: Migration and model testing

## Support

For technical support or questions about this implementation, please refer to the project documentation or contact the development team.
