<?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\AssetsAssigneesUsersType;
use App\Models\Key;
use App\Models\KeysAddition;
use App\Models\KeysTracking;
use App\Models\KeysPicture;
use App\Models\LoanableItem;
use App\Models\LoanableItemsAddition;
use App\Models\LoanableItemsPicture;
use App\Models\LoanableItemsSerialsNumber;

use App\Models\UsersRole;
use App\Models\User;
use Carbon\Carbon;

use App\Libraries\Generic;


class AssetsController extends Controller
{
    
    protected $generic;
    
    public function __construct(){
        
        $this->generic = new Generic();
        
    }
    
    public function getAssetsAssigneesUsersTypes(){

        $types = AssetsAssigneesUsersType::all();

        return response()->json(['data' => $types]);

    }
    
    // ---------------------------------------------------------------------------------
    // ---------------------------------------------------------------------------------
    // ------------------------  Keys Related functions Start --------------------------
    // ---------------------------------------------------------------------------------
    // ---------------------------------------------------------------------------------

    public function key(Request $request){
        
        // echo "<pre>";
        // print_r($request->all());
        // exit();

        $user_id = auth()->user()->id;
        $owner_id = User::getOwnerOfUser($user_id);

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

        $validator = Validator::make($request->all(), [
            'name' => 'required',
            'asset_assignee_user_type_id' => 'required|numeric|min:1|max:3'
        ]);

        if ($validator->fails()) {
            return response()->json($validator->errors(), 400);
        }

        $data = [
            'name' => $request->name,
            'model_number' => $request->model_number ?? '',
            'asset_assignee_user_type_id' => $request->asset_assignee_user_type_id,
            'description' => $request->description ?? '',
            'replacement_cost' => $request->replacement_cost ?? 0,
            'track_inventory' => $request->track_inventory ?? 0,
            'property_id' => $request->property_id ?? null,
            'owner_id' => $owner_id,
            'creator_id' => $user_id
        ];
        
        $update_criteria = [];
        if(!empty($request->id)){
            $update_criteria['id'] = $request->id;
        }
        else{
            $update_criteria['id'] = 0;
            $data['start_amount'] = $request->start_amount ?? 1;
            $data['total'] = $request->start_amount ?? 1;
            $data['on_hand'] = $request->start_amount ?? 1;
        }

        $key = Key::updateOrCreate(
            $update_criteria, 
            $data
        );

        $key_id = $key->id;
        
        // pictures
        $pictures = $request->pictures ?? [];

        foreach($pictures as $p){
            
            $update_criteria = [];
            if(!empty($p['id'])){
                $update_criteria['id'] = $p['id'];
            }
            else{
                $update_criteria['id'] = 0;
            }
            
            KeysPicture::updateOrCreate($update_criteria, [
                'picture' => $p['picture'],
                'key_id' => $key_id,
                'order_number' => $p['order_number']
            ]);
        }

        return response()->json(['message' => 'Added Successfully', 'data'=> $key_id ]);

    }
    
    public function getKey(Request $request)
    {
        
        $user_id = auth()->user()->id;
        $owner_id = User::getOwnerOfUser($user_id);
        
        // check if permission to do
        if(!User::checkPermission('get-key')){
            return response()->json(config('constants.messages.permission_denied'), 400);
            exit();
        }
        
        $key_id = $request->query('key_id');
        
        $key = Key::getSingleKey($key_id);
                
        return response()->json(['data' => $key]);
    }
    
    public function getMyKeys()
    {
        
        $user_id = auth()->user()->id;
        $owner_id = User::getOwnerOfUser($user_id);

        // check if permission to do
        if(!User::checkPermission('get-my-keys')){
            return response()->json(config('constants.messages.permission_denied'), 400);
            exit();
        }
        
        $keys = Key::getKeysByOwnerId($owner_id);
                
        return response()->json(['data' => $keys]);
    }
    
    public function addKeyQuantity(Request $request){
        
        // echo "<pre>";
        // print_r($request->all());
        // exit();

        $user_id = auth()->user()->id;
        $owner_id = User::getOwnerOfUser($user_id);

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

        $validator = Validator::make($request->all(), [
            'key_id' => 'required|numeric',
            'quantity' => 'required|numeric|min:1'
        ]);

        if ($validator->fails()) {
            return response()->json($validator->errors(), 400);
        }
        
        $key_id = $request->key_id;
        $quantity = $request->quantity;
        
        // get key data
        $key = Key::find($key_id);
        
        if(empty($key)){
            return response()->json(['message' => 'No Key Found']);
        }
        else{
            $key = $key->toArray();
        }

        $data = [
            'key_id' => $request->key_id,
            'quantity' => $request->quantity,
            'user_id' => $user_id
        ];
        
        $update_criteria['id'] = 0;
            
        KeysAddition::updateOrCreate(
            $update_criteria, 
            $data
        );
        
        // now update quantity in keys table
        $data = [
            'total' => $key['total'] + $quantity,
            'on_hand' => $key['on_hand'] + $quantity,
        ];
        
        Key::where(['id' => $key_id])->update($data);

        return response()->json(['message' => 'Quantity Successfully Updated', 'data'=> [] ]);

    }
    
