<?php
include_once __DIR__ . '/autoload.php';

class Compliance_exchange extends Cf_Model
{
    private $userName = false;

    public function __construct()
    {
        $this->load->model('search_save_model');
        $this->load->model('dashboard/rules_model');
        $this->load->model('variables_dictionary_model');
    }

    public function setUserName($userName)
    {
        $this->userName = $userName;
    }

    public function import($request)
    {
        $import = new ComplianceImport(
            $this->rules_model,
            $this->search_save_model,
            $this->variables_dictionary_model->getVariables(),
            $this->userName,
        );
        $data = json_decode($request['data'], true);
        $overwrite = isset($request['overwrite']) && $request['overwrite'] == 'true';
        $public = isset($request['public']) && $request['public'] == 'true';
        $source = $request['source'] ?? '';
        return $import->import($data, $overwrite, $public, $source);
    }

    public function export(int $id)
    {
        $export = new ComplianceExport();
        $result = ['reports' => [], 'conditions' => []];
        $filter = ['id' => $id, 'type' => 'compliance'];
        $searchResults = $this->search_save_model->get_all_search($filter);
        $report = reset($searchResults);

        if (empty($report)) {
            throw new Exception("Compliance report #$id not found");
        }

        if ($report->export_id === null) {
            $report->export_id = $this->search_save_model->generateExportId($report, $this->userName);
        }

        $result['reports'][$report->export_id] = [
            'id' => $report->export_id,
            'type' => $report->type,
            'title' => $report->label,
            'conditions' => [],
        ];

        if (isset($report->AdvancedReportsData['SQL'])) {
            $data = $report->AdvancedReportsData['SQL'];
            if (is_string($data)) {
                $data = json_decode($data, true);
            }
            $conditionIds = $data['conditions'] ?? [];
            if (sizeof($conditionIds) > 0) {
                $conditions = $this->rules_model->get_rules_with_ids($conditionIds);
                foreach ($conditions as $cond) {
                    if ($cond->export_id === null) {
                        $cond->export_id = $this->rules_model->generateExportId($cond, $this->userName);
                    }
                    $result['conditions'][$cond->export_id] = $export->export($cond);
                    $result['reports'][$report->export_id]['conditions'][] = $cond->export_id;
                }
            }
        }
        return $this->writeExportFile(json_encode($result, JSON_PRETTY_PRINT), strtolower($report->label));
    }

    /**
     * @param string $json
     * @param $reportName
     * @return string
     */
    private function writeExportFile(string $json, $reportName)
    {
        $this->load->helper('string');
        $now = DateTime::createFromFormat('U.u', microtime(true));
        $exportName = str_replace(
            ' ',
            '_',
            'compliance_report_' .
                preg_replace('/\W+/', '', $reportName) .
                '_' . // remove non-alphanumeric characters
                $now->format('m-d-Y') .
                random_string('alnum', 32) .
                '.json',
        );
        if (!file_put_contents(get_tmpdir() . $exportName, $json)) {
            throw new Exception('Error occurred while writing compliance report export file');
        }
        return $exportName;
    }
}
