<?php

namespace App\Http\Controllers\Admin;

use App\Option;
use App\Language;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Artisan;

class OptionController extends Controller
{
    public function __construct()
    {
        if ( alreadyInstalled() ) {
            $this->middleware('auth');
        }
    }

    public function index()
    {
        $options = Option::pluck('value', 'name')->all();
        $languages = Language::all();

        return view('options.index', compact(['options', 'languages']));
    }

    public function store(Request $request)
    {
        foreach($request->except('_token') as $key => $value) {
            $setting = Option::where('name', $key)->first();

            if ($key === 'block_movie' || $key === 'block_tv') {
                $value = explode(PHP_EOL, $value);
            }

            if ($key === 'logo') {
                if ($request->hasFile('logo')) {
                    $request->validate([
                        'logo' => 'required|image|mimes:jpeg,png,jpg,gif,svg',
                    ]);

                    $name = Str::slug(Str::before($request->logo->getClientOriginalName(), '.'));
                    $ext = $request->logo->getClientOriginalExtension();
                    $filename = "{$name}.{$ext}";

                    $request->logo->move(public_path('themes/'.get_theme()), $filename);

                    if ( file_exists( public_path('themes/'.get_theme().'/').Option::getSetting('logo') ) ) {
                        unlink(public_path('themes/'.get_theme().'/').Option::getSetting('logo'));
                    }

                    $value = $filename;
                }
            }

            $setting->update([
                'name' => $key,
                'value' => $value
            ]);

        }

        return redirect()->back();
    }

    public function purgingCached()
    {
        DB::table('cache')->truncate();

        return response()->json(['status' => 'oke']);
    }
}
