<?php
/**
 * Webkul Software.
 *
 * @category  Webkul
 * @package   Webkul_AdvanceSeoManager
 * @author    Webkul
 * @copyright Copyright (c) Webkul Software Private Limited (https://webkul.com)
 * @license   https://store.webkul.com/license.html
 */
namespace Webkul\AdvanceSeoManager\Controller\Adminhtml\Ping;

use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Controller\ResultFactory;
use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\Exception\InputException;

class Clear extends Action
{

    /**
     * Authorization level of a basic admin session
     *
     * @see _isAllowed()
     */
    const ADMIN_RESOURCE = 'Webkul_AdvanceSeoManager::ping_clear';

    /**
     * @var Magento\Framework\App\Filesystem\DirectoryList
     */
    protected $directoryList;

    /**
     * __construct
     *
     * @param Context                                    $context
     * @param Webkul\AdvanceSeoManager\Model\PingService $pingService
     */
    public function __construct(
        Context $context,
        \Magento\Framework\App\Filesystem\DirectoryList $directoryList,
        \Magento\Framework\Filesystem\Driver\File $driver,
        \Magento\Framework\Filesystem\Io\File $file
    ) {
        $this->directoryList = $directoryList;
        $this->file = $file;
        $this->driver = $driver;
        parent::__construct($context);
    }

    /**
     * ping url.
     *
     * @return json
     */
    public function execute()
    {
        $responseContent = [];
        try {
            $logFile = $this->directoryList->getPath(DirectoryList::LOG).'/ping-logger.log';
            if ($this->file->fileExists($logFile)) {
                $this->driver->fileGetContents($logFile, "");
                $responseContent = [
                    'success' => true,
                    'error_message' => __('log successfully cleared.')
                ];
            } else {
                throw new \Magento\Framework\Exception\LocalizedException(__("no log file found"));
            }
        } catch (\Exception $e) {
            $responseContent = [
                'success' => false,
                'error_message' => __($e->getMessage())
            ];
        }
        
        /**
         * @var \Magento\Framework\Controller\Result\Json $resultJson
         */
        $resultJson = $this->resultFactory->create(ResultFactory::TYPE_JSON);
        $resultJson->setData($responseContent);
        return $resultJson;
    }
   
    /**
     * Check for is allowed
     *
     * @return boolean
     */
    protected function _isAllowed()
    {
        return $this->_authorization->isAllowed(self::ADMIN_RESOURCE);
    }
}
