# Backend URL Centralization

## Overview

This document describes the centralized backend URL configuration that has been implemented to make it easier to update the Laravel backend URL throughout the application.

## Problem

Previously, the backend URL (`https://sellzaki.local`) was hardcoded in **79+ locations** across the codebase, making it difficult and error-prone to update when the backend URL changed.

## Solution

The backend URL is now centralized in a single configuration file with environment variable support.

## Configuration

### Environment Variable

Add this to your `.env` file (or copy from `.env.example`):

```bash
VITE_BACKEND_URL=https://sellzaki.local
```

**Important Notes:**
- Change this URL when your backend domain changes
- Do NOT include a trailing slash
- This variable must start with `VITE_` to be accessible in the frontend code
- After changing this value, restart your Vite dev server

### Configuration File

The main configuration is in `/resources/js/config/api.ts`:

```typescript
const BACKEND_URL = import.meta.env.VITE_BACKEND_URL || 'https://sellzaki.local';

export const API_CONFIG = {
  BASE_URL: import.meta.env.DEV ? '' : BACKEND_URL,
  BACKEND_URL: BACKEND_URL,
  // ... other config
};
```

## Helper Functions

### `buildApiUrl(endpoint: string)`

Builds API URLs that work in both development and production:

```typescript
import { buildApiUrl } from '@/config/api';

// In development: '/api/admin/users'
// In production: 'https://sellzaki.local/api/admin/users'
const url = buildApiUrl('/api/admin/users');
```

**Usage:**
```typescript
const response = await authService.authenticatedRequest(
  buildApiUrl('/api/admin/promotions')
);
```

### `getBackendUrl(path: string)`

Gets absolute backend URLs (always includes domain) for assets and static resources:

```typescript
import { getBackendUrl } from '@/config/api';

// Always: 'https://sellzaki.local/assets/images/logo.png'
const logoUrl = getBackendUrl('/assets/images/logo.png');
```

**Usage:**
```typescript
<img src={getBackendUrl('/assets/images/logo.png')} alt="Logo" />
```

## Files Updated

The following files now use the centralized configuration:

### Core Configuration
- `/resources/js/config/api.ts` - Main API configuration
- `/resources/js/services/authService.ts` - Authentication service
- `/resources/js/services/stockValidationService.ts` - Stock validation
- `/resources/js/utils/imageUtils.tsx` - Image utility functions
- `/vite.config.ts` - Vite proxy configuration

### Feature Modules
- `/resources/js/features/transfer/api/transfer.ts`
- `/resources/js/features/exchange/api/exchange.ts`
- `/resources/js/features/exchange/components/ExchangeForm.tsx`
- `/resources/js/features/exchange/pages/ExchangeList.tsx`
- `/resources/js/features/transactions/hooks/useRecentTransactions.ts`

### Admin Pages
- `/resources/js/pages/admin/Promotions/CreatePromotion.tsx`
- `/resources/js/pages/admin/Promotions/EditPromotion.tsx`
- `/resources/js/pages/admin/Promotions/ViewPromotion.tsx`
- `/resources/js/pages/admin/Promotions/PromotionsList.tsx`
- `/resources/js/pages/admin/Promotions/PromotionReports.tsx`
- `/resources/js/pages/admin/Promotions/VouchersManagement.tsx`

### Components
- `/resources/js/components/Layout/Layout.tsx`
- `/resources/js/components/Layout/Sidebar.tsx`
- `/resources/js/components/Promotions/CustomerSelector.tsx`
- `/resources/js/components/Promotions/ProductCategorySelector.tsx`
- `/resources/js/components/admin/PermissionManager.tsx`
- `/resources/js/components/Pages/Sales.tsx`
- `/resources/js/components/Pages/Dashboard.tsx`
- `/resources/js/components/Pages/AdminDashboard.tsx`
- `/resources/js/components/Pages/Transactions.tsx`
- `/resources/js/components/Pages/InvoiceDisplay.tsx`
- `/resources/js/components/Pages/InventoryReport.tsx`
- `/resources/js/components/Pages/Admin/ManageStaff.tsx`
- `/resources/js/components/Pages/Admin/EditStore.tsx`

### Stores and Hooks
- `/resources/js/stores/authStore.ts`
- `/resources/js/stores/cartStore.ts`
- `/resources/js/stores/privilegesStore.ts`
- `/resources/js/hooks/usePosPromotions.ts`

### Contexts
- `/resources/js/contexts/PermissionProvider.tsx`

## Development vs Production

### Development Mode
- Vite dev server runs on `localhost:3000`
- API calls use relative URLs (e.g., `/api/admin/users`)
- Vite proxy forwards requests to the backend URL
- No CORS issues

### Production Mode
- Frontend is built and served from the backend
- API calls use absolute URLs (e.g., `https://sellzaki.local/api/admin/users`)
- Direct communication with the backend

## How to Update the Backend URL

### For All Developers

1. **Update the environment variable:**
   ```bash
   # In your .env file
   VITE_BACKEND_URL=https://your-new-backend.local
   ```

2. **Restart the Vite dev server:**
   ```bash
   npm run dev
   ```

3. **That's it!** All URLs will now use the new backend URL.

### For Production Deployment

1. **Update the production `.env` file** on your server:
   ```bash
   VITE_BACKEND_URL=https://api.yourproduction.com
   ```

2. **Rebuild the frontend:**
   ```bash
   npm run build
   ```

3. **Deploy the built files** to your production server.

## Vite Proxy Configuration

The Vite development server is configured to proxy API requests in `/vite.config.ts`:

```typescript
proxy: {
  '/api': {
    target: process.env.VITE_BACKEND_URL || 'https://sellzaki.local',
    changeOrigin: true,
    secure: false,
    rewrite: (path) => path,
  },
}
```

This allows the frontend to make requests to `/api/...` which are automatically forwarded to your backend URL during development.

## Best Practices

1. **Always use the helper functions** instead of hardcoding URLs
2. **Use `buildApiUrl()`** for API endpoints
3. **Use `getBackendUrl()`** for static assets and images
4. **Never hardcode the backend URL** in component code
5. **Update only the environment variable** when the backend URL changes

## Migration Notes

All existing hardcoded URLs have been replaced with centralized configuration. If you need to add new API calls:

```typescript
// ❌ DON'T DO THIS
const response = await fetch('https://sellzaki.local/api/users');

// ✅ DO THIS INSTEAD
import { buildApiUrl } from '@/config/api';
const response = await authService.authenticatedRequest(
  buildApiUrl('/api/users')
);
```

## Troubleshooting

### Issue: "API calls failing after URL change"

**Solution:** Make sure you:
1. Updated the `VITE_BACKEND_URL` in your `.env` file
2. Restarted the Vite dev server (`npm run dev`)
3. Cleared your browser cache

### Issue: "Images not loading"

**Solution:** Use `getBackendUrl()` for image URLs:
```typescript
<img src={getBackendUrl('/assets/images/logo.png')} />
```

### Issue: "Environment variable not recognized"

**Solution:** 
- Make sure the variable name starts with `VITE_`
- Restart the dev server after adding/changing environment variables
- Check that the `.env` file is in the project root

## Summary

The backend URL is now configured in **ONE place only**:
- Set `VITE_BACKEND_URL` in your `.env` file
- Restart the dev server
- All API calls and asset URLs will use the new URL automatically

No more hunting through dozens of files to update URLs! 🎉