    public function deleteKey(Request $request)
    {
        
        $user_id = auth()->user()->id;
        $owner_id = User::getOwnerOfUser($user_id);
        
        // check if permission to do
        if(!User::checkPermission('delete-key')){
            return response()->json(config('constants.messages.permission_denied'), 400);
            exit();
        }
        
        $key_id = $request->query('key_id');
        
        $key = Key::getSingleKey($key_id);
        
        if($owner_id == $key->owner_id){
            Key::find($key_id)->delete();
        }
                
        return response()->json(['data' => ['Deleted']]);
    }
    
    
    
    // ---------------------------------------------------------------------------------
    // ---------------------------------------------------------------------------------
    // ------------------------  Keys Related functions End ----------------------------
    // ---------------------------------------------------------------------------------
    // ---------------------------------------------------------------------------------
    
    
    // ---------------------------------------------------------------------------------
    // ---------------------------------------------------------------------------------
    // ------------------  Loanable Items Related functions Start ----------------------
    // ---------------------------------------------------------------------------------
    // ---------------------------------------------------------------------------------

    public function loanableItem(Request $request){
        
        // echo "<pre>";
        // print_r($request->all());
        // exit();
        
        $user_id = auth()->user()->id;
        $owner_id = User::getOwnerOfUser($user_id);
        
        // check if permission to do
        if(!User::checkPermission('add-edit-loanable-item')){
            return response()->json(config('constants.messages.permission_denied'), 400);
            exit();
        }
        
        $validator = Validator::make($request->all(), [
            'name' => 'required',
            'asset_assignee_user_type_id' => 'required|numeric|min:1|max:3'
        ]);

        if ($validator->fails()) {
            return response()->json($validator->errors(), 400);
        }
        
        $data = [
            'name' => $request->name,
            'asset_assignee_user_type_id' => $request->asset_assignee_user_type_id,
            'description' => $request->description ?? '',
            'replacement_cost' => $request->replacement_cost ?? 0,
            'track_inventory' => $request->track_inventory ?? 0,
            'property_id' => $request->property_id ?? null,
            'owner_id' => $owner_id,
            'creator_id' => $user_id
        ];
        
        $update_criteria = [];
        if(!empty($request->id)){
            $update_criteria['id'] = $request->id;
        }
        else{
            $update_criteria['id'] = 0;
            $data['start_amount'] = $request->start_amount ?? 1;
            $data['total'] = $request->start_amount ?? 1;
            $data['on_hand'] = $request->start_amount ?? 1;
        }
        
        $loanable_item = LoanableItem::updateOrCreate(
            $update_criteria, 
            $data
        );
        
        $loanable_item_id = $loanable_item->id;
        
        // pictures
        $pictures = $request->pictures ?? [];
        
        foreach($pictures as $p){
            
            $update_criteria = [];
            if(!empty($p['id'])){
                $update_criteria['id'] = $p['id'];
            }
            else{
                $update_criteria['id'] = 0;
            }
            
            LoanableItemsPicture::updateOrCreate($update_criteria, [
                'picture' => $p['picture'],
                'loanable_item_id' => $loanable_item_id,
                'order_number' => $p['order_number']
            ]);
        }
        
        return response()->json(['message' => 'Added Successfully', 'data'=> $loanable_item_id ]);
        
    }
    
    public function getLoanableItem(Request $request)
    {
        
        $user_id = auth()->user()->id;
        $owner_id = User::getOwnerOfUser($user_id);
        
        // check if permission to do
        if(!User::checkPermission('get-loanable-item')){
            return response()->json(config('constants.messages.permission_denied'), 400);
            exit();
        }
        
        $loanable_item_id = $request->query('loanable_item_id');
        
        $loanable_item = LoanableItem::getSingleLoanableItem($loanable_item_id);
                
        return response()->json(['data' => $loanable_item]);
    }
    
