<?php

namespace App\Controllers;

use App\Models\CountriesModel;
use App\Models\CronTabModel;
use App\Models\CurrencyModel;
use App\Models\SettingsModel;
use App\Models\TemplateModel;
use App\Models\ThemeModel;
use App\Models\TimezoneModel;
use App\Models\Usuarios\UserGroupModel;
use App\Models\Usuarios\UserModel;

class Settings extends BaseController
{
    private $settings_model;
    private $countries_model;
    private $theme_model;
    private $currency_model;
    private $timezone_model;
    private $group_model;
    private $template_model;
    private $user_model;
    private $crontab_model;
    private $integration;

    function __construct()
    {
        $this->settings_model = new SettingsModel();
        $this->countries_model = new CountriesModel();
        $this->theme_model = new ThemeModel();
        $this->currency_model = new CurrencyModel();
        $this->timezone_model = new TimezoneModel();
        $this->group_model = new UserGroupModel();
        $this->template_model = new TemplateModel();
        $this->user_model = new UserModel();
        $this->crontab_model = new CronTabModel();
        $this->integration = new Integration();
    }

    public function index()
    {
        helper('form');

        $data['title'] = [
            'module' => lang("App.settings_title"),
            'page'   => lang("App.settings_subtitle"),
            'icon'  => 'fas fa-sliders-h'
        ];

        $data['breadcrumb'] = [
            ['title' => lang("App.menu_settings"), 'route'  => site_url('settings'), 'active' => true]
        ];

        $data['obj'] = $this->settings_model->first();
        $data['countries'] = $this->countries_model->select('id_country,code,name')->where('data_lang',session()->get('lang')??'en')->findAll();
        $data['theme'] = $this->theme_model->select('id_theme,type,name')->findAll();
        $data['currency'] = $this->currency_model->select('id_currency,code,name')->findAll();
        $data['timezone'] = $this->timezone_model->select('id_timezone,timezone,description')->findAll();
        $data['group'] = $this->group_model->select('token,title')->findAll();
        $db = db_connect('default');
        $data['tables'] = $db->listTables();
        $data['user'] = $this->user_model->select('token,first_name,email')->where('status',true)->findAll();

        echo view(getenv('theme.path').'form/settings/index', $data);

    }

    public function store()
    {
        //Demo Mode
        if(env('demo.mode')??false){
            session()->setFlashdata('sweet', ['warning',lang("App.general_demo_mode")]);
            return redirect()->to('/settings');
        }

        helper('form');
        $session = session();
        if($listPost = $this->request->getPost()){
            $listPost['id_settings'] = 1;
            $listPost['captcha_register'] = isset($listPost['captcha_register']) && $listPost['captcha_register'] == 'on';
            $listPost['captcha_login'] = isset($listPost['captcha_login']) && $listPost['captcha_login'] == 'on';
            $listPost['captcha_recovery'] = isset($listPost['captcha_recovery']) && $listPost['captcha_recovery'] == 'on';
            $listPost['registration'] = isset($listPost['registration']) && $listPost['registration'] == 'on';
            $listPost['terms_conditions'] = isset($listPost['terms_conditions']) && $listPost['terms_conditions'] == 'on';
            $listPost['email_confirmation'] = isset($listPost['email_confirmation']) && $listPost['email_confirmation'] == 'on';
            $listPost['send_email_register'] = isset($listPost['send_email_register']) && $listPost['send_email_register'] == 'on';
            $listPost['send_notification_register'] = isset($listPost['send_notification_register']) && $listPost['send_notification_register'] == 'on';
            $listPost['send_email_welcome'] = isset($listPost['send_email_welcome']) && $listPost['send_email_welcome'] == 'on';
            $listPost['remember_me'] = isset($listPost['remember_me']) && $listPost['remember_me'] == 'on';
            $listPost['forgot_password'] = isset($listPost['forgot_password']) && $listPost['forgot_password'] == 'on';
            $listPost['two_factor_auth'] = isset($listPost['two_factor_auth']) && $listPost['two_factor_auth'] == 'on';
            $listPost['throttle_auth'] = isset($listPost['throttle_auth']) && $listPost['throttle_auth'] == 'on';
            $listPost['enable_api'] = isset($listPost['enable_api']) && $listPost['enable_api'] == 'on';
            $listPost['block_external_api'] = isset($listPost['block_external_api']) && $listPost['block_external_api'] == 'on';
            $listPost['remove_log'] = isset($listPost['remove_log']) && $listPost['remove_log'] == 'on';
            $listPost['backup_notification_email'] = isset($listPost['backup_notification_email']) && $listPost['backup_notification_email'] == 'on';
            $listPost['backup_automatic'] = isset($listPost['backup_automatic']) && $listPost['backup_automatic'] == 'on';
            $listPost['backup_table'] = implode(",",$listPost['backup_table']??[]);
            $this->settings_model->save($listPost);
            $settings = $this->settings_model->first()??[];
            $session->set('settings', $settings);
            $session->set('lang', $settings['default_language'] ?? 'es');
            $session->setFlashdata('sweet', ['success',lang("App.settings_alert_add")]);
            return redirect()->to('/settings');
        } else{
            $session->setFlashdata('sweet', ['error',lang("App.settings_alert_error")]);
            return redirect()->to('/settings');
        }
    }  

