<?php
/**
 * Created by PhpStorm.
 * User: eater
 * Date: 4/6/16
 * Time: 11:30 PM
 */

namespace Eater\Glim\Handler\Panel\Certificates;

use Eater\Glim\Handler\Session;
use Eater\Glim\Model\CertificateQuery;
use Eater\Glim\Service\CA;
use Slim\Http\Response;

class Revoke extends Session
{
    protected $shouldHaveUser = true;

    /**
     * @return Response
     */
    public function handle()
    {
        $user     = $this->getUser();
        $name     = $this->post('name');
        $password = $this->post('password');

        $cert = CertificateQuery::create()
            ->filterByName($name)
            ->filterByUser($user)
            ->findOne();

        if ($cert === null) {
            return $this->json([
                "success" => false,
                "error"   => 'Certificate with the name "' . $name . '" doesn\'t exist'
            ]);
        }

        if (!password_verify($password, $user->getPassword())) {
            return $this->json([
                'success' => false,
                'error'   => 'Invalid password'
            ]);
        }

        /**
         * @var CA $ca
         */
        $ca   = $this->get('ca');

        try {
            $ca->revoke($cert->getCertificate());
        } catch (\Exception $e) {
            return $this->json([
                "success" => false,
                "error"   => $e->getMessage()
            ]);
        }

        $cert->setRevoked(true);
        $cert->save();

        return $this->json([
            "success" => true
        ]);
    }
}