# Printer Settings API Documentation

## Overview
This document describes the Printer Settings CRUD API endpoints for managing printer configurations in the LimooFood system.

## Base URL
```
https://your-domain.com/api/v1/admin/printer-settings
```

## Authentication
All endpoints require authentication via Bearer token:
```
Authorization: Bearer {your_token}
```

## Data Model

### PrinterSetting Object
```json
{
  "id": 1,
  "branch_id": 1,
  "name": "main_printer",
  "title": "پرینتر اصلی",
  "options": "{\"paper_size\":\"A4\",\"quality\":\"high\",\"orientation\":\"portrait\"}",
  "status": "active",
  "type": "app",
  "created_at": "2024-01-15T10:30:00.000000Z",
  "updated_at": "2024-01-15T10:30:00.000000Z",
  "deleted_at": null,
  "branch": {
    "id": 1,
    "title": "شعبه مرکزی",
    "address": "تهران، خیابان ولیعصر"
  }
}
```

### Field Descriptions
| Field | Type | Description | Required |
|-------|------|-------------|----------|
| `id` | integer | Unique identifier | Auto-generated |
| `branch_id` | integer | Branch ID (must exist in branches table) | Yes |
| `name` | string | Printer name (max 255 chars) | Yes |
| `title` | string | Display title (max 255 chars) | Yes |
| `options` | string | JSON configuration string | Yes |
| `status` | string | Status: "active" or "inactive" | No (default: "active") |
| `type` | string | Printer type: "app" or "qz" | Yes |
| `created_at` | datetime | Creation timestamp | Auto-generated |
| `updated_at` | datetime | Last update timestamp | Auto-generated |
| `deleted_at` | datetime | Soft delete timestamp | Auto-generated |
| `branch` | object | Branch information (included in responses) | Auto-loaded |

---

## API Endpoints

### 1. List Printer Settings

**GET** `/printer-settings/`

Get a paginated list of printer settings with optional filtering.

#### Query Parameters
| Parameter | Type | Description | Example |
|-----------|------|-------------|---------|
| `search` | string | Search in name and title | `?search=main` |
| `branch_id` | integer | Filter by branch ID | `?branch_id=1` |
| `status` | string | Filter by status | `?status=active` |
| `type` | string | Filter by type | `?type=app` |
| `page` | integer | Page number for pagination | `?page=2` |

#### Example Request
```bash
GET /api/v1/admin/printer-settings/?search=main&branch_id=1&status=active&type=app&page=1
```

#### Response
```json
{
  "data": {
    "current_page": 1,
    "data": [
      {
        "id": 1,
        "branch_id": 1,
        "name": "main_printer",
        "title": "پرینتر اصلی",
        "options": "{\"paper_size\":\"A4\",\"quality\":\"high\"}",
        "status": "active",
        "type": "app",
        "created_at": "2024-01-15T10:30:00.000000Z",
        "updated_at": "2024-01-15T10:30:00.000000Z",
        "deleted_at": null,
        "branch": {
          "id": 1,
          "title": "شعبه مرکزی"
        }
      }
    ],
    "first_page_url": "http://localhost/api/v1/admin/printer-settings?page=1",
    "from": 1,
    "last_page": 1,
    "last_page_url": "http://localhost/api/v1/admin/printer-settings?page=1",
    "links": [...],
    "next_page_url": null,
    "path": "http://localhost/api/v1/admin/printer-settings",
    "per_page": 25,
    "prev_page_url": null,
    "to": 1,
    "total": 1
  }
}
```

---

### 2. Get Single Printer Setting

**GET** `/printer-settings/show`

Get a specific printer setting by ID.

#### Query Parameters
| Parameter | Type | Description | Required |
|-----------|------|-------------|----------|
| `printer_setting_id` | integer | Printer setting ID | Yes |

#### Example Request
```bash
GET /api/v1/admin/printer-settings/show?printer_setting_id=1
```

