<?php

namespace App\Http\Controllers\Traits;

use Illuminate\Http\Request as Request;
use App\Models\Website\Website;
use App\Http\Resources\JsonResource;
use App\Models\Category as Entity;
use Illuminate\Support\Facades\Log;

/**
 * 'trait' sa zajednickim metodama kategorija (CategoriesController) i 
 * potkategorija (SubcategoriesController).
 */
trait CategoriesTrait
{
    /**
     * @var string Heksadecimalna vrednost 'default' boje
     */
    protected $defaultHexColor = '#305AA2';
    
    /**
     * Vrati vrednost activeWebsite na osnovu prosledjenog moda.
     * Konvertuje 'URL path' od vebsajta u ID i obratno.
     * 
     * @return string|integer
     */
    protected function activeWebsite($actWeb, $mode='id')
    {
        if($mode == 'id') {
            return $actWeb == Entity::COMMON_WEBSITE_ID_URL_PATHNAME ? Website::COMMON_WEBSITE_ID 
                                                                     : $actWeb;
        }
        elseif($mode == 'path') {
            return $actWeb == Website::COMMON_WEBSITE_ID ? Entity::COMMON_WEBSITE_ID_URL_PATHNAME
                                                         : $actWeb;
        }

        throw new \Exception('Programerska greska! Neispravna vrednost $mode parametra.');
    }

    /*
     * Yajrabox datatables metod
     */
    public function datatable(Request $request, $activeWebsite, $parentId=0)
    {
        $query = Entity::where('site_id', $this->activeWebsite($activeWebsite, 'id')) 
                       ->orderBy('priority');
        
        if($request->has('parent_id') && !is_null($request->parent_id)) {
            $parentId = $request->parent_id;
        }
        else {
            $parentId = 0;
        }

        return datatables($query)
            ->addColumn('actions', function ($entity) use($parentId, $activeWebsite) {
                $actionsPartial = $parentId > 0 ? 'subcategories.partials.table.actions'
                                                : 'categories.partials.table.actions';
                return view($actionsPartial, ['entity' => $entity, 'activeWebsite' => $activeWebsite]);
            })
            ->addColumn('sort_handle', function ($entity) {
                return view('_layout.partials.table.sort_handle');
            })
            ->addColumn('status', function ($entity) {
                return view('_layout.partials.table.active_inactive', 
                            ['active' => $entity->isActive()]);
            })
            ->editColumn('color', function ($entity) {
                return view('categories.partials.table.color', 
                            ['entity' => $entity]);
            })
            ->filter(function ($query) use($parentId) {
                $query->where('parent_id', $parentId);
            })
            ->rawColumns(['actions', 'status', 'color'])
            ->setRowAttr([
                'id' => function($entity) {
                    return $entity->id;
                }
            ])
            ->make(true);
    }

    /**
     * Ajaks funkcija koja prihvata novi redosled (mapu) prioriteta kategorija
     * ('blog_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);
    }    

}