<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;
use Illuminate\Http\Request;

use App\Models\User;
use App\Models\FilesFolder;
use App\Models\FilesTemplate;

use Carbon\Carbon;

use App\Libraries\Generic;

class FilesTemplatesController extends Controller
{
    
    protected $generic;
    protected $website_id;
    
    public function __construct(){
        
        $this->website_id = config('constants.website_id');
        $this->generic = new Generic();
        
    }
    
    public function getFileTemplate(Request $request)
    {
        
        $user_id = auth()->user()->id;
        
        $owner_id = User::getOwnerOfUser($user_id);

        // check if permission to do
        if(!User::checkPermission('get-file-template')){
            return response()->json(config('constants.messages.permission_denied'), 400);
            exit();
        }
        
        $template_id = $request->query('template_id');
        $template = FilesTemplate::find($template_id);
        
        // check if template exists
        if(empty($template)){
            return response()->json(['message' => 'No Template Found']);
        }
        
        // check if have access to view or edit
        if($template->owner_id != $owner_id){
            return response()->json(config('constants.messages.invalid_access'), 400);
            exit();
        }
        
        $template = $template->toArray();
            
        $template_id = $template['id'];
        $folders = FilesFolder::select(['id', 'name', 'picture', 'order_number', 'parent_id', 'file_template_id', 'name as title'])->where(['file_template_id'=>$template_id])->get();
        
        $template['folders'] = [];
        
        if(!empty($folders)){
            $folders = $folders->toArray();
            $template['folders'] = $this->parentChildTree($folders);
        }

        
        return response()->json(['message' => config('constants.messages.response_success'), 'data'=> ['template' => $template] ]);
    }
    
    public function getMyFilesTemplates()
    {
        
        $user_id = auth()->user()->id;
        
        $owner_id = User::getOwnerOfUser($user_id);

        // check if permission to do
        if(!User::checkPermission('get-my-files-templates')){
            return response()->json(config('constants.messages.permission_denied'), 400);
            exit();
        }
        
        $templates = FilesTemplate::select(['id', 'name'])->where(['owner_id'=>$owner_id])->get();
        
        $templates = (!empty($templates)) ? $templates->toArray() : [];
        
        for($i=0; $i<count($templates); $i++){
            
            $template_id = $templates[$i]['id'];
            $folders = FilesFolder::select(['id', 'name', 'order_number', 'picture', 'parent_id', 'file_template_id', 'name as title'])->where(['file_template_id'=>$template_id])->get();
            
            $templates[$i]['folders'] = [];
            
            if(!empty($folders)){
                $folders = $folders->toArray();
                $templates[$i]['folders'] = $this->parentChildTree($folders);
            }
            
        }
        
        return response()->json(['message' => config('constants.messages.response_success'), 'data'=> ['templates' => $templates] ]);
    }

    public function fileTemplate(Request $request)
    {
        
        $user_id = auth()->user()->id;
        $owner_id = User::getOwnerOfUser($user_id);

        // check if permission to do
        if(!User::checkPermission('file-template')){
            return response()->json(config('constants.messages.permission_denied'), 400);
            exit();
        }

        $validator = Validator::make($request->all(), [
            'name' => 'required',
        ]);
        
        if ($validator->fails()) {
            return response()->json($validator->errors(), 400);
        }
        
        
        $update_criteria = [];
        if(!empty($request->id)){
            $update_criteria['id'] = $request->id;
        }
        else{
            $update_criteria['id'] = 0;
        }
        
        //$update_criteria = [];
        
        FilesTemplate::updateOrCreate(
            $update_criteria,
            [
                'name' => $request->name, 
                'owner_id' => $owner_id, 
                'created_by' => $user_id
            ]
        );

        return response()->json(['message' => 'Success', 'data'=> [] ]);
        
    }
    