#### Response
```json
{
  "data": {
    "id": 1,
    "branch_id": 1,
    "name": "main_printer",
    "title": "پرینتر اصلی",
    "options": "{\"paper_size\":\"A4\",\"quality\":\"high\",\"orientation\":\"portrait\"}",
    "status": "active",
    "type": "app",
    "created_at": "2024-01-15T10:30:00.000000Z",
    "updated_at": "2024-01-15T10:30:00.000000Z",
    "deleted_at": null,
    "branch": {
      "id": 1,
      "title": "شعبه مرکزی",
      "address": "تهران، خیابان ولیعصر"
    }
  }
}
```

#### Error Response
```json
{
  "error": "تنظیمات پرینتر یافت نشد"
}
```

---

### 3. Create Printer Setting

**POST** `/printer-settings/store`

Create a new printer setting.

#### Request Body
```json
{
  "branch_id": 1,
  "name": "main_printer",
  "title": "پرینتر اصلی",
  "options": "{\"paper_size\":\"A4\",\"quality\":\"high\",\"orientation\":\"portrait\"}",
  "status": "active",
  "type": "app"
}
```

#### Field Validation
| Field | Rules | Error Message |
|-------|-------|---------------|
| `branch_id` | required, exists:branches,id | شعبه الزامی است / شعبه انتخابی معتبر نیست |
| `name` | required, string, max:255 | نام الزامی است / نام باید متن باشد / نام نباید بیشتر از 255 کاراکتر باشد |
| `title` | required, string, max:255 | عنوان الزامی است / عنوان باید متن باشد / عنوان نباید بیشتر از 255 کاراکتر باشد |
| `options` | required, json | تنظیمات الزامی است / تنظیمات باید در فرمت JSON باشد |
| `status` | nullable, in:active,inactive | وضعیت باید active یا inactive باشد |
| `type` | required, in:app,qz | نوع الزامی است / نوع باید app یا qz باشد |

#### Example Request
```bash
POST /api/v1/admin/printer-settings/store
Content-Type: application/json
Authorization: Bearer {your_token}

{
  "branch_id": 1,
  "name": "kitchen_printer",
  "title": "پرینتر آشپزخانه",
  "options": "{\"paper_size\":\"A4\",\"quality\":\"high\",\"orientation\":\"portrait\",\"copies\":1}",
  "status": "active",
  "type": "qz"
}
```

#### Success Response (201)
```json
{
  "data": {
    "id": 2,
    "branch_id": 1,
    "name": "kitchen_printer",
    "title": "پرینتر آشپزخانه",
    "options": "{\"paper_size\":\"A4\",\"quality\":\"high\",\"orientation\":\"portrait\",\"copies\":1}",
    "status": "active",
    "type": "qz",
    "created_at": "2024-01-15T11:00:00.000000Z",
    "updated_at": "2024-01-15T11:00:00.000000Z",
    "deleted_at": null
  },
  "message": "تنظیمات پرینتر با موفقیت ایجاد شد"
}
```

#### Error Response (400)
```json
{
  "error": "شعبه الزامی است"
}
```

---

### 4. Update Printer Setting

**PUT** `/printer-settings/update`

Update an existing printer setting.

#### Request Body
```json
{
  "printer_setting_id": 1,
  "branch_id": 1,
  "name": "updated_printer",
  "title": "پرینتر بروزرسانی شده",
  "options": "{\"paper_size\":\"A5\",\"quality\":\"medium\",\"orientation\":\"landscape\"}",
  "status": "active",
  "type": "app"
}
```

#### Field Validation
Same as create endpoint, plus:
| Field | Rules | Error Message |
|-------|-------|---------------|
| `printer_setting_id` | required, numeric, exists:printer_setting,id | شناسه تنظیمات پرینتر الزامی است / تنظیمات پرینتر یافت نشد |

#### Example Request
```bash
PUT /api/v1/admin/printer-settings/update
Content-Type: application/json
Authorization: Bearer {your_token}

{
  "printer_setting_id": 1,
  "branch_id": 1,
  "name": "main_printer_v2",
  "title": "پرینتر اصلی نسخه 2",
  "options": "{\"paper_size\":\"A4\",\"quality\":\"high\",\"orientation\":\"portrait\",\"auto_cut\":true}",
  "status": "active",
  "type": "app"
}
```

