<?php
namespace Clevercherry\Backslash4\Controllers\Admin;

use Illuminate\Http\Request;
use Clevercherry\Backslash4\Controllers\Controller;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\View;
use App\Models\Setting;
use Clevercherry\Backslash4\Services\Instagram;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Artisan;

class SettingController extends BkAdminController
{
    public $adminRoute = 'admin.settings';
    public $AppModel = Setting::class;
    //public $adminView = "backslash4::admin.settings";
    // id, title, description, group, input, order, default, required, options(json)
    
    /**
     * Returns the index page view
     * @return type
     */
    public function index(Request $request)
    {
        $q = @$request->q;
        if(empty($q))
        {   $items=Setting::orderBy('group')->orderBy('order')->get();
            $groups=Setting::getGroups();
        } else
        {   $items=Setting::indexSearch($q)
                        ->orderBy('group')->orderBy('order')
                        ->get();
            $groups=Setting::getGroups();
        }
        
        return view('backslash4::admin.settings.index') //$this->adminView.'.index'
            ->with('appModel', $this->AppModel)
            ->with('showAdminSearch', ($this->AppModel)::showAdminSearch())
            ->with('tableName', $this->getTableName() )
            ->with('type', Str::of(Str::replace('\\','/',$this->AppModel))->basename())
            ->with('adminRoute', $this->adminRoute)
            ->with('groups', $groups)
            ->with('selectedGroup',  @$request->group)
            ->with('action', route('admin.settings.savegroup'))
            ->with('items', $items);
    }

    public function saveGroupValues(Request $request)
    {   
        $clearSlugs = config('backslash4.settings.on_save.clear.slugs.list',[]);
        $clearAction = false;

        $store = $request->except(['_token', 'bs4_group']);
        $group = @$request->bs4_group;
        foreach($store as $key => $value)
        {    $setting = Setting::where('group', $group)->where('slug', $key)->first(); 
             $setting->update(['value' => $value]);

             // check if theslug in is the list of watched ones 
             // backslash4.settings.on_save.clear.slugs.list',[] 
             if(in_array($key, $clearSlugs))
                $clearAction = true;
        }

        //check all settings in this group for switch or checkbox
        $checks = Setting::where('group', $group)->where(function($query) {
            $query->where('input', 'check-box')
                  ->orWhere('input', 'switch');
            })->get();
        foreach($checks as $check)
        {   if(!isset($store[$check->slug]))
            {   $check->update(['value' => '0']);
            }
        }

        // if the slugs saved contain any of the listed slugs in 
        // backslash4.settings.on_save.clear.slugs.list',[]
        if($clearAction)
        {
            if(config('backslash4.settings.on_save.slugs.clear.views',0))
                Artisan::call('view:clear');

            if(config('backslash4.settings.on_save.slugs.clear.routes',0))
                Artisan::call('route:clear');
        
            if(config('backslash4.settings.on_save.slugs.clear.cache',0))
                Cache::flush();
        }

        //because some settings may be cache related
        if(config('backslash4.settings.on_save.clear.views',0))
            Artisan::call('view:clear');

        if(config('backslash4.settings.on_save.clear.routes',0))
            Artisan::call('route:clear');
            
        if(config('backslash4.settings.on_save.clear.cache',0))
            Cache::flush();

        //return redirect()->action("\App\Http\Controllers\Admin\SettingController@index", [$request]);
        return redirect()->back();
        //return $this->index($request);
    }


    public function checkBeforeSave($store): array
    {
        //checkbox
        if(!isset($store['required']))
            $store['required'] = 0;

        return $store;
    }

    public function instagramAuthentication()
    {
        return redirect( Instagram::getUrl() );
    }

    /**
     * Response Instagram Url Path
     * @param  Request $request 
     */
    public function responseInstagram(Request $request) {
        $code = $request->code;
        if(!$code) {
            abort(404);
        }

        $instagram = new Instagram();
        $token = $instagram->getAccessTokenAndUserId($code);

        return view('backslash4::admin.settings.instagram-acknowledge')
                        ->with('token', $token);
    }
}
