<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\InfoImage;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Validator;

class InfoImageController extends Controller
{
    private $indexRoute = null;

    public function __construct(){
        $this->indexRoute = route('info-image.index');
    }

    public function index()
    {
        $data['info_image'] = InfoImage::query()->orderBy('created_at', 'desc')->get();

        return view('content.backend.settings.banner.index', $data);
    }

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), InfoImage::RULES, InfoImage::ERROR_MESSAGE);

        if ($validator->fails())
        {
            $errormessage = $validator->messages();

            return redirect()
            ->back()
            ->withErrors($validator)
            ->withInput();
        }
        DB::beginTransaction();

        try{
            $infoImage = InfoImage::query()->create([
                'image' => ''
            ]);

            $fileName = $this->getFileName($request->file('image'), $infoImage->id);

            $this->storeFile('info_image', $request->file('image'), $fileName);

            $infoImage->image = $fileName;
            $infoImage->save();

            DB::commit();
        }
        catch (Exception $ex){
            DB::rollBack();
        }

        return redirect()->intended($this->indexRoute);
    }

    public function getFileName($file, $id)
    {
        $extension = $file->guessClientExtension();
        $size = $file->getSize();
        $filename = $id. '.' . $extension;

        return $filename;
    }

    public function storeFile($dir, $file, $filename)
    {
        Storage::disk('uploads')->put('profileunesa_konten_statik/uploads/rekrutmen' . '/'.$dir.'/' . $filename, file_get_contents($file->getRealPath()));
    }

    public function destroy(Request $request, $id)
    {
        $image = InfoImage::query()->find(decrypt($id));
        Storage::disk('uploads')->delete('profileunesa_konten_statik/uploads/rekrutmen/info_image/'. $image->image);
        // unlink('https://statik.unesa.ac.id/profileunesa_konten_statik/uploads/rekrutmen/info_image/' . $image->image);

        $image->delete();
    }
}
