<?php

namespace App\Http\Controllers;

//change the request class if needed
use Illuminate\Http\Request as Request;
use App\Http\Resources\JsonResource;
use App\Models\Admin\Setting as Entity;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use App\Http\Requests\Admin\SettingsRequest;

class SettingsController extends Controller 
{   
    
    protected $request;
    
    public function __construct(Request $request)
    {
        $this->request = $request;
    }
    
    public function index()
    {   
        $newsCmsLogo = Entity::where('key', 'newscms.logo')->first();
        $newsCmsIcon = Entity::where('key', 'newscms.icon')->first();
        
        return view('settings.index', [
            'newsCmsLogo' => $newsCmsLogo,
            'newsCmsIcon' => $newsCmsIcon
        ]);
    }

    public function update(SettingsRequest $request)
    {   
        
        $data = $request->validated();
        
        $this->saveOrUpdateNewsCmsImage($data, 'logo');
        $this->saveOrUpdateNewsCmsImage($data, 'icon');
        
        setting($data)->save();

        if ($request->wantsJson()) {
            return JsonResource::make()->withSuccess(__('Podešavanja su sačuvana'));
        }

        return redirect()->route('settings.index')->withSystemMessage(__('Podešavanja su sačuvana'));
    }

    /**
     * Snimi/apdejtuj sliku za firmu
     * Za ovaj metod vrlo je bitno da sledeci 'string'-ovi formiraju prema 
     * delu 'string'-a IME_SLIKE ovako:
     *  - imena polja u formi -> newscms.IME_SLIKE
     *  - kljuc u 'setting'-u -> newscms.IME_SLIKE
     *  - 'class' u 'images tabeli -> image_IME_SLIKE 
     * 
     * @param Array $data
     * @param string $imageName  | 'logo' ili 'icon'
     * 
     * @return void
     */
    private function saveOrUpdateNewsCmsImage(&$data, $imageName)
    {
        if(!setting('newscms.' . $imageName) && !key_exists($imageName, $data['newscms'])) {
            // Ignorisi ako nema snimljene slike od ranije i ako sa forme nije dosla image
            return;
        }
        if(key_exists($imageName, $data['newscms']) && $data['newscms'][$imageName] instanceof UploadedFile) {
            
            // sliku vezemo za instancu modela setting koja ima key = "newscms.logo" ili kreiramo novu instancu
            $newsCmsLogo = Entity::where('key', 'newscms.' . $imageName)->first();
            if(!$newsCmsLogo) {
                $newsCmsLogo = Entity::create(['key' => 'newscms.' . $imageName, 'value' => NULL]);
            }
            $newsCmsLogo->updateImage('image_' . $imageName, $data['newscms'][$imageName]);

            // u settings pod kljucem newscms.logo snimamo url do slike
            $newsCmsLogoUrl = Entity::where('key', 'newscms.' . $imageName)->first()->getImageUrl('image_' .$imageName);
            $data['newscms'][$imageName] = $newsCmsLogoUrl;
        
        } else {
            // ako nema nove slike sa forme ostavljamo stari url do slike
            $data['newscms'][$imageName] = setting('newscms.' . $imageName);
        }
    }
    
    /*
     * Obrisi sliku preko ajaks poziva
     */
    public function ajaxDeleteImage(Request $request, Entity $entity)
    {
        $data = $request->validate([
            "imageClass" => ["required", "string", "exists:images,class"]
        ]);
        
        $stat = $entity->deleteImage($data['imageClass']);
        
        if(!$stat) {
            return JsonResource::make()->withError(__("Greška. Slika nije mogla biti izbrisana."));
        }
        
        // brisemo kljuc newscms.logo ili newscms.icon u settings-u
        if($data['imageClass'] == 'image_logo') {
            setting(['newscms.logo' => null])->save();
        }
        else if($data['imageClass'] == 'image_icon') {
            setting(['newscms.icon' => null])->save();
        }
        else if($data['imageClass'] == 'image_app_logo') {
            setting(['newscms.app_logo' => null])->save();
        }
        
        return JsonResource::make()->withSuccess(__("Slika je izbrisana."));
    }
}
