<?php

namespace App\Libraries;

use App\Models\Key;
use App\Models\KeysTracking;
use App\Models\KeysAddition;
use App\Models\LoanableItem;
use App\Models\LoanableItemsTracking;
use App\Models\LoanableItemsAddition;
use App\Models\PicturesTemplate;
use App\Models\PicturesFolder;

class Generic {
    
    public function formatInputDate($date){
        
        if(empty($date)){
            return '';
        }
        
        return date('d-m-Y', strtotime($date));
        
    }
    
    
    /*
        This function will update keys total, on_hand, loaned, lost_damaged count 
    */
    public function updateKeyStats($key_id){
        
        $key = Key::find($key_id)->toArray();
        
        $key_tracking_obj = KeysTracking::where(['key_id'=>$key_id])->get();
        $trackings = (!empty($key_tracking_obj)) ? $key_tracking_obj->toArray() : [];
        
        $key_addition_obj = KeysAddition::where(['key_id'=>$key_id])->get();
        $additions = (!empty($key_addition_obj)) ? $key_addition_obj->toArray() : [];
        
        $total = $on_hand = $loaned = $lost_damaged = 0;
        
        // calculate total
        $total = $key['start_amount'];
        
        foreach($additions as $a){
            $total += $a['quantity'];
        }
        
        // calculate loaned
        $loaned = 0;
        foreach($trackings as $t){
            if($t['is_returned'] == 0 && $t['is_lost_damaged'] == 0){
                $loaned++;
            }
        }
        
        // calculate lost damaged
        $lost_damaged = 0;
        foreach($trackings as $t){
            if($t['is_returned'] == 0 && $t['is_lost_damaged'] == 1){
                $lost_damaged++;
            }
        }
        
        // calculate on hand
        $on_hand = $total - $loaned - $lost_damaged;
        
        $update_data = [
            'total' => $total,
            'on_hand' => $on_hand,
            'loaned' => $loaned,
            'lost_damaged' => $lost_damaged,
        ];
        
        Key::find($key_id)->update($update_data);
        
    }
    
    /*
        This function will update loanable items total, on_hand, loaned, lost_damaged count 
    */
    public function updateLoanableItemStats($loanable_item_id){
        
        $loanable_item = LoanableItem::find($loanable_item_id)->toArray();
        
        $loanable_item_tracking_obj = LoanableItemsTracking::where(['loanable_item_id'=>$loanable_item_id])->get();
        $trackings = (!empty($loanable_item_tracking_obj)) ? $loanable_item_tracking_obj->toArray() : [];
        
        $loanable_item_addition_obj = LoanableItemsAddition::where(['loanable_item_id'=>$loanable_item_id])->get();
        $additions = (!empty($loanable_item_addition_obj)) ? $loanable_item_addition_obj->toArray() : [];
        
        $total = $on_hand = $loaned = $lost_damaged = 0;
        
        // calculate total
        $total = $loanable_item['start_amount'];
        
        foreach($additions as $a){
            $total += $a['quantity'];
        }
        
        // calculate loaned
        $loaned = 0;
        foreach($trackings as $t){
            if($t['is_returned'] == 0 && $t['is_lost_damaged'] == 0){
                $loaned++;
            }
        }
        
        // calculate lost damaged
        $lost_damaged = 0;
        foreach($trackings as $t){
            if($t['is_returned'] == 0 && $t['is_lost_damaged'] == 1){
                $lost_damaged++;
            }
        }
        
        // calculate on hand
        $on_hand = $total - $loaned - $lost_damaged;
        
        $update_data = [
            'total' => $total,
            'on_hand' => $on_hand,
            'loaned' => $loaned,
            'lost_damaged' => $lost_damaged,
        ];
        
        LoanableItem::find($loanable_item_id)->update($update_data);
        
    }
    
    public function duplicatePictureTemplate($picture_template_id, $name = ''){
        
        $template = PicturesTemplate::find($picture_template_id);
        
        if(empty($template)){
            return response()->json(config('constants.messages.invalid_template'), 400);
            exit();
        }
        
        $template = $template->toArray();
        
        $update_criteria = [];
        
        // create template
        $new_template = PicturesTemplate::create(
            [
                'name' => (!empty($name)) ? $name : $template['name'], 
                'owner_id' => $template['owner_id'], 
                'created_by' => auth()->user()->id
            ]
        );
        
        $new_template_id = $new_template->id;
        
        // now create folders structure
        $folders = PicturesFolder::select(['id', 'name', 'order_number', 'picture', 'parent_id', 'picture_template_id'])->where(['picture_template_id'=>$picture_template_id])->get();
        
        if(!empty($folders)){
            
            $folders = $folders->toArray();
            $maping_array = array();
            
            foreach($folders as $f){
                
                if($f['parent_id'] == null){
                    
                    $new_folder = PicturesFolder::create(
                        [
                            'name' => $f['name'], 
                            'picture' => $f['picture'] ?? '', 
                            'order_number' => $f['order_number'], 
                            'path' => '',
                            'parent_id' => null,
                            'picture_template_id' => $new_template_id
                        ]
                    );
                    
                    $maping_array[$f['id']] = $new_folder->id;
                    
                }
                else{
                    
                    $new_folder = PicturesFolder::create(
                        [
                            'name' => $f['name'], 
                            'picture' => $f['picture'] ?? '', 
                            'order_number' => $f['order_number'], 
                            'path' => '',
                            'parent_id' => $maping_array[$f['parent_id']],
                            'picture_template_id' => $new_template_id
                        ]
                    );
                    
                    $maping_array[$f['id']] = $new_folder->id;
                    
                }
                
            }
            
        }
        
        return $new_template_id;
        
    }
    
    public function duplicateFileTemplate($file_template_id, $name = ''){
        
        $template = FilesTemplate::find($file_template_id);
        
        if(empty($template)){
            return response()->json(config('constants.messages.invalid_template'), 400);
            exit();
        }
        
        $template = $template->toArray();
        
        $update_criteria = [];
        
        // create template
        $new_template = FilesTemplate::create(
            [
                'name' => (!empty($name)) ? $name : $template['name'], 
                'owner_id' => $template['owner_id'], 
                'created_by' => auth()->user()->id
            ]
        );
        
        $new_template_id = $new_template->id;
        
        // now create folders structure
        $folders = FilesFolder::select(['id', 'name', 'order_number', 'picture', 'parent_id', 'file_template_id'])->where(['file_template_id'=>$file_template_id])->get();
        
        if(!empty($folders)){
            
            $folders = $folders->toArray();
            $maping_array = array();
            
            foreach($folders as $f){
                
                if($f['parent_id'] == null){
                    
                    $new_folder = FilesFolder::create(
                        [
                            'name' => $f['name'], 
                            'picture' => $f['picture'] ?? '', 
                            'order_number' => $f['order_number'], 
                            'path' => '',
                            'parent_id' => null,
                            'file_template_id' => $new_template_id
                        ]
                    );
                    
                    $maping_array[$f['id']] = $new_folder->id;
                    
                }
                else{
                    
                    $new_folder = FilesFolder::create(
                        [
                            'name' => $f['name'], 
                            'picture' => $f['picture'] ?? '', 
                            'order_number' => $f['order_number'], 
                            'path' => '',
                            'parent_id' => $maping_array[$f['parent_id']],
                            'file_template_id' => $new_template_id
                        ]
                    );
                    
                    $maping_array[$f['id']] = $new_folder->id;
                    
                }
                
            }
            
        }
        
        return $new_template_id;
        
    }
    
    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;
        
    }
    
}
    
?>