    public function fileTemplateFolder(Request $request)
    {
        
        $user_id = auth()->user()->id;

        // check if permission to do
        if(!User::checkPermission('file-template-folder')){
            return response()->json(config('constants.messages.permission_denied'), 400);
            exit();
        }
        
        $validator = Validator::make($request->all(), [
            'name' => 'required',
            'order_number' => 'required|numeric',
            'file_template_id' => 'required',
        ]);

        if ($validator->fails()) {
            return response()->json($validator->errors(), 400);
        }
        
        $update_criteria = [];
        if(!empty($request->id)){
            $update_criteria['id'] = $request->id;
        }
        else{
            $update_criteria['id'] = 0;
        }
        
        //$update_criteria = [];
        
        FilesFolder::updateOrCreate(
            $update_criteria,
            [
                'name' => $request->name, 
                'picture' => $request->picture ?? '',
                'order_number' => $request->order_number ?? 0, 
                'path' => '',
                'parent_id' => !empty($request->parent_id) ? $request->parent_id : null,
                'file_template_id' => $request->file_template_id
            ]
        );

        return response()->json(['message' => 'Success', 'data'=> [] ]);
        
    }
    
    public function parentChildTree(array $elements, $parentId = 0)
    {
         $branch = array();
        
        foreach ($elements as $element) {
            if ($element['parent_id'] == $parentId) {            
                
                $children = $this->parentChildTree($elements, $element['id']);
                if ($children) {
                   
                    $element['children'] = $children;
                   
                }
                $branch[] = $element;
            }
        }

        return $branch;
        
    }
    
    public function duplicateFileTemplate(Request $request){
        
        $user_id = auth()->user()->id;
        $owner_id = User::getOwnerOfUser($user_id);

        // check if permission to do
        if(!User::checkPermission('duplicate-file-template')){
            return response()->json(config('constants.messages.permission_denied'), 400);
            exit();
        }
        
        $validator = Validator::make($request->all(), [
            'name' => 'required',
            'file_template_id' => 'required|numeric'
        ]);

        if ($validator->fails()) {
            return response()->json($validator->errors(), 400);
        }
        
        $file_template_id = $request->file_template_id;
        
        $template = FilesTemplate::find($file_template_id);
        
        $this->generic->duplicateFileTemplate($file_template_id, $request->name);
        
        return response()->json(['message' => 'Success', 'data'=> [] ]);
        
        
    }
    
    public function deleteFileTemplate(Request $request){
        
        $user_id = auth()->user()->id;
        $owner_id = User::getOwnerOfUser($user_id);

        // check if permission to do
        if(!User::checkPermission('delete-file-template')){
            return response()->json(config('constants.messages.permission_denied'), 400);
            exit();
        }
        
        $file_template_id = $request->query('file_template_id');
        
        $template = FilesTemplate::find($file_template_id);
        
        if(empty($template)){
            return response()->json(config('constants.messages.invalid_template'), 400);
            exit();
        }
        
        if($template->owner_id != $owner_id){
            return response()->json(config('constants.messages.invalid_access'), 400);
            exit();
        }
        
        FilesTemplate::find($file_template_id)->delete();
        
        return response()->json(['message' => 'Success', 'data'=> [] ]);
        
        
    }
    
    public function deleteFileTemplateFolder(Request $request){
        
        $user_id = auth()->user()->id;
        $owner_id = User::getOwnerOfUser($user_id);

        // check if permission to do
        if(!User::checkPermission('delete-file-template-folder')){
            return response()->json(config('constants.messages.permission_denied'), 400);
            exit();
        }
        
        $file_folder_id = $request->query('file_folder_id');
        
        $folder = FilesFolder::find($file_folder_id);
        
        if(empty($folder)){
            return response()->json(config('constants.messages.invalid_folder'), 400);
            exit();
        }
        
        // get template 
        $file_template_id = $folder->file_template_id;
        
        $template = FilesTemplate::find($file_template_id);
        
        if($template->owner_id != $owner_id){
            return response()->json(config('constants.messages.invalid_access'), 400);
            exit();
        }
        
        FilesFolder::find($file_folder_id)->delete();
        
        return response()->json(['message' => 'Success', 'data'=> [] ]);
        
        
    }
    
}