# Card Management System Documentation

## Overview
The Card Management System provides comprehensive functionality for managing debit and credit cards, including card creation, transaction tracking, security settings, and ATM location services.

## Database Schema

### Cards Table
- **id**: Primary key
- **user_id**: Foreign key to users table
- **bank_account_id**: Foreign key to bank_accounts table
- **card_number**: Encrypted full card number (TEXT)
- **masked_number**: Masked display number (e.g., "**** **** **** 1234")
- **card_type**: debit, credit, prepaid
- **card_network**: visa, mastercard, amex, discover
- **card_name**: Custom name for the card
- **holder_name**: Name on the card
- **expiry_month/year**: Card expiration
- **cvv**: Encrypted CVV (TEXT)
- **pin_hash**: Hashed PIN
- **status**: active, inactive, locked, expired, lost, stolen
- **activation_code**: 6-digit activation code
- **activated_at**: Activation timestamp
- **last_used_at**: Last transaction timestamp
- **daily_atm_limit**: Daily ATM withdrawal limit
- **daily_purchase_limit**: Daily purchase limit
- **monthly_limit**: Monthly spending limit
- **international_transactions**: Boolean flag
- **contactless_enabled**: Boolean flag
- **online_transactions**: Boolean flag
- **atm_withdrawals**: Boolean flag
- **pos_transactions**: Boolean flag
- **transaction_alerts**: Boolean flag
- **design_theme**: Card design theme
- **plastic_type**: standard, eco, metal

### Card Transactions Table
- **id**: Primary key
- **card_id**: Foreign key to cards table
- **user_id**: Foreign key to users table
- **bank_account_id**: Foreign key to bank_accounts table
- **transaction_id**: Unique transaction identifier
- **type**: purchase, withdrawal, refund, fee, reversal, cashback
- **method**: chip, swipe, contactless, online, atm, manual
- **amount**: Transaction amount
- **fee**: Transaction fee
- **currency**: Currency code (default: USD)
- **status**: pending, completed, failed, cancelled, disputed
- **merchant_name**: Merchant name
- **merchant_category**: Merchant category
- **merchant_id**: Merchant identifier
- **merchant_address**: Merchant address
- **transaction_location**: Transaction location
- **latitude/longitude**: GPS coordinates
- **country_code**: Country code
- **security_data**: JSON security information
- **fraud_score**: Fraud detection score
- **is_international**: Boolean flag
- **is_suspicious**: Boolean flag
- **decline_reason**: Reason for declined transaction
- **authorization_code**: Authorization code
- **reference_number**: Reference number
- **processor_response**: Processor response
- **authorized_at**: Authorization timestamp
- **settled_at**: Settlement timestamp
- **raw_data**: JSON raw transaction data
- **metadata**: JSON additional metadata
- **description**: Transaction description

## API Endpoints

### Card Management

#### GET /api/cards
Get all user cards with account information, limits, and settings.

**Response:**
```json
{
  "status": "success",
  "data": {
    "cards": [
      {
        "id": 1,
        "card_name": "Primary Debit Card",
        "card_type": "debit",
        "card_network": "visa",
        "masked_number": "**** **** **** 1234",
        "holder_name": "John Doe",
        "expiry_date": "12/2028",
        "status": "active",
        "is_active": true,
        "is_expired": false,
        "is_locked": false,
        "bank_account": {
          "id": 1,
          "account_name": "Premium Checking",
          "available_balance": "1500.00"
        },
        "limits": {
          "daily_atm_limit": "500.00",
          "daily_purchase_limit": "2000.00"
        },
        "settings": {
          "international_transactions": false,
          "contactless_enabled": true,
          "transaction_alerts": true
        }
      }
    ]
  }
}
```

#### GET /api/cards/{id}
Get specific card details.

#### POST /api/cards
Request a new card.

**Request:**
```json
{
  "bank_account_id": 1,
  "card_type": "debit",
  "card_network": "visa",
  "card_name": "My New Card",
  "design_theme": "modern",
  "plastic_type": "eco"
}
```

#### PUT /api/cards/{id}/settings
Update card settings.

**Request:**
```json
{
  "transaction_alerts": true,
  "international_transactions": false,
  "contactless_enabled": true,
  "online_transactions": true,
  "atm_withdrawals": true,
  "pos_transactions": true
}
```

#### PUT /api/cards/{id}/limits
Update spending limits.

**Request:**
```json
{
  "daily_atm_limit": 600.00,
  "daily_purchase_limit": 2500.00,
  "monthly_limit": 10000.00
}
```

#### POST /api/cards/{id}/toggle-lock
Lock or unlock a card.

**Request:**
```json
{
  "action": "lock",
  "reason": "Lost card"
}
```

#### PUT /api/cards/{id}/pin
Change card PIN.

**Request:**
```json
{
  "current_pin": "1234",
  "new_pin": "5678",
  "confirm_pin": "5678"
}
```

#### POST /api/cards/{id}/report-lost-stolen
Report card as lost or stolen.