#### Success Response (200)
```json
{
  "data": {
    "id": 1,
    "branch_id": 1,
    "name": "main_printer_v2",
    "title": "پرینتر اصلی نسخه 2",
    "options": "{\"paper_size\":\"A4\",\"quality\":\"high\",\"orientation\":\"portrait\",\"auto_cut\":true}",
    "status": "active",
    "type": "app",
    "created_at": "2024-01-15T10:30:00.000000Z",
    "updated_at": "2024-01-15T12:00:00.000000Z",
    "deleted_at": null,
    "branch": {
      "id": 1,
      "title": "شعبه مرکزی"
    }
  },
  "message": "تنظیمات پرینتر با موفقیت بروزرسانی شد"
}
```

---

### 5. Delete Printer Setting

**DELETE** `/printer-settings/destroy`

Soft delete a printer setting.

#### Query Parameters
| Parameter | Type | Description | Required |
|-----------|------|-------------|----------|
| `printer_setting_id` | integer | Printer setting ID | Yes |

#### Example Request
```bash
DELETE /api/v1/admin/printer-settings/destroy?printer_setting_id=1
Authorization: Bearer {your_token}
```

#### Success Response (200)
```json
{
  "message": "تنظیمات پرینتر با موفقیت حذف شد"
}
```

#### Error Response (400)
```json
{
  "error": "شناسه تنظیمات پرینتر الزامی است"
}
```

---

### 6. Get Settings by Branch

**GET** `/printer-settings/by-branch`

Get all active printer settings for a specific branch.

#### Query Parameters
| Parameter | Type | Description | Required |
|-----------|------|-------------|----------|
| `branch_id` | integer | Branch ID | Yes |

#### Example Request
```bash
GET /api/v1/admin/printer-settings/by-branch?branch_id=1
```

#### Response
```json
{
  "data": [
    {
      "id": 1,
      "branch_id": 1,
      "name": "main_printer",
      "title": "پرینتر اصلی",
      "options": "{\"paper_size\":\"A4\",\"quality\":\"high\"}",
      "status": "active",
      "type": "app",
      "created_at": "2024-01-15T10:30:00.000000Z",
      "updated_at": "2024-01-15T10:30:00.000000Z",
      "deleted_at": null
    },
    {
      "id": 2,
      "branch_id": 1,
      "name": "kitchen_printer",
      "title": "پرینتر آشپزخانه",
      "options": "{\"paper_size\":\"A4\",\"quality\":\"high\"}",
      "status": "active",
      "type": "qz",
      "created_at": "2024-01-15T11:00:00.000000Z",
      "updated_at": "2024-01-15T11:00:00.000000Z",
      "deleted_at": null
    }
  ]
}
```

---

### 7. Get Settings by Type

**GET** `/printer-settings/by-type`

Get all active printer settings by type, optionally filtered by branch.

#### Query Parameters
| Parameter | Type | Description | Required |
|-----------|------|-------------|----------|
| `type` | string | Printer type: "app" or "qz" | Yes |
| `branch_id` | integer | Branch ID (optional) | No |

#### Example Request
```bash
GET /api/v1/admin/printer-settings/by-type?type=app&branch_id=1
```

#### Response
```json
{
  "data": [
    {
      "id": 1,
      "branch_id": 1,
      "name": "main_printer",
      "title": "پرینتر اصلی",
      "options": "{\"paper_size\":\"A4\",\"quality\":\"high\"}",
      "status": "active",
      "type": "app",
      "created_at": "2024-01-15T10:30:00.000000Z",
      "updated_at": "2024-01-15T10:30:00.000000Z",
      "deleted_at": null
    }
  ]
}
```

---

## Error Handling

### Common Error Responses

#### 400 Bad Request
```json
{
  "error": "نام الزامی است"
}
```

#### 401 Unauthorized
```json
{
  "message": "Unauthenticated."
}
```

#### 404 Not Found
```json
{
  "message": "تنظیمات پرینتر یافت نشد"
}
```

#### 422 Validation Error
```json
{
  "error": "فرمت JSON تنظیمات نامعتبر است"
}
```

#### 500 Internal Server Error
```json
{
  "message": "خطا در دریافت تنظیمات پرینتر"
}
```

