<?php
/**
 * Created by PhpStorm.
 * User: eater
 * Date: 4/5/16
 * Time: 2:03 AM
 */

namespace Eater\Glim\Handler\Panel\Certificates;


use Eater\Glim\Handler\Session;
use Eater\Glim\Model\CertificateQuery;

class Download extends Session
{
    protected $shouldHaveUser = true;

    public function handle()
    {
        $name = $this->attr('name');

        $cert = CertificateQuery::create()
            ->findOneByUserAndName($this->getUser(), $name);

        if ($cert === null) {
            return $this->getResponse()->withStatus(404)->write("Couldn't find your Certificate with the name '{$name}'");
        }

        return $this->getResponse()
            ->withHeader('Content-Type', 'plain/text')
            ->withHeader('Content-Disposition', 'attachment; filename="' . $name . '.' . $cert->getSerial() .'.crt"')
            ->write($cert->getCertificate());
    }
}