# Hướng dẫn cài đặt Module UiBuilder

## ✅ Module đã được tạo hoàn chỉnh!

Module UiBuilder đã được scaffold đầy đủ theo yêu cầu và sẵn sàng sử dụng.

## 📦 Các bước tiếp theo

### 1. Chạy Migrations

Module đã được đăng ký trong `config/app.php`, bây giờ hãy chạy migrations để tạo các bảng cần thiết:

```bash
cd /var/www/html/lms_hocmai
php artisan migrate
```

Migrations sẽ tạo 2 bảng:
- `ui_templates` - Lưu trữ các template HTML/CSS
- `ui_configs` - Mapping giữa tenant/domain với template

### 2. Kiểm tra Routes

Xác nhận routes đã được load:

```bash
php artisan route:list --path=ui-builder
php artisan route:list --path=api/ui
```

### 3. Truy cập Admin Interface

Sau khi đăng nhập vào hệ thống, truy cập:

```
http://your-domain.com/admin/ui-builder
```

### 4. Clear Cache (nếu cần)

```bash
php artisan config:clear
php artisan route:clear
php artisan view:clear
php artisan cache:clear
```

## 🎯 Kiểm tra hoạt động

### Test tạo Template

1. Truy cập: `/admin/ui-builder/templates`
2. Click "Tạo Template mới"
3. Nhập thông tin test:
   - Component: `footer`
   - Tên: `Test Footer`
   - Slug: `test-footer`
   - HTML: 
   ```html
   <footer class="bg-gray-800 text-white p-4 text-center">
       <p>Copyright © 2025 Test Company</p>
   </footer>
   ```
   - CSS:
   ```css
   .bg-gray-800 { background-color: #1f2937; }
   .text-white { color: white; }
   .p-4 { padding: 1rem; }
   .text-center { text-align: center; }
   ```
4. Click "Preview" để xem responsive

### Test API

**Tạo config trước (qua admin interface), sau đó test API:**

```bash
# Test public API render endpoint
curl "http://your-domain.com/api/ui/footer?tenant_id=1&domain_id=1"
```

**Response mẫu:**
```json
{
    "success": true,
    "data": {
        "component": "footer",
        "template": {
            "id": 1,
            "name": "Test Footer",
            "html": "<footer>...</footer>",
            "css": ".bg-gray-800 { ... }"
        },
        "config": {
            "company": "Test Company"
        }
    }
}
```

## 🔐 Authentication

Module yêu cầu authentication cho:
- **Web Routes**: Middleware `auth` (đã config)
- **Admin API**: Middleware `auth:sanctum` (đã config)
- **Public API**: Không yêu cầu authentication

### Nếu chưa có authentication

Cần đảm bảo:
1. User đã đăng nhập
2. Session/token hợp lệ
3. Middleware `auth` và `auth:sanctum` hoạt động

## 📁 Cấu trúc Files đã tạo

```
✅ app/Modules/UiBuilder/
   ✅ Http/Controllers/
      ✅ Api/TemplateApiController.php
      ✅ Api/ConfigApiController.php
      ✅ Web/UiBuilderController.php
   ✅ Http/Requests/
      ✅ StoreTemplateRequest.php
      ✅ StoreConfigRequest.php
   ✅ Models/
      ✅ UiTemplate.php
      ✅ UiConfig.php
   ✅ Database/migrations/
      ✅ 2025_10_11_000001_create_ui_templates_table.php
      ✅ 2025_10_11_000002_create_ui_configs_table.php
   ✅ Providers/
      ✅ UiBuilderServiceProvider.php
   ✅ Resources/views/
      ✅ layouts/app.blade.php
      ✅ dashboard.blade.php
      ✅ templates/index.blade.php
      ✅ templates/form.blade.php
      ✅ templates/preview.blade.php
      ✅ configs/index.blade.php
      ✅ configs/form.blade.php
   ✅ Resources/assets/
      ✅ css/uibuilder.css
      ✅ js/uibuilder.js
   ✅ routes/
      ✅ api.php
      ✅ web.php
   ✅ vite.config.js
   ✅ README.md

✅ config/app.php (đã thêm UiBuilderServiceProvider)
✅ public/modules/uibuilder/
   ✅ css/uibuilder.css
   ✅ js/uibuilder.js
```

## 🎨 Frontend Integration (Next.js)

### Ví dụ fetch và render template

```javascript
// components/DynamicFooter.jsx
import { useEffect, useState } from 'react';

export default function DynamicFooter({ tenantId, domainId }) {
  const [footerData, setFooterData] = useState(null);

  useEffect(() => {
    async function fetchFooter() {
      try {
        const res = await fetch(
          `/api/ui/footer?tenant_id=${tenantId}&domain_id=${domainId}`
        );
        const { data } = await res.json();
        setFooterData(data);
      } catch (error) {
        console.error('Failed to fetch footer:', error);
      }
    }
    
    fetchFooter();
  }, [tenantId, domainId]);

  if (!footerData) return <div>Loading footer...</div>;

  return (
    <>
      <style dangerouslySetInnerHTML={{ __html: footerData.template.css }} />
      <div dangerouslySetInnerHTML={{ __html: footerData.template.html }} />
    </>
  );
}
```

## 🔧 Troubleshooting

### Lỗi "Class not found"
```bash
composer dump-autoload
```

### Routes không load
```bash
php artisan route:clear
php artisan config:clear
```

### Views không tìm thấy
Kiểm tra Service Provider đã được đăng ký trong `config/app.php`

### Assets không load
Kiểm tra:
1. Files có trong `public/modules/uibuilder/`
2. Permissions: `chmod -R 755 public/modules/`

## 📝 Next Steps

1. ✅ Chạy migrations
2. ✅ Test admin interface
3. ✅ Tạo template mẫu
4. ✅ Tạo config cho tenant/domain
5. ✅ Test API endpoints
6. ✅ Integrate với Next.js frontend

## 💡 Tips

- **Preview responsive** rất hữu ích để kiểm tra template trên các kích thước màn hình
- **Config JSON** có thể chứa bất kỳ data nào: text, links, colors, settings...
- **Slug phải unique** trong mỗi component
- **Một tenant+domain+component** chỉ có thể có 1 config duy nhất

## 🚀 Module đã sẵn sàng!

Hãy chạy migrations và bắt đầu sử dụng module UiBuilder!

```bash
php artisan migrate
```

Sau đó truy cập: `http://your-domain.com/admin/ui-builder`

