# Setting Module Documentation

## Overview

The Setting module is designed to store website configuration data like website name, social media links, logos, and other site-wide settings. It follows the same flexible JSON-based structure as the Section module, allowing you to store any type of data with automatic image upload handling.

## Database Structure

The `settings` table has the following structure:

- `id`: Primary key
- `name`: Unique string identifier (e.g., "general", "social_media", "contact_info")
- `body`: JSON field that can store any data structure
- `added_by`: Foreign key to users table
- `updated_by`: Foreign key to users table
- `created_at`: Timestamp
- `updated_at`: Timestamp
- `deleted_at`: Soft delete timestamp

## API Endpoints

### Public Endpoints (No Authentication Required)

#### 1. List All Settings
```http
GET /api/settings
```

**Response:**
```json
{
    "success": true,
    "data": [
        {
            "id": 1,
            "name": "general",
            "body": {
                "website_name": "My Website",
                "tagline": "Your Success Partner",
                "logo_image": "http://localhost/storage/settings/abc123.png"
            },
            "added_by": {...},
            "updated_by": {...},
            "created_at": "2025-10-08T12:00:00.000000Z",
            "updated_at": "2025-10-08T12:00:00.000000Z"
        }
    ]
}
```

#### 2. Get Specific Setting by Name
```http
GET /api/settings/{name}
```

**Example:**
```http
GET /api/settings/general
```

**Response:**
```json
{
    "success": true,
    "data": {
        "id": 1,
        "name": "general",
        "body": {
            "website_name": "My Website",
            "tagline": "Your Success Partner",
            "logo_image": "http://localhost/storage/settings/abc123.png"
        },
        "added_by": {...},
        "updated_by": {...}
    }
}
```

### Authenticated Endpoints (Require Sanctum Token)

#### 3. Create or Update Setting
```http
POST /api/settings/{name}
Authorization: Bearer {token}
```

**Example 1: General Website Settings**
```http
POST /api/settings/general
Content-Type: application/json

{
    "website_name": "My Awesome Website",
    "tagline": "Building the Future",
    "description": "We are a leading company in innovation"
}
```

**Example 2: Social Media Links**
```http
POST /api/settings/social_media
Content-Type: application/json

{
    "facebook": "https://facebook.com/mypage",
    "twitter": "https://twitter.com/myhandle",
    "linkedin": "https://linkedin.com/company/mycompany",
    "instagram": "https://instagram.com/myprofile"
}
```

**Example 3: Contact Information**
```http
POST /api/settings/contact_info
Content-Type: application/json

{
    "email": "info@example.com",
    "phone": "+1234567890",
    "address": "123 Main Street, City, Country",
    "business_hours": "Mon-Fri: 9AM-5PM"
}
```

**Example 4: With Logo/Favicon Upload**
```http
POST /api/settings/branding
Content-Type: multipart/form-data

logo_image: [file]
favicon_image: [file]
brand_color: "#007bff"
secondary_color: "#6c757d"
```

**Response (201 Created or 200 Updated):**
```json
{
    "success": true,
    "message": "Setting 'general' created successfully",
    "data": {
        "id": 1,
        "name": "general",
        "body": {...},
        "added_by": {...},
        "updated_by": {...}
    }
}
```

#### 4. Delete Setting
```http
DELETE /api/settings/{name}
Authorization: Bearer {token}
```

**Example:**
```http
DELETE /api/settings/general
```

**Response:**
```json
{
    "success": true,
    "message": "Setting 'general' deleted successfully"
}
```

## Image Upload Features

The Setting module automatically handles image uploads:

### Single Images
Fields ending with `_image` are treated as single images:
- `logo_image`
- `favicon_image`
- `hero_image`
- `background_image`

**Example:**
```http
POST /api/settings/branding
Content-Type: multipart/form-data

logo_image: [file]
favicon_image: [file]
```

### Multiple Images
Fields ending with `_images` are treated as image arrays:
- `partner_images`
- `gallery_images`
- `social_images`

**Example:**
```http
POST /api/settings/partners
Content-Type: multipart/form-data

partner_images[0]: [file1]
partner_images[1]: [file2]
partner_images[2]: [file3]
```

