<?php

class Customization_model extends Cf_Model
{
    private $allowedKeys = [
        'login_text',
        'color_schema',
        'logo_on_pdf',
        'logo_on_login',
        'logo_on_header',
        'header_text_color',
        'header_color',
        'header_links_color',
        'company_logo',
    ];

    private $tableName = 'customization';

    /**
     * @return array
     */
    public function getSettings()
    {
        $query = $this->db->get($this->tableName);
        $settings = $query->result();
        $data = [];
        foreach ($settings as $setting) {
            $data[trim($setting->key)] = trim($setting->value, '"');
        }
        return $data;
    }

    public function getSetting($key)
    {
        $query = $this->db->where('key', $key)->get($this->tableName);
        $setting = $query->row();
        if ($setting && isset($setting->value)) {
            return trim($setting->value, '"');
        }
        return false;
    }

    /**
     * @param $data
     * @return bool
     */
    public function updateSettings($data)
    {
        foreach ($data as $key => $value) {
            if (!in_array($key, $this->allowedKeys)) {
                unset($data[$key]);
                continue;
            }

            $value = is_array($value) ? json_encode($value) : '"' . trim($value) . '"';
            $sql = "INSERT INTO {$this->tableName} (key, value)
                    VALUES (?, ?)
                    ON CONFLICT (key) DO UPDATE
                    SET value = EXCLUDED.value";

            $this->db->query($sql, [$key, $value]);
        }

        return true;
    }

    public function uploadLogo($filePath)
    {
        $fileName = $_FILES['company_logo']['name'];
        // replace all non-alphanumeric and dot chars with underscores
        $fileName = preg_replace('/[^a-z0-9\.]+/', '_', strtolower($fileName));
        $config['upload_path'] = $filePath;
        $config['allowed_types'] = 'jpg|jpeg|png';
        $config['max_size'] = '5120';
        $config['max_width'] = '1024';
        $config['max_height'] = '1024';
        $config['overwrite'] = true;
        $config['file_name'] = $fileName;
        $this->load->library('upload', $config);

        if (!$this->upload->do_upload('company_logo')) {
            $error = $this->upload->display_errors();
            $error .= '<p> Max file size: 5MB , Max dimension: 1024x1024</p>';
            throw new Exception($error);
        } else {
            $this->upload->data();
        }
        return $fileName;
    }

    public function removeLogo($fileName, $filePath)
    {
        $filePath = realpath($filePath . $fileName);
        if (is_file($filePath)) {
            unlink($filePath);
        }
    }
}
