# API Documentation for Target Domain

This document describes the API endpoints that your target domain must implement to work with the Shopify Order Sender app.

## Overview

The Shopify Order Sender app requires your target domain to implement two API endpoints:
1. **GET /api/user-info** - For retrieving user information during configuration
2. **POST /api/orders** - For receiving order data from Shopify

## Authentication

Currently, the app sends requests without authentication. If you need authentication, you can modify the `WebhookController` to include API keys or tokens in the requests.

## Endpoints

### 1. GET /api/user-info

This endpoint is called during the app configuration process to retrieve the user ID associated with your domain.

#### Request
```http
GET /api/user-info HTTP/1.1
Host: your-domain.com
Content-Type: application/json
```

#### Response
```json
{
  "user_id": 123,
  "status": "success"
}
```

#### Response Fields
- `user_id` (integer, required): The unique user identifier for your system
- `status` (string, optional): Status message

#### Error Response
```json
{
  "error": "User not found",
  "status": "error"
}
```

#### Example Implementation (PHP)
```php
<?php
// GET /api/user-info
header('Content-Type: application/json');

// Your logic to determine user ID
$user_id = getCurrentUserId(); // Implement this function

if ($user_id) {
    echo json_encode([
        'user_id' => $user_id,
        'status' => 'success'
    ]);
} else {
    http_response_code(404);
    echo json_encode([
        'error' => 'User not found',
        'status' => 'error'
    ]);
}
?>
```

### 2. POST /api/orders

This endpoint receives order data whenever a new order is created in the connected Shopify store.

#### Request
```http
POST /api/orders HTTP/1.1
Host: your-domain.com
Content-Type: application/json

{
  "user_id": 123,
  "order_id": "1001",
  "client_name": "John Doe",
  "address": "123 Main St --- New York",
  "product_name": "Product Name (Qty: 2)",
  "product_desc": "Product Name (Qty: 2)",
  "price": 29.99,
  "quantity": 2,
  "sector_id": 1,
  "phone_1": "1234567890",
  "notes": "Order notes",
  "service_type": "1"
}
```

#### Request Fields

| Field | Type | Description |
|-------|------|-------------|
| `user_id` | integer | User ID from your system |
| `order_id` | string | Shopify order number (numeric only) |
| `client_name` | string | Customer's full name |
| `address` | string | Full address including city (format: "address --- city") |
| `product_name` | string | Product names with quantities |
| `product_desc` | string | Product descriptions (same as product_name) |
| `price` | float | Total order price (0 if paid) |
| `quantity` | integer | Total quantity of items |
| `sector_id` | integer | Sector ID based on city mapping |
| `phone_1` | string | Customer phone number (without +2 prefix) |
| `notes` | string | Order notes/comments |
| `service_type` | string | Service type (default: "1") |

#### Response
```json
{
  "status": "success",
  "message": "Order received successfully",
  "order_id": "1001"
}
```

#### Error Response
```json
{
  "status": "error",
  "message": "Invalid order data",
  "errors": {
    "user_id": "User ID is required",
    "order_id": "Order ID is required"
  }
}
```

#### Example Implementation (PHP)
```php
<?php
// POST /api/orders
header('Content-Type: application/json');

// Get JSON input
$input = json_decode(file_get_contents('php://input'), true);

// Validate required fields
$required_fields = ['user_id', 'order_id', 'client_name'];
$errors = [];

foreach ($required_fields as $field) {
    if (empty($input[$field])) {
        $errors[$field] = ucfirst($field) . ' is required';
    }
}

if (!empty($errors)) {
    http_response_code(400);
    echo json_encode([
        'status' => 'error',
        'message' => 'Validation failed',
        'errors' => $errors
    ]);
    exit;
}

// Process the order
try {
    // Your order processing logic here
    $result = processOrder($input);
    
    echo json_encode([
        'status' => 'success',
        'message' => 'Order received successfully',
        'order_id' => $input['order_id']
    ]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'status' => 'error',
        'message' => 'Failed to process order: ' . $e->getMessage()
    ]);
}

function processOrder($orderData) {
    // Implement your order processing logic
    // Save to database, send to shipping provider, etc.
    
    // Example database insertion
    $pdo = new PDO('mysql:host=localhost;dbname=your_db', $username, $password);
    
    $stmt = $pdo->prepare("
        INSERT INTO orders (
            user_id, order_id, client_name, address, product_name, 
            price, quantity, sector_id, phone, notes, service_type, created_at
        ) VALUES (
            :user_id, :order_id, :client_name, :address, :product_name,
            :price, :quantity, :sector_id, :phone, :notes, :service_type, NOW()
        )
    ");
    
    return $stmt->execute([
        ':user_id' => $orderData['user_id'],
        ':order_id' => $orderData['order_id'],
        ':client_name' => $orderData['client_name'],
        ':address' => $orderData['address'],
        ':product_name' => $orderData['product_name'],
        ':price' => $orderData['price'],
        ':quantity' => $orderData['quantity'],
        ':sector_id' => $orderData['sector_id'],
        ':phone' => $orderData['phone_1'],
        ':notes' => $orderData['notes'],
        ':service_type' => $orderData['service_type']
    ]);
}
?>
```