    public function template()
    {
        helper('form');

        $data['title'] = [
            'module' => lang("App.template_title"),
            'page'   => lang("App.template_subtitle"),
            'icon'  => 'fas fa-mail-bulk'
        ];

        $data['breadcrumb'] = [
            ['title' => lang("App.menu_dashboard"), 'route' => "/home", 'active' => false],
            ['title' => lang("App.menu_settings"), 'route'  => "/settings", 'active' => false],
            ['title' => lang("App.template_title"), 'route'  => "", 'active' => true]
        ];

        $data['btn_return'] = [
            'title' => lang("App.global_come_back"),
            'route'   => '/home',
            'class'   => 'btn btn-dark mr-1',
            'icon'  => 'fas fa-angle-left'
        ];

        $data['btn_submit'] = [
            'title' => lang("App.global_save"),
            'route'   => '',
            'class'   => 'btn btn-primary mr-1',
            'icon'  => 'fas fa-save'
        ];

        $data['template'] = $this->template_model->findAll();

        echo view(getenv('theme.path').'main/header');
        echo view(getenv('theme.path').'form/settings/template', $data);
        echo view(getenv('theme.path').'main/footer');
    }

    public function template_store()
    {
        //Demo Mode
        if(env('demo.mode')??false){
            session()->setFlashdata('sweet', ['warning',lang("App.general_demo_mode")]);
            return redirect()->to('/settings/template');
        }

        $session = session();
        helper('form');

        if($field = $this->request->getPost()){
            $ids = [];
            $template = [];
            unset($field['files']);
            foreach ($field as $key=>$value){
                $id = explode('_',$key);
                array_push($ids,$id[2]);
            }
            foreach (array_unique($ids) as $item){
                $template[$item] = [];
                foreach ($field as $key=>$value){
                    $id = explode('_',$key);
                    if($id[2] == $item){
                        if(empty($template[$item])){
                            $template[$item] = array_merge( $template[$item],['id_template' => intval($id[2])]);
                            $template[$item] = array_merge( $template[$item],['subject' => ""]);
                            $template[$item] = array_merge( $template[$item],['body' => ""]);
                        }
                        switch($id[1])
                        {
                            case 'email';
                                switch($id[0])
                                {
                                    case 'title';
                                        $template[$item] = array_merge( $template[$item],['subject' => $value]);
                                        break;
                                    default;
                                        $template[$item] = array_merge( $template[$item],[$id[0] => $value]);
                                        break;
                                }
                                break;
                        }
                    }
                }
            }
            $this->template_model->updateBatch($template,'id_template');
            $session->setFlashdata('sweet', ['success',lang("App.template_alert_add")]);
            return redirect()->to('/settings/template');
        } else{
            $session->setFlashdata('sweet', ['error',lang("App.template_alert_error")]);
            return redirect()->to('/settings/template');
        }
    }
}
