<?php

namespace CCDN\Controllers;

use CCDN\Helpers\Api\ApiHandler;
use CCDN\Helpers\Controller;
use CCDN\Helpers\DB\SettingsSave;
use CCDN\Helpers\Facade\Http\Response;
use CCDN\Helpers\Facade\Http\Url;
use CCDN\Helpers\Http\Request;
use CCDN\Helpers\Settings;
use CCDN\Helpers\XFields;

class SettingsController extends Controller
{

    protected $viewsFolder = 'settings';
    protected $parent = '';

    public function __construct($parent = 'settings')
    {
        $this->parent = $parent;
    }

    public function settings()
    {
        $api = new ApiHandler();

        $voices = $api->getVoices([
            'limit' => 500
        ]);

        $ccdnConf = Settings::all();

        $videoVoicePriority = (array)$ccdnConf->getJsonDecode('video_voice_priority');
        $videoVoicesDisable = (array)$ccdnConf->getJsonDecode('video_voices_disabled');
        return Response::make($this->render('settings', [
            'ccdnConf' => $ccdnConf,
            'customFields' => XFields::load(),
            'voices' => $voices,
            'videoVoicePriority' => $videoVoicePriority,
            'videoVoicesDisable' => $videoVoicesDisable,
        ]));
    }

    public function saveConfig(Request $request)
    {

        $settings = $request->post();

        $voicePriorityJson = '';
        $voicesDisabledJson = '';

        if (isset($settings['video_voice_priority'])) {
            $voicePriorityJson = json_encode($settings['video_voice_priority'], JSON_UNESCAPED_UNICODE);
        }

        if (isset($settings['video_voices_disabled'])) {
            $voicesDisabledJson = json_encode($settings['video_voices_disabled'], JSON_UNESCAPED_UNICODE);
        }

        if (empty($settings['premier_format_date'])) {
            $settings['premier_format_date'] = 'Y-m-d';
        }

        $settings['video_voice_priority'] = $voicePriorityJson;
        $settings['video_voices_disabled'] = $voicesDisabledJson;
        $configSave = new SettingsSave($settings);
        $configSave->main();

        Response::redirect(Url::to($this->parent));
    }
}
