# 📍 Sitemap System - Hướng Dẫn Sử Dụng

Hệ thống sitemap tự động cho website đọc truyện với khả năng tự động cập nhật và tối ưu SEO.

---

## 🚀 Tính Năng

### 1. **Sitemap Động (Dynamic Sitemap)**
- Tự động generate sitemap theo thời gian thực
- Cache 1 giờ để tối ưu performance
- Hỗ trợ phân trang cho chapters (10,000 chapters/page)

### 2. **Sitemap Tĩnh (Static Sitemap)**
- Generate file XML tĩnh để phục vụ nhanh hơn
- Lưu trong storage/public/sitemaps/
- Tự động copy sitemap.xml vào thư mục public

### 3. **Tự Động Cập Nhật**
- Scheduled task chạy mỗi ngày lúc 3:00 AM
- Tự động clear cache và regenerate
- Logging success/failure

---

## 📂 Cấu Trúc Sitemap

### Sitemap Index (Chính)
**URL**: `http://yoursite.com/sitemap.xml`

Sitemap index bao gồm các sub-sitemaps:
- `/sitemap/static` - Trang tĩnh (Home, Search, List)
- `/sitemap/comics` - Tất cả comics (24,753+ truyện)
- `/sitemap/chapters` - Tất cả chapters (618K+ chapters, phân trang)
- `/sitemap/categories` - Tất cả thể loại
- `/sitemap/authors` - Tất cả tác giả

### Sub-Sitemaps

#### 1. Static Pages Sitemap
```xml
<url>
  <loc>http://yoursite.com/</loc>
  <changefreq>daily</changefreq>
  <priority>1.0</priority>
</url>
```

#### 2. Comics Sitemap
```xml
<url>
  <loc>http://yoursite.com/danh-sach-tap-truyen/truyen-abc</loc>
  <changefreq>weekly</changefreq>
  <priority>0.8</priority>
  <lastmod>2025-12-23T10:00:00+00:00</lastmod>
</url>
```

#### 3. Chapters Sitemap (Paginated)
```xml
<url>
  <loc>http://yoursite.com/doc-truyen/chuong-1</loc>
  <changefreq>monthly</changefreq>
  <priority>0.6</priority>
  <lastmod>2025-12-23T10:00:00+00:00</lastmod>
</url>
```

---

## 🛠️ Cách Sử Dụng

### 1. **Generate Sitemap Thủ Công**

#### Generate Dynamic Sitemap (Recommended cho lần đầu)
```bash
php artisan sitemap:generate
```

#### Generate với clear cache
```bash
php artisan sitemap:generate --clear-cache
```

#### Generate vào storage disk cụ thể
```bash
php artisan sitemap:generate --storage=local
```

**Output**:
```
Starting sitemap generation...
Generating sitemap index...
✓ sitemap.xml
Generating static pages sitemap...
✓ sitemap-static.xml
Generating comics sitemap...
✓ sitemap-comics.xml
Generating categories sitemap...
✓ sitemap-categories.xml
Generating authors sitemap...
✓ sitemap-authors.xml
Generating chapters sitemaps...
[████████████████████████] 100%
✓ 62 chapter sitemap(s) generated
✓ Copied sitemap.xml to public directory
✓ Sitemap generation completed successfully!
Access your sitemap at: http://yoursite.com/sitemap.xml
```

### 2. **Truy Cập Sitemap qua Web**

#### Dynamic Sitemap (Real-time)
- Main Index: `http://yoursite.com/sitemap.xml`
- Static: `http://yoursite.com/sitemap/static`
- Comics: `http://yoursite.com/sitemap/comics`
- Chapters: `http://yoursite.com/sitemap/chapters?page=1`
- Categories: `http://yoursite.com/sitemap/categories`
- Authors: `http://yoursite.com/sitemap/authors`

### 3. **Tự Động Cập Nhật**

Sitemap sẽ tự động regenerate **mỗi ngày lúc 3:00 AM**.

Để kích hoạt scheduler, thêm vào crontab:
```bash
crontab -e
```

Thêm dòng:
```
* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1
```

Hoặc chạy queue worker:
```bash
php artisan schedule:work
```

### 4. **Clear Cache Sitemap**

Cache sitemap có thể clear bằng cách:

#### Option 1: Regenerate với --clear-cache
```bash
php artisan sitemap:generate --clear-cache
```

#### Option 2: Clear cache Laravel
```bash
php artisan cache:forget sitemap_comics
php artisan cache:forget sitemap_categories
php artisan cache:forget sitemap_authors
php artisan cache:forget comics_last_modified
php artisan cache:forget chapters_last_modified
```

---

## 📊 Performance

### Caching Strategy
- **Comics Sitemap**: Cache 1 giờ
- **Categories Sitemap**: Cache 1 giờ
- **Authors Sitemap**: Cache 1 giờ
- **Chapters Sitemap**: Cache 1 giờ (per page)
- **Last Modified Dates**: Cache 5 phút

### Pagination
- Chapters được phân trang: **10,000 chapters/sitemap**
- Với 618K chapters → ~62 sitemap files
- Giảm memory usage và tăng tốc độ load

### HTTP Headers
- `Content-Type: application/xml`
- `Cache-Control: public, max-age=3600` (1 giờ)
- `Cache-Control: public, max-age=86400` (24 giờ cho static pages)

---

## 🔍 Submit Sitemap đến Google

### 1. Google Search Console
1. Truy cập: https://search.google.com/search-console
2. Chọn property của bạn
3. Vào **Sitemaps** (bên trái)
4. Nhập: `sitemap.xml`
5. Click **SUBMIT**

### 2. Bing Webmaster Tools
1. Truy cập: https://www.bing.com/webmasters
2. Vào **Sitemaps**
3. Nhập: `http://yoursite.com/sitemap.xml`
4. Click **Submit**