---

## Frontend Integration Examples

### JavaScript/Axios Examples

#### Get All Printer Settings
```javascript
const getPrinterSettings = async (filters = {}) => {
  try {
    const params = new URLSearchParams(filters);
    const response = await axios.get(`/api/v1/admin/printer-settings/?${params}`, {
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    });
    return response.data;
  } catch (error) {
    console.error('Error fetching printer settings:', error.response.data);
    throw error;
  }
};
```

#### Create Printer Setting
```javascript
const createPrinterSetting = async (data) => {
  try {
    const response = await axios.post('/api/v1/admin/printer-settings/store', data, {
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    });
    return response.data;
  } catch (error) {
    console.error('Error creating printer setting:', error.response.data);
    throw error;
  }
};
```

#### Update Printer Setting
```javascript
const updatePrinterSetting = async (id, data) => {
  try {
    const response = await axios.put('/api/v1/admin/printer-settings/update', {
      printer_setting_id: id,
      ...data
    }, {
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    });
    return response.data;
  } catch (error) {
    console.error('Error updating printer setting:', error.response.data);
    throw error;
  }
};
```

#### Delete Printer Setting
```javascript
const deletePrinterSetting = async (id) => {
  try {
    const response = await axios.delete(`/api/v1/admin/printer-settings/destroy?printer_setting_id=${id}`, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
    return response.data;
  } catch (error) {
    console.error('Error deleting printer setting:', error.response.data);
    throw error;
  }
};
```

### React Hook Example
```javascript
import { useState, useEffect } from 'react';
import axios from 'axios';

const usePrinterSettings = () => {
  const [printerSettings, setPrinterSettings] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  const fetchPrinterSettings = async (filters = {}) => {
    setLoading(true);
    setError(null);
    try {
      const params = new URLSearchParams(filters);
      const response = await axios.get(`/api/v1/admin/printer-settings/?${params}`);
      setPrinterSettings(response.data.data);
    } catch (err) {
      setError(err.response?.data?.error || 'خطا در دریافت داده‌ها');
    } finally {
      setLoading(false);
    }
  };

  const createPrinterSetting = async (data) => {
    try {
      const response = await axios.post('/api/v1/admin/printer-settings/store', data);
      setPrinterSettings(prev => [response.data.data, ...prev]);
      return response.data;
    } catch (err) {
      throw new Error(err.response?.data?.error || 'خطا در ایجاد تنظیمات');
    }
  };

  const updatePrinterSetting = async (id, data) => {
    try {
      const response = await axios.put('/api/v1/admin/printer-settings/update', {
        printer_setting_id: id,
        ...data
      });
      setPrinterSettings(prev => 
        prev.map(item => item.id === id ? response.data.data : item)
      );
      return response.data;
    } catch (err) {
      throw new Error(err.response?.data?.error || 'خطا در بروزرسانی تنظیمات');
    }
  };

  const deletePrinterSetting = async (id) => {
    try {
      await axios.delete(`/api/v1/admin/printer-settings/destroy?printer_setting_id=${id}`);
      setPrinterSettings(prev => prev.filter(item => item.id !== id));
    } catch (err) {
      throw new Error(err.response?.data?.error || 'خطا در حذف تنظیمات');
    }
  };

  return {
    printerSettings,
    loading,
    error,
    fetchPrinterSettings,
    createPrinterSetting,
    updatePrinterSetting,
    deletePrinterSetting
  };
};

export default usePrinterSettings;
```

---

## Notes

1. **JSON Options Field**: The `options` field must be a valid JSON string. Parse it on the frontend to display configuration options.

2. **Pagination**: The list endpoint returns paginated results with 25 items per page by default.

3. **Soft Delete**: Deleted items are soft-deleted and won't appear in list results.

4. **Branch Relationship**: The `branch` object is automatically included in responses.

5. **Error Messages**: All error messages are in Persian as per the application's localization.

6. **Authentication**: All endpoints require valid authentication token.

7. **Rate Limiting**: API calls are rate-limited to 500 requests per minute.

---

## Support

For technical support or questions about this API, please contact the backend development team.
