<?php
/**
 * DownloadController — admin-facing page that manages the mobile install
 * links. Not public. Admin generates a link, sees the QR + copyable URL,
 * shares it with a driver via WhatsApp/SMS, and can revoke it any time.
 *
 *   /Download                — list of live + expired links
 *   /Download/generate       — POST, creates a new 7-day link
 *   /Download/view/{id}      — link details + list of drivers who installed
 *   /Download/revoke/{id}    — POST, revoke a link
 *   /Download/apkAdmin       — admin can download the APK directly (for their own testing)
 */
class DownloadController extends Controller
{
    public function indexAction()
    {
        $m = new AppInstallTokens();
        $this->view->setLayout($this->roleLayout());
        $this->view->render('Download/index', [
            'page_title' => 'App Downloads',
            'tokens'     => $m->listAll(50),
            'apk_meta'   => $m->apkMeta(),
        ]);
    }

    public function generateAction()
    {
        $this->verifyCsrf();
        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') { Router::redirect('Download'); return; }

        $label = trim((string)($_POST['label'] ?? ''));
        $days  = (int)($_POST['days'] ?? 7);
        if ($days < 1)  $days = 1;
        if ($days > 90) $days = 90;

        $m = new AppInstallTokens();
        $r = $m->generate($label, $days, $this->currentUserId(), $_SESSION['full_name'] ?? '');
        if (!$r['ok']) {
            $_SESSION['flash_tenant_msg']  = 'Could not create link.';
            $_SESSION['flash_tenant_type'] = 'danger';
            Router::redirect('Download'); return;
        }
        $_SESSION['flash_tenant_msg']  = 'New install link created (expires ' . humanDate($r['expires_on']) . ').';
        $_SESSION['flash_tenant_type'] = 'success';
        Router::redirect('Download/view/' . $r['id']);
    }

    public function viewAction($id = 0)
    {
        $m = new AppInstallTokens();
        $t = $m->byId((int)$id);
        if (!$t) { $this->notFound('Install link'); return; }
        $this->view->setLayout($this->roleLayout());
        $this->view->render('Download/view', [
            'page_title' => 'Install link',
            't'          => $t,
            'downloads'  => $m->downloadsFor((int)$id),
            'install_url'=> $this->buildInstallUrl($t['token']),
        ]);
    }

    public function revokeAction($id = 0)
    {
        $this->verifyCsrf();
        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') { Router::redirect('Download/view/' . (int)$id); return; }
        (new AppInstallTokens())->revoke((int)$id, $this->currentUserId());
        $_SESSION['flash_tenant_msg']  = 'Link revoked.';
        $_SESSION['flash_tenant_type'] = 'success';
        Router::redirect('Download/view/' . (int)$id);
    }

    /** Admin-only direct APK download (bypasses the driver-info gate). */
    public function apkAdminAction()
    {
        $m = new AppInstallTokens();
        $p = $m->apkPath();
        if (!$p) { $this->notFound('APK not yet built'); return; }
        $this->streamApk($p);
    }

    /* ── helpers ───────────────────────────────────────────────────── */

    private function buildInstallUrl(string $token): string
    {
        $scheme = (($_SERVER['HTTPS'] ?? '') === 'on') ? 'https' : 'http';
        $host   = $_SERVER['HTTP_HOST'] ?? 'localhost';
        return $scheme . '://' . $host . PROOT . 'Install/' . $token;
    }

    private function streamApk(string $path): void
    {
        if (ob_get_length()) ob_clean();
        header('Content-Type: application/vnd.android.package-archive');
        header('Content-Disposition: attachment; filename="pacific-driver.apk"');
        header('Content-Length: ' . filesize($path));
        header('X-Content-Type-Options: nosniff');
        readfile($path);
        exit();
    }

    private function notFound(string $what): void
    {
        $this->view->setLayout($this->roleLayout());
        $this->view->render('generals/fb_page', [
            'page_title' => 'Not found',
            'fb_msg'     => '<div class="alert alert-danger">' . htmlspecialchars($what) . '.</div>',
        ]);
    }
}
