<?php

namespace App\Controllers;

use App\Core\Controller;
use App\Services\ApkService;

class ApkController extends Controller {
    protected $apkService;

    public function __construct() {
        $this->apkService = new ApkService();
    }

    public function detail($params) {
        $apk = $this->apkService->getBySlug($params['slug']);
        if (!$apk) {
            header("HTTP/1.0 404 Not Found");
            $this->view("404");
            return;
        }

        $siteName = get_setting('site_name', 'ApkNusa');
        return $this->view('apk_detail', [
            'apk' => $apk,
            'title' => sprintf(__('apk_detail_title'), $apk['title'], $apk['version'], $siteName)
        ]);
    }

    public function download($params) {
        $apk = $this->apkService->getBySlug($params['slug']);
        
        if (!$apk) {
            header("HTTP/1.0 404 Not Found");
            $this->view("404");
            return;
        }

        // Increment download counter
        $this->apkService->incrementDownload($apk['id']);
        
        // Get the download URL
        $downloadUrl = $apk['download_url'];
        
        // If URL is empty or #, redirect back to detail with a message
        if (empty($downloadUrl) || $downloadUrl === '#') {
            $this->redirect('/apk/' . $apk['slug'] . '?error=no_url');
            return;
        }

        // Redirect to the actual download link (External URL)
        $this->redirect($downloadUrl);
    }
}