### Base64 Image Support
You can also send base64 encoded images in the JSON body:

```json
{
    "logo_image": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUg..."
}
```

### Image URLs
When you retrieve settings, all image paths are automatically converted to full URLs:
```json
{
    "logo_image": "http://localhost/storage/settings/abc123.png"
}
```

## Common Use Cases

### 1. General Website Settings
```json
POST /api/settings/general
{
    "website_name": "My Company",
    "tagline": "Innovation at its best",
    "copyright": "© 2025 My Company. All rights reserved.",
    "enable_maintenance": false
}
```

### 2. Social Media Links
```json
POST /api/settings/social_media
{
    "facebook": "https://facebook.com/mypage",
    "twitter": "https://twitter.com/myhandle",
    "linkedin": "https://linkedin.com/company/mycompany",
    "instagram": "https://instagram.com/myprofile",
    "youtube": "https://youtube.com/mychannel"
}
```

### 3. Contact Information
```json
POST /api/settings/contact
{
    "email": "info@example.com",
    "phone": "+1234567890",
    "address": "123 Main St, City, Country",
    "map_coordinates": {
        "lat": 40.7128,
        "lng": -74.0060
    }
}
```

### 4. SEO Settings
```json
POST /api/settings/seo
{
    "meta_title": "My Company - Innovation Leader",
    "meta_description": "We provide innovative solutions...",
    "meta_keywords": "innovation, technology, solutions",
    "google_analytics_id": "UA-XXXXXXXXX-X",
    "google_tag_manager_id": "GTM-XXXXXXX"
}
```

### 5. Email Configuration
```json
POST /api/settings/email
{
    "smtp_host": "smtp.example.com",
    "smtp_port": "587",
    "smtp_username": "user@example.com",
    "from_email": "noreply@example.com",
    "from_name": "My Company"
}
```

## Features

### ✅ Flexible JSON Structure
Store any data structure in the body field - strings, numbers, objects, arrays, etc.

### ✅ Automatic Image Upload
Images are automatically uploaded to storage and paths converted to full URLs.

### ✅ Base64 Support
Send images as base64 strings for easy integration with frontend editors.

### ✅ Multiple Image Support
Upload multiple images at once with array fields.

### ✅ Automatic Cleanup
Old images are automatically deleted when updated or when setting is deleted.

### ✅ User Tracking
Automatically tracks who created and last updated each setting.

### ✅ Soft Deletes
Settings are soft deleted for data recovery.

### ✅ Public Read Access
Frontend can fetch settings without authentication.

### ✅ Authenticated Write
Only authenticated users can create/update/delete settings.

## Tips

1. **Organize by Purpose**: Create separate settings for different purposes (general, social_media, contact, seo, etc.)
2. **Use Descriptive Names**: Use clear names like "general", "social_media", "branding" for easy identification
3. **Image Fields**: Always use `_image` suffix for single images and `_images` for multiple images
4. **Keep It Structured**: Maintain consistent structure within each setting type
5. **Version Control**: Consider adding a "version" field to track configuration changes

## Example Frontend Integration

### Fetch General Settings
```javascript
// Get general website settings
const response = await fetch('http://localhost/api/settings/general');
const data = await response.json();

if (data.success) {
    document.title = data.data.body.website_name;
    // Use other settings...
}
```

### Update Settings (Authenticated)
```javascript
// Update social media links
const token = 'your-sanctum-token';
const response = await fetch('http://localhost/api/settings/social_media', {
    method: 'POST',
    headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    },
    body: JSON.stringify({
        facebook: 'https://facebook.com/newpage',
        twitter: 'https://twitter.com/newhandle'
    })
});
```

## Migration

To apply the database changes, run:
```bash
php artisan migrate:fresh
```

Or if you want to preserve existing data:
```bash
php artisan migrate:refresh --path=/database/migrations/2025_10_05_175554_create_settings_table.php
```

## Testing

You can test the setting module using curl:

```bash
# Get all settings
curl http://localhost/api/settings

# Get specific setting
curl http://localhost/api/settings/general

# Create/Update setting (requires authentication)
curl -X POST http://localhost/api/settings/general \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"website_name":"My Website","tagline":"Success Partner"}'
```