## Data Processing Notes

### Address Format
The address field combines shipping/billing address with city in the format:
```
"Street Address Line 1 Street Address Line 2 --- City Name"
```

### Phone Number Processing
- Phone numbers have the "+2" prefix removed
- Original format: "+201234567890"
- Sent format: "01234567890"

### Price Handling
- If the order's financial status is "paid", the price is sent as 0
- Otherwise, the current total price is sent

### Product Information
- Multiple products are combined into a single string
- Format: "Product 1 (Qty: 2) - Product 2 (Qty: 1)"
- Both `product_name` and `product_desc` contain the same value

### Sector ID Mapping
The app includes built-in mapping for Egyptian cities:

| City | Sector ID |
|------|-----------|
| Cairo | 1 |
| Alexandria | 2 |
| Giza | 3 |
| ... | ... |

Default sector ID is 1 if city is not found in the mapping.

## Testing Your Implementation

### Test User Info Endpoint
```bash
curl -X GET https://your-domain.com/api/user-info \
  -H "Content-Type: application/json"
```

Expected response:
```json
{
  "user_id": 123,
  "status": "success"
}
```

### Test Order Endpoint
```bash
curl -X POST https://your-domain.com/api/orders \
  -H "Content-Type: application/json" \
  -d '{
    "user_id": 123,
    "order_id": "1001",
    "client_name": "John Doe",
    "address": "123 Main St --- New York",
    "product_name": "Test Product (Qty: 1)",
    "product_desc": "Test Product (Qty: 1)",
    "price": 29.99,
    "quantity": 1,
    "sector_id": 1,
    "phone_1": "1234567890",
    "notes": "Test order",
    "service_type": "1"
  }'
```

Expected response:
```json
{
  "status": "success",
  "message": "Order received successfully",
  "order_id": "1001"
}
```

## Error Handling

Your API should handle these error scenarios:

1. **Invalid JSON**: Return 400 Bad Request
2. **Missing required fields**: Return 400 Bad Request with field errors
3. **User not found**: Return 404 Not Found
4. **Database errors**: Return 500 Internal Server Error
5. **Processing failures**: Return 500 Internal Server Error

## Security Considerations

1. **Input Validation**: Always validate and sanitize input data
2. **SQL Injection**: Use prepared statements for database queries
3. **Rate Limiting**: Implement rate limiting to prevent abuse
4. **Logging**: Log all order processing attempts for debugging
5. **Authentication**: Consider implementing API key authentication

## Example Database Schema

```sql
CREATE TABLE orders (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT NOT NULL,
    order_id VARCHAR(50) NOT NULL,
    client_name VARCHAR(255) NOT NULL,
    address TEXT NOT NULL,
    product_name TEXT NOT NULL,
    price DECIMAL(10,2) NOT NULL,
    quantity INT NOT NULL,
    sector_id INT NOT NULL,
    phone VARCHAR(20),
    notes TEXT,
    service_type VARCHAR(10),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_user_id (user_id),
    INDEX idx_order_id (order_id)
);
```

## Support

If you need help implementing these endpoints:
1. Review the example implementations above
2. Test your endpoints using the provided curl commands
3. Check the Shopify Order Sender app logs for detailed error messages
4. Ensure your endpoints are publicly accessible and return proper JSON responses