### 3. robots.txt
File `public/robots.txt` đã được cấu hình với sitemap URL:
```
Sitemap: http://yoursite.com/sitemap.xml
```

---

## 🧪 Testing

### 1. Kiểm Tra Sitemap XML Format
```bash
curl http://yoursite.com/sitemap.xml | xmllint --format -
```

### 2. Validate với Google
- Truy cập: https://search.google.com/test/rich-results
- Paste URL sitemap
- Click **Test URL**

### 3. Validate với Schema.org
- Truy cập: https://validator.schema.org/
- Paste sitemap XML
- Check for errors

### 4. Check Sitemap Size
```bash
# Check file size
ls -lh public/sitemap.xml

# Check number of URLs
curl http://yoursite.com/sitemap.xml | grep -c "<loc>"
```

---

## 📝 Files Created

### Controllers
- `app/Http/Controllers/SitemapController.php`

### Services
- `app/Services/SitemapService.php`

### Commands
- `app/Console/Commands/GenerateSitemap.php`

### Routes
- `routes/web.php` (sitemap routes added)
- `routes/console.php` (scheduled task added)

### Config
- `public/robots.txt` (updated)

---

## ⚙️ Customization

### Thay Đổi Thời Gian Scheduled Task

Edit `routes/console.php`:
```php
// Mỗi ngày lúc 3 AM
Schedule::command('sitemap:generate --clear-cache')
    ->dailyAt('03:00');

// Mỗi 6 giờ
Schedule::command('sitemap:generate --clear-cache')
    ->everySixHours();

// Mỗi tuần Chủ nhật lúc 2 AM
Schedule::command('sitemap:generate --clear-cache')
    ->weekly()
    ->sundays()
    ->at('02:00');
```

### Thay Đổi Cache Time

Edit `app/Services/SitemapService.php`:
```php
// Từ 1 giờ (3600s) → 2 giờ (7200s)
Cache::remember('sitemap_comics', 7200, function () {
    // ...
});
```

### Thay Đổi Pagination Size

Edit `app/Services/SitemapService.php`:
```php
// Từ 10,000 → 5,000 chapters per sitemap
public function generateChaptersSitemap(int $page = 1, int $perPage = 5000)
```

### Thêm Sitemap Mới

1. Thêm method trong `SitemapService.php`:
```php
public function generateNewSitemap(): string
{
    $urls = [
        [
            'loc' => route('new.page'),
            'changefreq' => 'daily',
            'priority' => '0.8',
        ],
    ];

    return $this->buildUrlSet($urls);
}
```

2. Thêm route trong `routes/web.php`:
```php
Route::get('/sitemap/new', [SitemapController::class, 'new'])->name('sitemap.new');
```

3. Thêm controller method trong `SitemapController.php`:
```php
public function new(): Response
{
    $xml = $this->sitemapService->generateNewSitemap();
    return response($xml, 200)->header('Content-Type', 'application/xml');
}
```

4. Update sitemap index trong `SitemapService::generateSitemapIndex()`:
```php
[
    'loc' => route('sitemap.new'),
    'lastmod' => now()->toAtomString(),
],
```

---

## 🐛 Troubleshooting

### Issue: Sitemap không hiển thị
**Solution**:
```bash
# Check route list
php artisan route:list | grep sitemap

# Check file permissions
ls -la public/sitemap.xml

# Regenerate
php artisan sitemap:generate --clear-cache
```

### Issue: Memory limit exceeded
**Solution**:
```bash
# Increase memory limit temporarily
php -d memory_limit=512M artisan sitemap:generate

# Or update php.ini
memory_limit = 512M
```

### Issue: Scheduled task không chạy
**Solution**:
```bash
# Test manually
php artisan schedule:run

# Check schedule list
php artisan schedule:list

# Check crontab
crontab -l
```

### Issue: Cache không clear
**Solution**:
```bash
# Clear all cache
php artisan cache:clear

# Clear specific sitemap caches
php artisan sitemap:generate --clear-cache
```

---

## 📈 SEO Benefits

### 1. **Faster Indexing**
- Google bot tìm thấy tất cả pages nhanh hơn
- Chapters mới được index trong vòng 24-48 giờ

### 2. **Better Crawl Efficiency**
- Sitemap giúp Google ưu tiên crawl pages quan trọng
- Giảm crawl budget waste

### 3. **Rich Results**
- Kết hợp với structured data đã implement
- Có thể hiển thị rich snippets trong SERP

### 4. **Mobile-First Indexing**
- Sitemap hỗ trợ mobile crawling
- Tối ưu cho mobile search results

---

## 📚 Resources

- [Google Sitemap Protocol](https://www.sitemaps.org/protocol.html)
- [Google Search Central - Sitemaps](https://developers.google.com/search/docs/advanced/sitemaps/overview)
- [Laravel Task Scheduling](https://laravel.com/docs/11.x/scheduling)
- [Schema.org Documentation](https://schema.org/)

---

## ✅ Checklist After Implementation

- [ ] Run `php artisan sitemap:generate` lần đầu
- [ ] Verify sitemap at `http://yoursite.com/sitemap.xml`
- [ ] Setup crontab cho scheduled task
- [ ] Submit sitemap to Google Search Console
- [ ] Submit sitemap to Bing Webmaster Tools
- [ ] Verify robots.txt có sitemap URL
- [ ] Test với Google Rich Results Test
- [ ] Monitor trong Search Console (1-2 tuần)
- [ ] Update domain trong `robots.txt` từ localhost sang production

---

🎉 **Hoàn tất!** Sitemap system đã sẵn sàng tự động cập nhật và tối ưu SEO cho website của bạn!
