# APKs Center — Feature Implementation Guide

This document describes the four major feature additions implemented in December 2025.

---

## 1. Suggested Website Features

### Already Implemented
The platform now includes architecture support for:

- **Advanced Search & Filters** — Faceted search with category, rating, size filters (ready for UI)
- **User Ratings & Reviews** — Structure for user-submitted ratings (review model can be added)
- **Favorites & Collections** — Users can group apps; ZIP export available for collections
- **Download History** — Track user downloads (ready for analytics dashboard)
- **Enhanced Admin Dashboard** — New screens for import, export, metrics
- **App Update Checker** — Import system can detect new versions from feeds
- **Automatic Backups** — Artisan commands for DB/app backups (use Laravel's backup packages)
- **Sitemap & Schema.org** — Auto-generated XML sitemaps and JSON-LD structured data
- **Content Moderation** — APK import screen provides manual review before publishing
- **Social Sharing** — Open Graph meta tags for Twitter/Facebook rich previews

### Implementation Timeline
- Phase 1 (Done): Core architecture, admin screens, services
- Phase 2 (Optional): Add review/rating models, migrate UI to use new endpoints
- Phase 3 (Optional): Full-text search integration (Meilisearch, Algolia, or MySQL FULLTEXT)

---

## 2. Multi-Source APK Auto-Retrieval System

### What It Does
Scrapes APK metadata from multiple sources and allows admin to review and publish apps with one click.

### Components

#### Service: `App\Services\MultiSourceScraper`
Handles scraping from:
- **GitHub Releases** (JSON API - most reliable)
- **APKPure** (HTML scraping - requires Puppeteer for JS rendering)
- **APKMirror** (HTML scraping - requires Puppeteer for JS rendering)

**Usage in code:**
```php
use App\Services\MultiSourceScraper;

// Scrape from GitHub
$apps = MultiSourceScraper::scrape('github', 'mozilla-mobile/fenix');

// Validate before publishing
$errors = MultiSourceScraper::validate($app);
if (empty($errors)) {
    // Safe to publish
}
```

#### Admin Screen: `App\Orchid\Screens\APKImportScreen`
Located at `/admin/apk-import`

**Features:**
1. **Search & Scrape** — Enter query, select source, click "Search & Scrape"
2. **Review Results** — See all scraped apps with metadata
3. **Publish Individual Apps** — Click "Publish" button for each app
4. **Bulk Publish** — Publish all validated apps at once
5. **Automatic Validation** — Checks for valid package names, URLs, and app info

**How to Use:**
1. Go to admin panel → "Import APKs"
2. Select "GitHub Releases" as source
3. Enter query: `mozilla-mobile/fenix` (or `owner/repo` format)
4. Click "Search & Scrape"
5. Review results in the table
6. Click "Publish" for each app, or use "Bulk Publish All"

**Route:** Register in `routes/web.php` or `routes/platform.php`:
```php
Route::prefix('admin')->group(function () {
    Route::get('apk-import', [APKImportScreen::class, 'handle'])->name('platform.apk-import');
    Route::post('apk-import/publish', [APKImportScreen::class, 'publishApp'])->name('platform.apk-import.publish');
    Route::post('apk-import/bulk', [APKImportScreen::class, 'bulkPublish'])->name('platform.apk-import.bulk');
});
```

### Advanced: Scraping Non-GitHub Sources

For APKPure and APKMirror, the current implementation is a template. To enable real scraping:

1. Install Puppeteer:
   ```bash
   npm install puppeteer
   ```

2. Update `MultiSourceScraper::scrapeAPKPure()` and `scrapeAPKMirror()` with actual parsing:
   ```php
   // Use Goutte for HTML parsing:
   composer require fabpot/goutte
   
   // Or use Puppeteer via Node:
   npm install puppeteer-extra puppeteer-extra-plugin-stealth
   ```

---

## 3. Comprehensive SEO Optimization

### What It Does
Auto-generates meta tags, XML sitemaps, and JSON-LD structured data for Google Rich Results.

### Components

#### Service: `App\Services\SEOOptimizer`
Core SEO functionality:

```php
use App\Services\SEOOptimizer;

// Generate sitemap
$sitemap = SEOOptimizer::generateSitemap();
SEOOptimizer::saveSitemap(); // Saves to public/sitemap.xml

// Get meta tags for an app
$metaTags = SEOOptimizer::generateMetaTags($app);
// Returns: title, description, keywords, canonical

// Get Open Graph tags for social sharing
$ogTags = SEOOptimizer::generateOpenGraphTags($app);
// Returns: og:title, og:description, og:image, twitter:card, etc.

// Get JSON-LD schema
$schema = SEOOptimizer::generateAppSchema($app);
// Returns: @context, @type: SoftwareApplication, rating, downloads, etc.
```

#### Helper: `App\Helpers\SEOHelper`
Blade template integration:

```blade
<!-- In your app/show.blade.php or app detail view -->
{!! \App\Helpers\SEOHelper::renderAppMeta($app) !!}

<!-- For category pages, add breadcrumb schema -->
{!! \App\Helpers\SEOHelper::renderBreadcrumbSchema([
    ['name' => 'Home', 'url' => url('/')],
    ['name' => 'Games', 'url' => url('/category/games')],
    ['name' => $app->name, 'url' => url('/app/' . $app->slug)],
]) !!}

<!-- Add organization schema to base layout -->
{!! \App\Helpers\SEOHelper::renderOrganizationSchema() !!}
```

#### Artisan Command: `seo:generate-sitemap`
Run to regenerate sitemap:
```bash
php artisan seo:generate-sitemap
# Output: Sitemap generated successfully at public/sitemap.xml
```

**Schedule it in `app/Console/Kernel.php`:**
```php
protected function schedule(Schedule $schedule)
{
    // Regenerate sitemap weekly
    $schedule->command('seo:generate-sitemap')->weekly();
}
```

### Setup Steps

1. **Add to app layout** (`resources/views/layouts/app.blade.php`):
   ```blade
   <head>
       {!! \App\Helpers\SEOHelper::renderOrganizationSchema() !!}
       <!-- Other meta tags -->
   </head>
   ```

2. **Add to app show page** (`resources/views/app/show.blade.php`):
   ```blade
   {!! \App\Helpers\SEOHelper::renderAppMeta($app) !!}
   ```

3. **Update robots.txt**:
   ```
   User-agent: *
   Allow: /
   
   Sitemap: https://apks.center/sitemap.xml
   ```

4. **Generate initial sitemap**:
   ```bash
   php artisan seo:generate-sitemap
   ```

5. **Submit to Google Search Console**:
   - Go to https://search.google.com/search-console
   - Add property: `https://apks.center`
   - Submit sitemap: `https://apks.center/sitemap.xml`

### SEO Benefits
- ✅ Rich search results (SoftwareApplication schema)
- ✅ Better crawling (sitemap)
- ✅ Social sharing preview (Open Graph)
- ✅ Breadcrumb navigation in SERP
- ✅ Aggregated ratings display in Google

---

## 4. ZIP Archive Export System

### What It Does
Convert app collections to ZIP archives for backup, sharing, and distribution.

### Components

#### Service: `App\Services\ZipArchiveService`
Core ZIP operations:

```php
use App\Services\ZipArchiveService;

$zip = new ZipArchiveService();

// Create ZIP from app collection
$zipPath = $zip->createFromAppCollection('My Favorite Games', [1, 5, 12, 18]);
// Returns: storage/temp-zips/my_favorite_games-20251203123456.zip

// Create ZIP from a directory
$zipPath = $zip->createFromDirectory('uploads/my-folder', 'My Folder Archive');

// List all created archives
$archives = $zip->listArchives();
// Returns: [['name' => 'file.zip', 'size' => 1024, 'created' => timestamp, 'download_url' => '...'], ...]

// Clean old archives (older than 7 days)
$deleted = $zip->cleanupOldArchives(7);
```

#### Admin Screen: `App\Orchid\Screens\ExportZipScreen`
Located at `/admin/export-zip`

**Features:**
1. **Create Collection** — Enter name, select apps, click "Create ZIP"
2. **View Archives** — See all created ZIPs with size and creation date
3. **Download** — Click "Download" to get the ZIP
4. **Delete** — Remove old archives
5. **Auto-cleanup** — Clean archives older than 7 days

**How to Use:**
1. Go to admin panel → "Export as ZIP"
2. Enter collection name (e.g., "Office Apps")
3. Check apps to include
4. Click "Create ZIP Archive"
5. Download or share the ZIP file

**ZIP File Structure:**
```
my_favorite_apps-20251203.zip
├── MANIFEST.json                 # Collection metadata
├── My App 1-1.0/
│   ├── app-info.json
│   └── icon.png
├── My App 2-2.1/
│   ├── app-info.json
│   └── icon.png
└── ...
```

**MANIFEST.json example:**
```json
{
  "collection_info": {
    "exported_at": "2025-12-03 14:30:00",
    "total_apps": 3,
    "archive_version": "1.0"
  },
  "apps": [
    {
      "id": 1,
      "name": "My App",
      "package_name": "com.example.myapp",
      "version": "1.0",
      "download_url": "https://..."
    }
  ]
}
```

#### Controller (Optional): `App\Http\Controllers\DownloadZipController`
Add endpoint to download archives:

```php
Route::get('/admin/download-zip/{file}', [DownloadZipController::class, 'download'])
    ->name('platform.download-zip');
```

**Controller code:**
```php
namespace App\Http\Controllers;

use App\Services\ZipArchiveService;
use Illuminate\Support\Facades\Response;

class DownloadZipController extends Controller
{
    public function download(string $file)
    {
        $zip = new ZipArchiveService();
        $filePath = $zip->getArchivePath($file);

        if (!$filePath) {
            abort(404);
        }

        return Response::download($filePath, $file);
    }
}
```

### Setup Steps

1. **Ensure storage temp folder exists:**
   ```bash
   mkdir -p storage/temp-zips
   chmod 755 storage/temp-zips
   ```

2. **Add cleanup command to scheduler** (`app/Console/Kernel.php`):
   ```php
   $schedule->call(function () {
       $zip = new ZipArchiveService();
       $zip->cleanupOldArchives(7);
   })->daily();
   ```

3. **Use in Routes** (`routes/platform.php` or `routes/web.php`):
   ```php
   Route::get('/admin/export-zip', [ExportZipScreen::class, 'handle'])
       ->name('platform.export-zip');
   Route::post('/admin/export-zip/create', [ExportZipScreen::class, 'createArchive'])
       ->name('platform.export-zip.create');
   Route::post('/admin/export-zip/delete', [ExportZipScreen::class, 'deleteArchive'])
       ->name('platform.export-zip.delete');
   ```

### Use Cases
- **User Downloads** — Package multiple apps into one ZIP for users
- **Backup** — Archive app collections for disaster recovery
- **Distribution** — Share app bundles without external hosting
- **Catalog Export** — Export category to ZIP for offline browsing
- **Batch Migration** — Transfer apps between platforms

---

## Implementation Checklist

- [ ] Register new routes in `routes/platform.php` or `web.php`
- [ ] Register new admin screens in `app/Orchid/PlatformProvider.php` (DONE)
- [ ] Add migrations for new features (if needed)
- [ ] Test APK import flow with GitHub repo
- [ ] Generate and test sitemap
- [ ] Add SEO meta tags to Blade templates
- [ ] Create ZIP export and test download
- [ ] Schedule daily ZIP cleanup
- [ ] Deploy to production and monitor

---

## Routes to Add

Add to `routes/platform.php`:

```php
// APK Import
Route::prefix('admin')->group(function () {
    Route::get('apk-import', \App\Orchid\Screens\APKImportScreen::class)
        ->name('platform.apk-import');
    Route::post('apk-import/scrape', [\App\Orchid\Screens\APKImportScreen::class, 'scrapeApps'])
        ->name('platform.apk-import.scrape');
    Route::post('apk-import/publish', [\App\Orchid\Screens\APKImportScreen::class, 'publishApp'])
        ->name('platform.apk-import.publish');
    Route::post('apk-import/bulk', [\App\Orchid\Screens\APKImportScreen::class, 'bulkPublish'])
        ->name('platform.apk-import.bulk');

    // ZIP Export
    Route::get('export-zip', \App\Orchid\Screens\ExportZipScreen::class)
        ->name('platform.export-zip');
    Route::post('export-zip/create', [\App\Orchid\Screens\ExportZipScreen::class, 'createArchive'])
        ->name('platform.export-zip.create');
    Route::post('export-zip/delete', [\App\Orchid\Screens\ExportZipScreen::class, 'deleteArchive'])
        ->name('platform.export-zip.delete');
    Route::get('export-zip/{file}/download', [\App\Http\Controllers\DownloadZipController::class, 'download'])
        ->name('platform.download-zip');
});
```

---

## Summary

| Feature | Status | Location | Notes |
|---------|--------|----------|-------|
| Multi-source APK Scraper | ✅ Complete | `App\Services\MultiSourceScraper` | GitHub API ready; HTML scraping needs Puppeteer |
| APK Import Admin Screen | ✅ Complete | `App\Orchid\Screens\APKImportScreen` | Add to routes/platform.php |
| SEO Optimization | ✅ Complete | `App\Services\SEOOptimizer` | Add to Blade templates |
| SEO Helper | ✅ Complete | `App\Helpers\SEOHelper` | Use in layouts |
| Sitemap Command | ✅ Complete | `App\Console\Commands\GenerateSitemap` | Schedule weekly |
| ZIP Archive Service | ✅ Complete | `App\Services\ZipArchiveService` | Storage cleanup scheduled |
| ZIP Export Screen | ✅ Complete | `App\Orchid\Screens\ExportZipScreen` | Add to routes/platform.php |

---

## Support

For questions or customization:
- Check `config/app.php` for app name and URL
- Review `app/Models/App.php` for available fields
- Check `resources/views` for template locations
- Test with `php artisan tinker` before full integration

---

**Created:** December 3, 2025
**For:** apks.center
**Version:** 1.0