    public function getMyLoanableItems()
    {
        
        $user_id = auth()->user()->id;
        $owner_id = User::getOwnerOfUser($user_id);

        // check if permission to do
        if(!User::checkPermission('get-my-loanable-items')){
            return response()->json(config('constants.messages.permission_denied'), 400);
            exit();
        }
        
        $loanable_items = LoanableItem::getLoanableItemsByOwnerId($owner_id);
                
        return response()->json(['data' => $loanable_items]);
    }
    
    public function addLoanableItemQuantity(Request $request){
        
        // echo "<pre>";
        // print_r($request->all());
        // exit();

        $user_id = auth()->user()->id;
        $owner_id = User::getOwnerOfUser($user_id);

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

        $validator = Validator::make($request->all(), [
            'loanable_item_id' => 'required|numeric',
            'quantity' => 'required|numeric|min:1'
        ]);

        if ($validator->fails()) {
            return response()->json($validator->errors(), 400);
        }
        
        $loanable_item_id = $request->loanable_item_id;
        $quantity = $request->quantity;
        
        // get loanable_item data
        $loanable_item = LoanableItem::find($loanable_item_id);
        
        if(empty($loanable_item)){
            return response()->json(['message' => 'No Loanable Item Found']);
        }
        else{
            $loanable_item = $loanable_item->toArray();
        }

        $data = [
            'loanable_item_id' => $request->loanable_item_id,
            'quantity' => $request->quantity,
            'user_id' => $user_id
        ];
        
        $update_criteria['id'] = 0;
            
        LoanableItemsAddition::updateOrCreate(
            $update_criteria, 
            $data
        );
        
        // now update quantity in loanable items table
        $data = [
            'total' => $loanable_item['total'] + $quantity,
            'on_hand' => $loanable_item['on_hand'] + $quantity,
        ];
        
        LoanableItem::where(['id' => $loanable_item_id])->update($data);

        return response()->json(['message' => 'Quantity Successfully Updated', 'data'=> [] ]);

    }
    
    public function deleteLoanableItem(Request $request)
    {
        
        $user_id = auth()->user()->id;
        $owner_id = User::getOwnerOfUser($user_id);
        
        // check if permission to do
        if(!User::checkPermission('delete-loanable-item')){
            return response()->json(config('constants.messages.permission_denied'), 400);
            exit();
        }
        
        $loanable_item_id = $request->query('loanable_item_id');
        
        $loanable_item = LoanableItem::getSingleLoanableItem($loanable_item_id);
        
        if($owner_id == $loanable_item->owner_id){
            LoanableItem::find($loanable_item_id)->delete();
        }
                
        return response()->json(['data' => ['Deleted']]);
    }
    
    public function addLoanableItemSerialNumber(Request $request){
        
        // echo "<pre>";
        // print_r($request->all());
        // exit();

        $user_id = auth()->user()->id;
        $owner_id = User::getOwnerOfUser($user_id);

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

        $validator = Validator::make($request->all(), [
            'loanable_item_id' => 'required|numeric',
            'serial_number' => 'required'
        ]);

        if ($validator->fails()) {
            return response()->json($validator->errors(), 400);
        }
        
        $loanable_item_id = $request->loanable_item_id;
        $quantity = $request->quantity;
        
        // get loanable_item data
        $loanable_item = LoanableItem::find($loanable_item_id);
        
        if(empty($loanable_item)){
            return response()->json(['message' => 'No Loanable Item Found']);
        }
        
        if($owner_id == $loanable_item->owner_id){
            
            // $serial_numbers = $request->serial_numbers;
            
            // foreach($serial_numbers as $s){
                
            //     $data = [
            //         'loanable_item_id' => $request->loanable_item_id,
            //         'serial_number' => $s,
            //         'creator_id' => $user_id
            //     ];
                
            //     $update_criteria['id'] = 0;
                    
            //     LoanableItemsSerialsNumber::updateOrCreate(
            //         $update_criteria, 
            //         $data
            //     );
                
            // }
            
            $serial_number = $request->serial_number;
            
            $data = [
                'loanable_item_id' => $request->loanable_item_id,
                'serial_number' => $serial_number,
                'creator_id' => $user_id
            ];
            
            $update_criteria['id'] = 0;
            
            LoanableItemsSerialsNumber::updateOrCreate(
                $update_criteria, 
                $data
            );
            
            
        }
        
        return response()->json(['message' => 'Successfully Added', 'data'=> [] ]);
        
    }
    
    // ---------------------------------------------------------------------------------
    // ---------------------------------------------------------------------------------
    // ------------------  Loanable Items Related functions End ------------------------
    // ---------------------------------------------------------------------------------
    // ---------------------------------------------------------------------------------
    


}