**Request:**
```json
{
  "type": "lost",
  "description": "Lost at shopping mall",
  "last_known_location": "Downtown Mall"
}
```

### Transaction Management

#### GET /api/cards/{id}/transactions
Get card transaction history.

**Query Parameters:**
- `limit`: Number of transactions (default: 50)
- `offset`: Pagination offset
- `status`: Filter by status
- `type`: Filter by transaction type
- `from_date`: Start date filter
- `to_date`: End date filter

#### GET /api/cards/transactions/summary
Get transaction summary and analytics.

### ATM Services

#### GET /api/cards/atm-locations
Get nearby ATM locations.

**Query Parameters:**
- `latitude`: User latitude
- `longitude`: User longitude
- `radius`: Search radius in miles (default: 10)
- `limit`: Number of results (default: 20)

**Response:**
```json
{
  "status": "success",
  "data": {
    "atm_locations": [
      {
        "id": 1,
        "name": "First Heritage ATM",
        "address": "123 Main Street, Downtown",
        "distance": 0.2,
        "latitude": 40.7128,
        "longitude": -74.0060,
        "services": ["Cash Withdrawal", "Deposits", "Balance Inquiry"],
        "fees": "Free",
        "available": true,
        "hours": "24/7",
        "accessibility": true
      }
    ]
  }
}
```

## Model Features

### Card Model
- **Encryption**: Card numbers and CVVs are automatically encrypted
- **Masking**: Automatic generation of masked card numbers
- **PIN Management**: Secure PIN hashing and verification
- **Validation**: Card number validation using Luhn algorithm
- **Status Management**: Comprehensive status tracking
- **Limit Enforcement**: Spending limit validation
- **Security**: Fraud detection and security features

### Key Methods:
- `generateCardNumber($network)`: Generate valid card numbers
- `generateCvv()`: Generate CVV codes
- `verifyPin($pin)`: Verify PIN
- `isExpired()`: Check if card is expired
- `isActive()`: Check if card is active
- `canTransact($amount, $type)`: Check transaction limits

### CardTransaction Model
- **Comprehensive Tracking**: All transaction details
- **Geolocation**: GPS coordinates for transactions
- **Fraud Detection**: Fraud scoring and suspicious activity flagging
- **Merchant Information**: Detailed merchant data
- **Status Tracking**: Transaction lifecycle management

## Security Features

1. **Encryption**: All sensitive data (card numbers, CVVs) encrypted at rest
2. **PIN Security**: PINs are hashed using bcrypt
3. **Fraud Detection**: Real-time fraud scoring
4. **Transaction Monitoring**: Suspicious activity detection
5. **Geolocation Tracking**: Location-based security
6. **Limit Enforcement**: Spending and withdrawal limits
7. **Status Controls**: Card locking and unlocking
8. **Alert System**: Real-time transaction alerts

## Frontend Integration

The React frontend provides:
- **Card Display**: Visual card representations with proper branding
- **Real-time Updates**: Live card status and transaction updates
- **Interactive Controls**: Card locking, PIN changes, limit updates
- **Transaction History**: Comprehensive transaction viewing
- **ATM Locator**: Interactive map with nearby ATMs
- **Settings Management**: User-friendly settings interface
- **Security Features**: Fraud alerts and security notifications

## Usage Examples

### Creating a New Card
```php
$card = Card::create([
    'user_id' => $user->id,
    'bank_account_id' => $account->id,
    'card_type' => 'debit',
    'card_network' => 'visa',
    'card_name' => 'Primary Debit Card',
    'holder_name' => $user->name,
    'daily_atm_limit' => 500.00,
    'daily_purchase_limit' => 2000.00
]);
```

### Recording a Transaction
```php
CardTransaction::create([
    'card_id' => $card->id,
    'user_id' => $user->id,
    'bank_account_id' => $card->bank_account_id,
    'type' => 'purchase',
    'method' => 'contactless',
    'amount' => 45.67,
    'merchant_name' => 'Coffee Shop',
    'status' => 'completed'
]);
```

### Checking Transaction Limits
```php
if ($card->canTransact(100.00, 'atm')) {
    // Process ATM withdrawal
} else {
    // Decline - limit exceeded
}
```

## Error Handling

The system includes comprehensive error handling for:
- Invalid card numbers
- Expired cards
- Insufficient limits
- Fraud detection
- Network errors
- Database constraints
- Validation failures

## Testing

The system includes comprehensive test coverage:
- Unit tests for models
- Integration tests for API endpoints
- Security tests for encryption
- Performance tests for high-volume transactions
- Frontend component tests

## Deployment Notes

1. Ensure proper encryption keys are configured
2. Set up fraud detection thresholds
3. Configure ATM location data
4. Set up transaction monitoring
5. Configure alert systems
6. Test all security features
7. Verify API rate limiting
8. Set up logging and monitoring

## Future Enhancements

- Mobile wallet integration
- Biometric authentication
- Advanced fraud detection
- Real-time notifications
- Cashback and rewards system
- International transaction support
- Cryptocurrency integration
- AI-powered spending insights 