# Complete React Native App Setup Guide
## Hafeez Center Inventory Management System

This is a comprehensive guide to build a complete React Native mobile application that integrates with the Hafeez Center Inventory API. The app will support authentication and full CRUD operations for all modules: Shops, Users, Customers, Items, Brands, and Categories.

---

## 📋 Table of Contents

1. [Prerequisites](#prerequisites)
2. [Project Initialization](#project-initialization)
3. [Project Structure](#project-structure)
4. [Dependencies Installation](#dependencies-installation)
5. [Configuration Setup](#configuration-setup)
6. [Core Services](#core-services)
7. [State Management](#state-management)
8. [Navigation Setup](#navigation-setup)
9. [Authentication Flow](#authentication-flow)
10. [Module Implementation](#module-implementation)
11. [UI Components](#ui-components)
12. [Error Handling](#error-handling)
13. [Testing & Debugging](#testing--debugging)
14. [Build & Deployment](#build--deployment)

---

## 1. Prerequisites

### Required Software
- **Node.js** (v18 or higher)
- **npm** or **yarn** package manager
- **React Native CLI** (`npm install -g react-native-cli`)
- **Expo CLI** (optional, for Expo projects: `npm install -g expo-cli`)
- **Android Studio** (for Android development)
- **Xcode** (for iOS development, macOS only)
- **Git** for version control

### Development Environment
- **VS Code** or **Android Studio** / **Xcode**
- **Postman** or **Insomnia** (for API testing)
- **React Native Debugger** (optional)

### API Information
- **Base URL**: `http://127.0.0.1:8000/api/v1` (Development)
- **Production URL**: `https://api.hafeezcenter.com/api/v1` (Production)
- **Authentication**: Bearer Token (Laravel Sanctum)
- **Token Expiration**: 24 hours (configurable)

---

## 2. Project Initialization

### Option A: React Native CLI (Recommended for Full Control)

```bash
# Create new React Native project
npx react-native init HafeezCenterInventory --template react-native-template-typescript

# Navigate to project
cd HafeezCenterInventory

# Initialize Git (if not already initialized)
git init
git add .
git commit -m "Initial React Native project setup"
```

### Option B: Expo (Faster Development, Easier Setup)

```bash
# Create new Expo project
npx create-expo-app HafeezCenterInventory --template

# Navigate to project
cd HafeezCenterInventory
```

### Project Type Recommendation
**Use React Native CLI** for production apps that need:
- Full native module access
- Custom native code
- Better performance
- More control over build process

**Use Expo** if you want:
- Faster development setup
- Over-the-air updates
- Easier testing with Expo Go app
- Less native configuration

---

## 3. Project Structure

Create the following folder structure:

```
HafeezCenterInventory/
├── src/
│   ├── api/                    # API service layer
│   │   ├── client.ts          # Axios instance with interceptors
│   │   ├── auth.ts            # Authentication API calls
│   │   ├── shops.ts          # Shop CRUD operations
│   │   ├── users.ts           # User CRUD operations
│   │   ├── customers.ts       # Customer CRUD operations
│   │   ├── items.ts           # Item CRUD operations
│   │   ├── brands.ts          # Brand CRUD operations
│   │   ├── categories.ts     # Category CRUD operations
│   │   └── types.ts           # API response types
│   ├── components/            # Reusable UI components
│   │   ├── common/
│   │   │   ├── Button.tsx
│   │   │   ├── Input.tsx
│   │   │   ├── Card.tsx
│   │   │   ├── LoadingSpinner.tsx
│   │   │   ├── ErrorMessage.tsx
│   │   │   ├── EmptyState.tsx
│   │   │   └── SearchBar.tsx
│   │   ├── forms/
│   │   │   ├── FormField.tsx
│   │   │   ├── SelectDropdown.tsx
│   │   │   ├── DatePicker.tsx
│   │   │   └── FormContainer.tsx
│   │   └── lists/
│   │       ├── ItemCard.tsx
│   │       ├── ListItem.tsx
│   │       └── Pagination.tsx
│   ├── screens/               # Screen components
│   │   ├── auth/
│   │   │   ├── LoginScreen.tsx
│   │   │   └── SplashScreen.tsx
│   │   ├── shops/
│   │   │   ├── ShopListScreen.tsx
│   │   │   ├── ShopDetailScreen.tsx
│   │   │   ├── ShopFormScreen.tsx
│   │   │   └── index.ts
│   │   ├── users/
│   │   │   ├── UserListScreen.tsx
│   │   │   ├── UserDetailScreen.tsx
│   │   │   ├── UserFormScreen.tsx
│   │   │   └── index.ts
│   │   ├── customers/
│   │   │   ├── CustomerListScreen.tsx
│   │   │   ├── CustomerDetailScreen.tsx
│   │   │   ├── CustomerFormScreen.tsx
│   │   │   └── index.ts
│   │   ├── items/
│   │   │   ├── ItemListScreen.tsx
│   │   │   ├── ItemDetailScreen.tsx
│   │   │   ├── ItemFormScreen.tsx
│   │   │   └── index.ts
│   │   ├── brands/
│   │   │   ├── BrandListScreen.tsx
│   │   │   ├── BrandDetailScreen.tsx
│   │   │   ├── BrandFormScreen.tsx
│   │   │   └── index.ts
│   │   ├── categories/
│   │   │   ├── CategoryListScreen.tsx
│   │   │   ├── CategoryDetailScreen.tsx
│   │   │   ├── CategoryFormScreen.tsx
│   │   │   └── index.ts
│   │   └── dashboard/
│   │       └── DashboardScreen.tsx
│   ├── navigation/             # Navigation configuration
│   │   ├── AppNavigator.tsx
│   │   ├── AuthNavigator.tsx
│   │   ├── MainNavigator.tsx
│   │   ├── types.ts
│   │   └── index.ts
│   ├── store/                 # State management (Redux/Zustand)
│   │   ├── slices/
│   │   │   ├── authSlice.ts
│   │   │   ├── shopSlice.ts
│   │   │   ├── userSlice.ts
│   │   │   ├── customerSlice.ts
│   │   │   ├── itemSlice.ts
│   │   │   ├── brandSlice.ts
│   │   │   └── categorySlice.ts
│   │   ├── store.ts
│   │   └── hooks.ts
│   ├── hooks/                 # Custom React hooks
│   │   ├── useAuth.ts
│   │   ├── useApi.ts
│   │   ├── useForm.ts
│   │   ├── usePagination.ts
│   │   └── useDebounce.ts
│   ├── utils/                 # Utility functions
│   │   ├── storage.ts         # AsyncStorage helpers
│   │   ├── validation.ts     # Form validation
│   │   ├── constants.ts      # App constants
│   │   ├── helpers.ts        # Helper functions
│   │   └── formatters.ts     # Data formatters
│   ├── types/                 # TypeScript type definitions
│   │   ├── auth.ts
│   │   ├── shop.ts
│   │   ├── user.ts
│   │   ├── customer.ts
│   │   ├── item.ts
│   │   ├── brand.ts
│   │   ├── category.ts
│   │   └── common.ts
│   ├── context/               # React Context providers
│   │   ├── AuthContext.tsx
│   │   └── ThemeContext.tsx
│   └── constants/             # App-wide constants
│       ├── colors.ts
│       ├── sizes.ts
│       └── config.ts
├── assets/                    # Images, fonts, etc.
│   ├── images/
│   ├── fonts/
│   └── icons/
├── __tests__/                 # Test files
├── android/                   # Android native code
├── ios/                       # iOS native code
├── .env                       # Environment variables
├── .env.example              # Environment variables template
├── .gitignore
├── package.json
├── tsconfig.json
├── babel.config.js
└── README.md
```

---

## 4. Dependencies Installation

### Core Dependencies

```bash
# Navigation
npm install @react-navigation/native @react-navigation/native-stack @react-navigation/bottom-tabs
npm install react-native-screens react-native-safe-area-context

# HTTP Client
npm install axios

# State Management (Choose one)
# Option 1: Redux Toolkit (Recommended)
npm install @reduxjs/toolkit react-redux
# Option 2: Zustand (Lighter alternative)
npm install zustand

# Async Storage (for token persistence)
npm install @react-native-async-storage/async-storage

# Form Handling
npm install react-hook-form yup @hookform/resolvers

# UI Components
npm install react-native-paper  # Material Design components
# OR
npm install react-native-elements react-native-vector-icons  # Alternative UI library

# Date/Time Handling
npm install date-fns

# Icons
npm install react-native-vector-icons
# For Expo: npx expo install @expo/vector-icons

# Loading & Animations
npm install react-native-loading-spinner-overlay
npm install lottie-react-native  # For animations

# Image Handling
npm install react-native-image-picker

# Notifications/Toasts
npm install react-native-toast-message

# Pull to Refresh
# Built-in with React Native, but can use:
npm install react-native-pull-to-refresh

# TypeScript (if not using TypeScript template)
npm install --save-dev typescript @types/react @types/react-native
```

### Development Dependencies

```bash
# TypeScript
npm install --save-dev @types/react @types/react-native

# Linting & Formatting
npm install --save-dev eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin
npm install --save-dev prettier eslint-config-prettier

# Testing
npm install --save-dev jest @testing-library/react-native
```

### Platform-Specific Setup

#### For React Native CLI (iOS)
```bash
cd ios && pod install && cd ..
```

#### For Android
- Ensure Android SDK is installed
- Set up Android emulator or connect physical device

---

## 5. Configuration Setup

### Environment Variables

Create `.env` file:
```env
# API Configuration
API_BASE_URL=http://127.0.0.1:8000/api/v1
API_TIMEOUT=30000

# App Configuration
APP_NAME=Hafeez Center Inventory
APP_VERSION=1.0.0

# Storage Keys
STORAGE_TOKEN_KEY=@auth_token
STORAGE_USER_KEY=@user_data

# Pagination
DEFAULT_PAGE_SIZE=15
MAX_PAGE_SIZE=100
```

Create `.env.example`:
```env
API_BASE_URL=http://127.0.0.1:8000/api/v1
API_TIMEOUT=30000
APP_NAME=Hafeez Center Inventory
APP_VERSION=1.0.0
STORAGE_TOKEN_KEY=@auth_token
STORAGE_USER_KEY=@user_data
DEFAULT_PAGE_SIZE=15
MAX_PAGE_SIZE=100
```

### Install react-native-config for environment variables:
```bash
npm install react-native-config
```

### TypeScript Configuration

`tsconfig.json`:
```json
{
  "compilerOptions": {
    "target": "esnext",
    "module": "commonjs",
    "lib": ["es2017"],
    "allowJs": true,
    "jsx": "react-native",
    "noEmit": true,
    "isolatedModules": true,
    "strict": true,
    "moduleResolution": "node",
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "resolveJsonModule": true,
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"],
      "@components/*": ["src/components/*"],
      "@screens/*": ["src/screens/*"],
      "@api/*": ["src/api/*"],
      "@store/*": ["src/store/*"],
      "@utils/*": ["src/utils/*"],
      "@types/*": ["src/types/*"]
    }
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "babel.config.js", "metro.config.js"]
}
```

### Babel Configuration

`babel.config.js`:
```javascript
module.exports = {
  presets: ['module:metro-react-native-babel-preset'],
  plugins: [
    [
      'module-resolver',
      {
        root: ['./src'],
        extensions: ['.ios.js', '.android.js', '.js', '.ts', '.tsx', '.json'],
        alias: {
          '@': './src',
          '@components': './src/components',
          '@screens': './src/screens',
          '@api': './src/api',
          '@store': './src/store',
          '@utils': './src/utils',
          '@types': './src/types',
        },
      },
    ],
    'react-native-reanimated/plugin',
  ],
};
```

Install babel plugin:
```bash
npm install --save-dev babel-plugin-module-resolver
```

---

## 6. Core Services

### API Client Setup

**File: `src/api/client.ts`**

This file should:
- Create Axios instance with base URL
- Add request interceptor to attach Bearer token
- Add response interceptor for error handling
- Handle token expiration and auto-logout
- Handle network errors
- Implement request/response logging (dev mode)

**Key Features:**
- Automatic token injection in Authorization header
- Token refresh logic (if implemented)
- 401 handling (redirect to login)
- Network error handling
- Request timeout configuration
- Response data transformation

### Storage Service

**File: `src/utils/storage.ts`**

This file should:
- Store/retrieve authentication token
- Store/retrieve user data
- Clear storage on logout
- Handle storage errors gracefully
- Use AsyncStorage with proper error handling

**Methods needed:**
- `setToken(token: string): Promise<void>`
- `getToken(): Promise<string | null>`
- `removeToken(): Promise<void>`
- `setUser(user: User): Promise<void>`
- `getUser(): Promise<User | null>`
- `clearAll(): Promise<void>`

### API Service Files

Each module needs a dedicated API service file:

**Files to create:**
1. `src/api/auth.ts` - Login, logout, get user info
2. `src/api/shops.ts` - Shop CRUD operations
3. `src/api/users.ts` - User CRUD operations
4. `src/api/customers.ts` - Customer CRUD operations
5. `src/api/items.ts` - Item CRUD operations
6. `src/api/brands.ts` - Brand CRUD operations
7. `src/api/categories.ts` - Category CRUD operations

**Each API service should have:**
- TypeScript interfaces for request/response
- Functions for all CRUD operations
- Proper error handling
- Type-safe API calls
- Support for query parameters (pagination, filtering, search)

**Example structure for each service:**
```typescript
// List all items with pagination and filters
getAll(params?: ListParams): Promise<PaginatedResponse<Item>>

// Get single item by ID
getById(id: number): Promise<Item>

// Create new item
create(data: CreateItemRequest): Promise<Item>

// Update existing item
update(id: number, data: UpdateItemRequest): Promise<Item>

// Delete item
delete(id: number): Promise<void>
```

---

## 7. State Management

### Option A: Redux Toolkit (Recommended)

**File: `src/store/store.ts`**
- Configure Redux store
- Add middleware (thunk, logger for dev)
- Setup persistence

**Slices needed:**
1. `authSlice.ts` - Authentication state (user, token, isAuthenticated)
2. `shopSlice.ts` - Shop list, selected shop, loading states
3. `userSlice.ts` - User list, selected user, loading states
4. `customerSlice.ts` - Customer list, selected customer, loading states
5. `itemSlice.ts` - Item list, selected item, loading states
6. `brandSlice.ts` - Brand list, selected brand, loading states
7. `categorySlice.ts` - Category list, selected category, loading states

**Each slice should have:**
- Initial state
- Reducers for:
  - Set loading state
  - Set data
  - Set error
  - Clear data
  - Update single item
  - Add new item
  - Remove item
- Async thunks for API calls
- Selectors for accessing state

### Option B: Zustand (Lighter Alternative)

Create stores for each module with:
- State variables
- Actions for state updates
- Async actions for API calls
- Computed values (selectors)

---

## 8. Navigation Setup

### Navigation Structure

**File: `src/navigation/AppNavigator.tsx`**

Navigation should have:
1. **Auth Stack** - Login, Splash screens
2. **Main Stack** - All authenticated screens
   - Dashboard (optional)
   - Shops stack
   - Users stack
   - Customers stack
   - Items stack
   - Brands stack
   - Categories stack
3. **Tab Navigator** (optional) - Bottom tabs for quick access

### Navigation Types

**File: `src/navigation/types.ts`**

Define TypeScript types for all navigation routes and params:
- AuthStackParamList
- MainStackParamList
- TabParamList
- RootStackParamList

### Navigation Flow

1. **App starts** → Check if token exists
2. **Token exists** → Validate token (call `/me` endpoint)
3. **Valid token** → Navigate to Main Stack
4. **Invalid/No token** → Navigate to Auth Stack
5. **Login success** → Store token → Navigate to Main Stack
6. **Logout** → Clear token → Navigate to Auth Stack

---

## 9. Authentication Flow

### Login Screen

**File: `src/screens/auth/LoginScreen.tsx`**

**Features:**
- Email and password input fields
- Form validation
- Loading state during login
- Error message display
- "Remember me" option (optional)
- "Forgot password" link (if implemented)
- Auto-focus on next input
- Keyboard handling

**Flow:**
1. User enters credentials
2. Validate form
3. Show loading spinner
4. Call login API
5. On success:
   - Store token in AsyncStorage
   - Store user data
   - Update Redux/Zustand state
   - Navigate to Dashboard/Home
6. On error:
   - Display error message
   - Clear password field
   - Keep email field

### Token Management

**File: `src/hooks/useAuth.ts`**

Custom hook for:
- Login function
- Logout function
- Check authentication status
- Get current user
- Token refresh (if implemented)

**Token Storage:**
- Store in AsyncStorage
- Store in Redux/Zustand state
- Auto-inject in API requests
- Handle token expiration

### Auto-Logout

**Implementation:**
- Intercept 401 responses
- Clear token and user data
- Navigate to login screen
- Show message: "Session expired. Please login again."

---

## 10. Module Implementation

Each module (Shops, Users, Customers, Items, Brands, Categories) needs:

### List Screen

**Features:**
- Display items in a list (FlatList or SectionList)
- Pull-to-refresh
- Infinite scroll / Pagination
- Search functionality
- Filter options (status, type, etc.)
- Empty state when no data
- Loading state
- Error state with retry button
- FAB (Floating Action Button) for "Add New"
- Swipe actions (edit/delete) - optional

**Components needed:**
- SearchBar component
- FilterModal component
- ItemCard/ListItem component
- LoadingSpinner component
- EmptyState component
- ErrorMessage component

### Detail Screen

**Features:**
- Display all item details
- Edit button (navigates to form)
- Delete button with confirmation
- Loading state
- Error handling
- Back navigation

### Form Screen (Add/Edit)

**Features:**
- Reusable form for both Add and Edit
- Form validation
- Loading state during submit
- Success message
- Error display per field
- Cancel button (with unsaved changes warning)
- Save button (disabled during submission)
- Auto-populate fields in Edit mode

**Form Fields per Module:**

**Shops:**
- Title (required, max 150)
- Address (optional, textarea)
- Owner Name (required, max 150)
- Contact No (required, max 25)
- Status (required, dropdown: Active/Inactive)

**Users:**
- Shop (required, dropdown - shops created by user)
- Name (required, max 255)
- Email (required, email validation)
- Password (required for add, optional for edit)
- Confirm Password (required if password provided)
- Contact No (optional, max 25)
- User Type (required, dropdown: admin/user)
- Status (required, dropdown: Active/Inactive)

**Customers:**
- Name (required, max 150)
- Type (required, dropdown: walk-in/shop)
- Vendor Type (required, dropdown: customer/vendor/both)
- ID Card (optional, max 25)
- Contact Number (optional, max 25)
- Address (optional, textarea)
- Opening Balance (optional, decimal)
- Opening Balance Date (optional, date picker)
- Shop (required, dropdown - user's shops)
- Status (required, dropdown: Active/Inactive)

**Items:**
- Shop (required, dropdown - user's shops)
- Category (required, dropdown - active categories)
- Brand (required, dropdown - active brands)
- Title (required, max 250)
- Description (optional, textarea)
- RAM (optional, max 100)
- Memory (optional, max 100)
- Color (optional, max 50)
- Registration Type (required, dropdown: Non PTA/PTA/CPID/JV)
- SIM Status (required, dropdown: Single/Dual Physical/Dual + eSim/eSim Dual)
- IMEI 1 (optional, max 100)
- IMEI 2 (optional, max 100)
- Serial Number (optional, max 100)
- Condition (required, dropdown: New/Used/Used Rough)
- Status (required, dropdown: Active/Inactive)

**Brands:**
- Title (required, max 150)
- Category (required, dropdown - active categories)
- Status (required, dropdown: Active/Inactive)

**Categories:**
- Title (required, max 150)
- Status (required, dropdown: Active/Inactive)

### Data Flow for Each Module

1. **List Screen loads:**
   - Check if data exists in store
   - If not, fetch from API
   - Show loading state
   - Display data in list
   - Handle pagination

2. **User taps item:**
   - Navigate to Detail Screen
   - Fetch full item details (if not in store)
   - Display details

3. **User taps "Add" button:**
   - Navigate to Form Screen (mode: "add")
   - Initialize empty form
   - Load dropdown data (shops, categories, brands, etc.)

4. **User taps "Edit" button:**
   - Navigate to Form Screen (mode: "edit")
   - Pre-populate form with item data
   - Load dropdown data

5. **User submits form:**
   - Validate form
   - Show loading state
   - Call create/update API
   - On success:
     - Update store
     - Show success message
     - Navigate back to list
     - Refresh list data
   - On error:
     - Display validation errors
     - Keep form data

6. **User taps "Delete":**
   - Show confirmation dialog
   - On confirm:
     - Call delete API
     - Remove from store
     - Navigate back to list
     - Show success message

---

## 11. UI Components

### Common Components

**Button Component** (`src/components/common/Button.tsx`)
- Primary, secondary, danger variants
- Loading state
- Disabled state
- Icon support
- Full width option

**Input Component** (`src/components/common/Input.tsx`)
- Label
- Placeholder
- Error message
- Required indicator
- Icon support (left/right)
- Password visibility toggle
- Keyboard type configuration

**Card Component** (`src/components/common/Card.tsx`)
- Shadow/elevation
- Padding customization
- Pressable option

**LoadingSpinner Component** (`src/components/common/LoadingSpinner.tsx`)
- Full screen overlay
- Inline spinner
- Customizable size and color

**ErrorMessage Component** (`src/components/common/ErrorMessage.tsx`)
- Display API errors
- Display validation errors
- Retry button option

**EmptyState Component** (`src/components/common/EmptyState.tsx`)
- Icon
- Title
- Message
- Action button (optional)

**SearchBar Component** (`src/components/common/SearchBar.tsx`)
- Debounced search
- Clear button
- Loading indicator
- Placeholder customization

### Form Components

**FormField Component** (`src/components/forms/FormField.tsx`)
- Wrapper for Input with label and error
- Integration with react-hook-form

**SelectDropdown Component** (`src/components/forms/SelectDropdown.tsx`)
- Searchable dropdown
- Multi-select option
- Customizable styling

**DatePicker Component** (`src/components/forms/DatePicker.tsx`)
- Date selection
- Time selection (if needed)
- Format customization

### List Components

**ItemCard Component** (`src/components/lists/ItemCard.tsx`)
- Display item information
- Action buttons (edit/delete)
- Swipe actions (optional)
- Press to navigate to detail

**Pagination Component** (`src/components/lists/Pagination.tsx`)
- Page numbers
- Previous/Next buttons
- Items per page selector
- Total count display

---

## 12. Error Handling

### API Error Handling

**Types of errors to handle:**
1. **Network errors** - No internet connection
2. **401 Unauthorized** - Invalid/expired token
3. **403 Forbidden** - Insufficient permissions
4. **404 Not Found** - Resource not found
5. **422 Validation Error** - Form validation errors
6. **500 Server Error** - Server-side errors
7. **Timeout errors** - Request timeout

**Error handling strategy:**
- Centralized error handler in API client
- User-friendly error messages
- Retry mechanism for network errors
- Auto-logout on 401
- Display field-specific errors for 422
- Generic error message for 500

### Form Validation

**Client-side validation:**
- Required fields
- Email format
- Password strength
- Min/max length
- Number ranges
- Custom validation rules

**Server-side validation:**
- Display API validation errors
- Map errors to form fields
- Show error messages below fields

---

## 13. Testing & Debugging

### Testing Setup

**Unit Tests:**
- Test utility functions
- Test form validation
- Test API service functions (mocked)

**Integration Tests:**
- Test navigation flow
- Test authentication flow
- Test CRUD operations

**E2E Tests (Optional):**
- Use Detox or Appium
- Test critical user flows

### Debugging Tools

**React Native Debugger:**
- Install React Native Debugger
- Enable remote debugging
- Inspect Redux store
- View network requests
- Check console logs

**Flipper (Optional):**
- Network inspector
- Redux DevTools
- Layout inspector
- Logs viewer

**Development Tools:**
- React DevTools
- Redux DevTools
- Axios interceptor logging
- Console logging (remove in production)

---

## 14. Build & Deployment

### Android Build

**Development Build:**
```bash
# Debug APK
cd android && ./gradlew assembleDebug

# APK location: android/app/build/outputs/apk/debug/app-debug.apk
```

**Production Build:**
```bash
# Generate signed APK
cd android && ./gradlew assembleRelease

# Or generate AAB (Android App Bundle) for Play Store
cd android && ./gradlew bundleRelease
```

**Requirements:**
- Generate signing key
- Configure `android/app/build.gradle` with signing config
- Update version code and version name

### iOS Build

**Development Build:**
```bash
# Open Xcode
open ios/HafeezCenterInventory.xcworkspace

# Select device/simulator
# Click Run
```

**Production Build:**
1. Open Xcode project
2. Select "Any iOS Device" or specific device
3. Product → Archive
4. Distribute App
5. Choose distribution method (App Store, Ad Hoc, Enterprise)

**Requirements:**
- Apple Developer account
- Certificates and provisioning profiles
- App Store Connect setup

### Environment Configuration

**Development:**
- Use development API URL
- Enable debug logging
- Show error details

**Production:**
- Use production API URL
- Disable debug logging
- Hide sensitive error details
- Enable error reporting (Sentry, etc.)

### Code Obfuscation (Optional)

- Use ProGuard for Android
- Use code obfuscation tools
- Remove console logs in production build

---

## 15. Additional Features to Implement

### Optional Enhancements

1. **Offline Support**
   - Cache data locally
   - Queue API requests when offline
   - Sync when connection restored

2. **Push Notifications**
   - Integrate Firebase Cloud Messaging
   - Handle notification taps
   - Badge counts

3. **Biometric Authentication**
   - Face ID / Touch ID login
   - Secure token storage

4. **Dark Mode**
   - Theme context
   - Toggle in settings
   - Persist preference

5. **Multi-language Support**
   - i18n library (react-i18next)
   - Language switcher
   - Persist language preference

6. **Image Upload**
   - For items/products
   - Image picker
   - Image compression
   - Preview before upload

7. **Export/Import**
   - Export data to CSV/PDF
   - Import from file
   - Share functionality

8. **Analytics**
   - Track user actions
   - Screen views
   - Error tracking (Sentry)

9. **Performance Optimization**
   - Image optimization
   - List virtualization
   - Memoization
   - Code splitting

10. **Accessibility**
    - Screen reader support
    - Proper labels
    - High contrast mode
    - Font scaling

---

## 16. Implementation Checklist

### Phase 1: Foundation
- [ ] Project initialization
- [ ] Folder structure setup
- [ ] Dependencies installation
- [ ] Configuration files
- [ ] TypeScript setup
- [ ] Navigation setup
- [ ] API client setup
- [ ] Storage service setup

### Phase 2: Authentication
- [ ] Login screen
- [ ] Auth API service
- [ ] Token management
- [ ] Auth state management
- [ ] Auto-logout on token expiry
- [ ] Splash screen with auth check

### Phase 3: Core Modules
- [ ] Shops module (List, Detail, Form)
- [ ] Users module (List, Detail, Form)
- [ ] Customers module (List, Detail, Form)
- [ ] Items module (List, Detail, Form)
- [ ] Brands module (List, Detail, Form)
- [ ] Categories module (List, Detail, Form)

### Phase 4: UI/UX
- [ ] Common components
- [ ] Form components
- [ ] List components
- [ ] Loading states
- [ ] Error states
- [ ] Empty states
- [ ] Success messages
- [ ] Theme/styling

### Phase 5: Advanced Features
- [ ] Search functionality
- [ ] Filtering
- [ ] Pagination
- [ ] Pull-to-refresh
- [ ] Infinite scroll
- [ ] Form validation
- [ ] Image handling (if needed)

### Phase 6: Testing & Polish
- [ ] Unit tests
- [ ] Integration tests
- [ ] Bug fixes
- [ ] Performance optimization
- [ ] UI/UX improvements
- [ ] Error handling refinement

### Phase 7: Build & Deploy
- [ ] Android build setup
- [ ] iOS build setup
- [ ] Environment configuration
- [ ] Production build
- [ ] App store submission (if applicable)

---

## 17. API Endpoints Reference

### Authentication
- `POST /api/v1/login` - Login
- `GET /api/v1/me` - Get current user
- `POST /api/v1/logout` - Logout current device
- `POST /api/v1/logout-all` - Logout all devices

### Shops
- `GET /api/v1/shops` - List shops (query: per_page, status, search)
- `GET /api/v1/shops/{id}` - Get shop
- `POST /api/v1/shops` - Create shop
- `PATCH /api/v1/shops/{id}` - Update shop
- `DELETE /api/v1/shops/{id}` - Delete shop

### Users
- `GET /api/v1/users` - List users (query: per_page, shop_id, status, user_type, search)
- `GET /api/v1/users/{id}` - Get user
- `POST /api/v1/users` - Create user
- `PATCH /api/v1/users/{id}` - Update user
- `DELETE /api/v1/users/{id}` - Delete user

### Customers
- `GET /api/v1/customers` - List customers (query: per_page, shop_id, status, type, vendor_type, search)
- `GET /api/v1/customers/{id}` - Get customer
- `POST /api/v1/customers` - Create customer
- `PATCH /api/v1/customers/{id}` - Update customer
- `DELETE /api/v1/customers/{id}` - Delete customer

### Items
- `GET /api/v1/items` - List items (query: per_page, shop_id, cat_id, brand_id, status, condition, search)
- `GET /api/v1/items/{id}` - Get item
- `POST /api/v1/items` - Create item
- `PATCH /api/v1/items/{id}` - Update item
- `DELETE /api/v1/items/{id}` - Delete item

### Brands
- `GET /api/v1/brands` - List brands (query: per_page, cat_id, status, search)
- `GET /api/v1/brands/{id}` - Get brand
- `POST /api/v1/brands` - Create brand
- `PATCH /api/v1/brands/{id}` - Update brand
- `DELETE /api/v1/brands/{id}` - Delete brand

### Categories
- `GET /api/v1/categories` - List categories (query: per_page, status, search)
- `GET /api/v1/categories/{id}` - Get category
- `POST /api/v1/categories` - Create category
- `PATCH /api/v1/categories/{id}` - Update category
- `DELETE /api/v1/categories/{id}` - Delete category

### Response Format
All endpoints return:
```json
{
  "success": true/false,
  "message": "Human-readable message",
  "data": { ... },
  "errors": { ... }
}
```

### Error Codes
- `200` - Success
- `201` - Created
- `401` - Unauthorized (invalid/missing token)
- `403` - Forbidden (insufficient permissions)
- `404` - Not Found
- `422` - Validation Error
- `500` - Server Error

---

## 18. Best Practices

### Code Organization
- Keep components small and focused
- Use TypeScript for type safety
- Follow consistent naming conventions
- Separate concerns (UI, logic, data)

### Performance
- Use FlatList for long lists
- Implement pagination
- Optimize images
- Memoize expensive computations
- Avoid unnecessary re-renders

### Security
- Never store sensitive data in plain text
- Use secure storage for tokens
- Validate all user inputs
- Sanitize data before display
- Use HTTPS in production

### User Experience
- Show loading states
- Provide feedback for actions
- Handle errors gracefully
- Implement pull-to-refresh
- Add empty states
- Optimize for offline scenarios

### Maintainability
- Write clean, readable code
- Add comments for complex logic
- Use constants for magic numbers/strings
- Follow DRY principle
- Write unit tests

---

## 19. Troubleshooting Common Issues

### Network Issues
- **Problem**: API calls failing
- **Solution**: Check API base URL, network connectivity, CORS settings

### Token Issues
- **Problem**: 401 errors after login
- **Solution**: Check token storage, token injection in headers, token expiration

### Navigation Issues
- **Problem**: Navigation not working
- **Solution**: Check navigation setup, route names, navigation types

### Build Issues
- **Problem**: Android/iOS build failing
- **Solution**: Check dependencies, native module setup, platform-specific configurations

### Performance Issues
- **Problem**: App is slow
- **Solution**: Optimize images, implement pagination, use FlatList, check for memory leaks

---

## 20. Resources & Documentation

### Official Documentation
- [React Native Docs](https://reactnative.dev/)
- [React Navigation](https://reactnavigation.org/)
- [Redux Toolkit](https://redux-toolkit.js.org/)
- [Axios](https://axios-http.com/)
- [React Hook Form](https://react-hook-form.com/)

### Community Resources
- [React Native Community](https://github.com/react-native-community)
- [Awesome React Native](https://github.com/jondot/awesome-react-native)
- [React Native Directory](https://reactnative.directory/)

### API Documentation
- OpenAPI YAML: `http://127.0.0.1:8000/api/v1/documentation.yaml`
- Interactive Docs: `http://127.0.0.1:8000/api/v1/documentation`
- Postman Collection: `Hafeez_Center_Inventory_API.postman_collection.json`

---

## Conclusion

This guide provides a complete roadmap for building a React Native application that integrates with the Hafeez Center Inventory API. Follow the phases sequentially, and refer to the API documentation for detailed endpoint specifications.

**Key Success Factors:**
1. Start with a solid foundation (project setup, navigation, API client)
2. Implement authentication first
3. Build modules incrementally
4. Test thoroughly at each phase
5. Follow best practices for code quality and performance
6. Prioritize user experience

**Estimated Timeline:**
- Phase 1-2 (Foundation + Auth): 1-2 weeks
- Phase 3 (Core Modules): 3-4 weeks
- Phase 4-5 (UI/UX + Advanced Features): 2-3 weeks
- Phase 6-7 (Testing + Build): 1-2 weeks

**Total Estimated Time: 7-11 weeks** (depending on team size and experience)

Good luck with your React Native development! 🚀

