<?php
class cli_tasks extends Cli_Controller
{
    public function __construct()
    {
        parent::__construct();

        $this->load->database();

        if (CLI === false) {
            throw new Exception('You must run this in CLI mode');
        }
    }

    /**
     * Run check for checks
     *
     * @param type $delay - delay for lastCheck time
     * @param type $limit - how many checks per run
     * @param type $type  - all, sql
     */

    /* How to execute:
      /usr/bin/php /vagrant/source/mission-portal/index.php cli_tasks runalerts 10 10 sql

     */

    public function runalerts($delay = 300, $limit = 20, $type = 'all')
    {
        log_message('debug', "Start runalerts(). Params: delay: $delay, limit: $limit");

        $delay = intval($delay);
        $limit = intval($limit);

        if (!is_int($delay) || !is_int($limit) || !in_array($type, ['all', 'sql'])) {
            $message = 'runcheck(): Invalid parameters.';
            $message .= "\n Expected: int int [all|sql]\n";
            $message .= "\n Example: check_cli runcheck 300 20 sql\n";
            log_message('error', $message);
            echo "\n\n" . $message . "\n\n";
            exit(1);
        }

        // check if CFE_ROBOT_PASSWORD is set;

        if (!file_exists(APPPATH . '/config/cf_robot.php')) {
            $message = "\n Unable to find config file\n";
            log_message('error', $message);
            echo "\n\n" . $message . "\n\n";
            exit(1);
        }

        $this->config->load('cf_robot');

        $CFE_ROBOT_PASS = $this->config->item('CFE_ROBOT_PASSWORD');

        if (empty($CFE_ROBOT_PASS)) {
            $message = "\n Unable to find password file for CFE_ROBOT. Check if config/cf_robot.php exists\n";
            log_message('error', $message);
            echo "\n\n" . $message . "\n\n";
            exit(1);
        }

        try {
            $this->authorizePestByCFRobot();
            Cf_RestInstance::setRestClient($this->http_client);
            $this->restClient = $this->getRestClient();
        } catch (Exception $e) {
            $message = 'Unable to get REST service' . $e->getMessage();
            log_message('error', $message);
            echo "\n\n" . $message . "\n\n";
            exit(1);
        }

        $this->load->model('dashboard/alerts_model');

        try {
            $result = $this->alerts_model->runalerts($delay, $limit, $type);

            if (empty($result)) {
                $result = 'No alerts to process';
                log_message('info', $result);
            }

            exit(0);
        } catch (Exception $e) {
            $message = 'Unable to run check for alerts, error:' . $e->getMessage();
            log_message('error', $message);
            echo "\n\n" . $message . "\n\n";
            exit(1);
        }
    }

    /**
     *Remove events which are older than CFE_TRUNCATE_EVENTS
     *
     */
    public function truncate_events()
    {
        log_message('debug', 'Start truncate_events()');

        $time = $this->config->item('CFE_TRUNCATE_EVENTS');

        if (empty($time)) {
            echo "\nUnable get events truncate time\n";
            exit(1);
        }

        $filter = ['extract(epoch from time) <' => time() - (int) $time];

        $this->load->model('eventslog_model');

        try {
            $this->eventslog_model->delete($filter);
        } catch (Exception $e) {
            $message = 'Unable to delete events' . $e->getMessage();
            log_message('error', $message);
            echo "\n\n" . $message . "\n\n";
            exit(1);
        }
        log_message('debug', 'Finish truncate_events()');
        exit(0);
    }

    public function migrate_ldap_settings($url, $p)
    {
        $url = end($_SERVER['argv']);
        if (!filter_var($url, FILTER_VALIDATE_URL)) {
            echo "Url is required parameter \n";
            exit(0);
        }

        require_once APPPATH . '/services/LdapMigrationService.php';
        $migrateService = new LdapMigrationService($url);
        $migrateService->migrateLDAPSettings();
    }

    public function migrate_cmdb_configs()
    {
        require_once APPPATH . '/services/CmdbMigrationService.php';

        try {
            $migrateService = new CmdbMigrationService();
            if ($migrateService->migrate()) {
                fwrite(STDOUT, "Migration completed successfully.\n");
            }
            exit(0);
        } catch (Exception $e) {
            fwrite(STDERR, 'CMDB Migration failed: ' . $e->getMessage() . "\n");
            exit(2);
        }
    }

    public function process_api_events()
    {
        $this->authorizePestByCFRobot();

        $this->load->model('events/api_event_model');
        $this->api_event_model->setRestClient($this->http_client);

        $this->api_event_model->process();
    }

    public function update_health_failures()
    {
        $this->load->model('setup_model');
        $this->authorizePestByCFRobot();
        if ($this->setup_model->isSetupComplete()) {
            $this->http_client->post('/internal-tasks/health-diagnostics-failures');
        }
    }
}
