<?php

namespace App\Http\Controllers;

//change the request class if needed

use Akaunting\Setting\Drivers\Json;
use Illuminate\Http\Request as Request;
use App\Models\Pages as Entity;
use Illuminate\Validation\Rule;
use Yajra\DataTables\DataTables;
use App\Http\Resources\JsonResource;
use Illuminate\Http\File;

class PagesController extends Controller
{

    protected $namespace = 'pages.';

    public function index()
    {

        return view($this->namespace . 'index', [
            'entity' => new Entity(),
            'namespace' => $this->namespace
        ]);
    }

    public function store()
    {

        $entity = new Entity;

        $data = request()->validate(self::rules($entity));

        $entity->fill($data);
        
        $lastPriority = Entity::orderBy('priority', 'DESC')->first();
        if(isset($lastPriority) && !empty($lastPriority)){
            $entity->priority = $lastPriority->priority + 1;
        }else{
            $entity->priority = 0;
        }
        

        $entity->save();

        $this->handleUploadedImage($entity);

        if (request()->wantsJson()) {
            return JsonResource::make()->withSuccess(__('Stranica je uspešno sačuvana!'));
        }

        return redirect()->route($this->namespace . 'index')->withSystemSuccess(__('Stranica je uspešno sačuvana!'));
    }

    public function edit(Entity $entity)
    {
        return view($this->namespace . 'edit', [
            'entity' => $entity,
            'namespace' => $this->namespace
        ]);
    }

    public function update(Entity $entity)
    {

        $data = request()->validate(self::rules($entity));

        $entity->fill($data);

        $entity->save();

        $this->handleUploadedImage($entity);

        if (request()->wantsJson()) {
            return JsonResource::make()->withSuccess(__('Stranica je uspešno izmenjena!'));
        }

        return redirect()->route($this->namespace . 'index')->withSystemSuccess(__('Stranica je uspešno izmenjena!'));;
    }

    public function delete(Entity $entity)
    {

        $entity->delete();

        if (request()->wantsJson()) {
            return JsonResource::make()->withSuccess(__('Stranica je uspešno obrisana!'));
        }

        return redirect()->route($this->namespace . 'index')->withSystemSuccess(__('Stranica je uspešno obrisana!'));
    }

    public function datatable(Request $request)
    {
        $entity = request()['entityId'];
        $entities = Entity::query();

        if ($entity) {
            $entities->where('id', '<>', $entity);
        }

        $entities->orderBy('priority');
        
        return datatables($entities)
            ->addColumn('actions', function ($entity) {
                return view($this->namespace . 'partials.table.actions', [
                    'entity' => $entity,
                    'namespace' => $this->namespace
                ]);
            })->addColumn('sort_handle', function () {
                return view('_layout.partials.table.sort_handle');
            })->addColumn('ban', function ($entity) {
                return view('_layout.partials.table.active_inactive', [
                    'entity' => $entity,
                    'namespace' => $this->namespace,
                    'active' => $entity->isActive()
                ]);
            })
            ->rawColumns(['actions', 'ban'])
            ->setRowAttr([
                'id' => function($entity) {
                    return $entity->id;
                }
            ])
            ->make(true);
    }

    public function changeActive(Entity $entity)
    {
        $entity->ban = $entity->ban == 1 ? 0 : 1;

        $entity->save();

        $status = $entity->isActive() ? 'aktivirana' : 'deaktivirana';

        if (request()->wantsJson()) {
            return JsonResource::make()->withSuccess(__('Stranica je uspešno' . $status . '!'));
        }

        return redirect()->route($this->namespace . 'index')->withSystemSuccess(__('Autor je uspešno ' . $status . '!'));
    }

    protected function handleUploadedImage(Entity $entity)
    {
        if (request()->hasFile('photo')) {

            $currentDate = date("Y-m-d");

            $path = public_path('/data/images/' . $currentDate);

            if (!\File::exists($path)) {

                \File::makeDirectory($path);

                $path = public_path('/data/images/' . $currentDate);
            }

            $photoFile = request()->file('photo');
            $newPhotoFileName = $entity->id . '-' . $photoFile->getClientOriginalName() . '-orig.' . $photoFile->getClientOriginalExtension();
            $photoFile->move(
                $path,
                $newPhotoFileName
            );
            $entity->image = $path . '/' . $newPhotoFileName;

            $entity->save();
        }
    }
    
     /**
     * Ajaks funkcija koja prihvata novi redosled (mapu) prioriteta kategorija
     * ('media_categories') i setuje nove vrednosti u bazu podataka.
     * Napomena: Kod je identican onom u Content\SitemapController->changePriority()
     * 
     * @param Request $request
     * $request JSON struktura:
     * {
     *      'map_collection_range': "full", <- kreirano radi moguceg buduceg prosirenja
     *      'priority_map': [
     *          3, 1, 4, 2     
     *      ]
     * }
     * 
     * @return JSON
     */
    public function changePriority(Request $request)
    {
        $message = __('Redosled je uspešno izmenjen');
        $statusCode = 202;

        $data = $request->validate([
            'map_collection_range' => ['required', 'string', 'in:full'],
            'priority_map' => ['required' ,'array'],
            'priority_map.*' => ['numeric']
        ]);
        
        for($i=0; $i<count($data['priority_map']); ++$i) {

            // proveri za svaki slucaj da li je setovan indeks
            if( ! isset($data['priority_map'][$i]) ) {
                $statusCode = 400;
                $message = __("Primljena je neispravna 'JSON' struktura. Nedostaje indeks $i.");
                break;
            }

            $priority = $i;
            $id = $data['priority_map'][$i];

            // Izvrsi 'update' 'priority' kolone
            Entity::where('id', $id)->update(['priority' => $priority]);
        }

        return JsonResource::make()->withHttpStatus($statusCode)
                                   ->withMessage($message);
    } 

    protected function rules($entity)
    {
        $rules = [
            'title' => ['required', 'string','min:3', 'max:80'],
            'description' => ['nullable', 'string',  'max:191'],
            'with_sidebar' => ['required', 'int'],
            'photo' => ['nullable', 'file', 'image','max:' . config('newscms.max_document_upload_file_size')],
            'text' => ['required', 'string']
        ];

        return $rules;
    }
}
