<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Service\ActivityService;
use Auth;
use App\Models\Warehouse;
use App\Models\Item;
use App\Models\WarehouseBin;
use App\Models\WarehouseRack;
use App\Models\WarehouseZone;

class WarehouseController extends Controller
{

    public function createUpdate(Request $request){
        // Validate Name
        $validator=validator($request->all(),[
           'name'=>'required|string',
           'warehouse_code'=>'required'
       ]);

       if ($validator->fails()) { 
           return [
               'success' => false, 
               'message' => $validator->errors()->first()
           ];
       } else {  
           $obj['warehouse_code']=$request['warehouse_code'];
           $obj['name']=ucwords($request['name']);
           $obj['branch_name']=$request['branch_name'];
           $obj['warehouse_type']=$request['warehouse_type'];
           $obj['capacity']=$request['capacity'];
           $obj['department']=$request['department'];
           $obj['warehouse_for']=$request['warehouse_for'];
           $obj['branch_name']=$request['branch_name'];
           $obj['gst_no']=$request['gst_no']??null;
           $obj['address']=$request['address'];
           $obj['city_id']=$request['city']??0;
           $obj['country_id']=$request['country']??0;
           $obj['state_id']=$request['state']??0;
           $obj['description']=$request['description'];

           if($request['id']>0){

               try{
                   
                   $warehouse=Warehouse::findOrFail($request['id']);
                   $warehouse->update($obj);

                   // Creating Activities
                   $activity=new ActivityService;
                   $activity->activityCreateUpdate('Warehouse',$warehouse['id'],'Updated');

               } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
                   // Return error message in JSON if ID not found
                   return response()->json(['message' => 'Invalid Id to update '], 404);
               }
           }else{
               $warehouse=Warehouse::create($obj);

               // Creating Activities
               $activity=new ActivityService;
               $activity->activityCreateUpdate('Warehouse',$warehouse['id'],'Created');
           }
           
           $response=[
               'success'=>true,
               'data'=>$warehouse,
               'message'=>($request['id'] > 0) ? "Warehouse Updated Successfully" : "Warehouse Created Successfully",
           ];

           return response()->json($response);
       }
    }


    public function list(Request $request)
    {
        $user=Auth::user();

        $warehouse= Warehouse::with('country:id,name','state:id,name','city:id,name');
        // ->where('organisation_id',$user['active_organisation'])

        
        if($request['search']!='' && isset($request['search']) && $request['search']!=null){
            $warehouse = $warehouse->where(function ($query) use ($request) {

                $query->where('name', 'LIKE', '%' . $request['search'] . '%')

                ->orWhere('warehouse_type', 'LIKE', '%' . $request['search'] . '%');
            });
        }

        if($request['is_active']!='' && isset($request['is_active']) && $request['is_active']!=null){
            $warehouse = $warehouse->where('is_active',$request['is_active']);
        }

        if($request['warehouse_type']!='' && isset($request['warehouse_type']) && $request['warehouse_type']!=null){
            $warehouse = $warehouse->where('warehouse_type',$request['warehouse_type']);
        }

        if($request['department']!='' && isset($request['department']) && $request['department']!=null){
            // Decode the JSON string into an array
            $decodedValues = json_decode($request['department'], true);
            $warehouse = $warehouse->whereJsonContains('department',$decodedValues);
        }
        
        $count=$warehouse->count();

        if(isset($request['sort_by']) && $request['sort_by']!='' && $request['sort_by']!=null){
                
            $sort_order=$request['sort_order']==1?'asc':'desc';

            $warehouse = $warehouse->orderby($request['sort_by'],$sort_order);

        }else{
            $warehouse = $warehouse->orderby('id','desc');
        }


        $warehouse=$warehouse->skip($request['noofrec']*($request['currentpage']-1))->take($request['noofrec']??50)
            // ->orderBy('id','desc')
            ->get();

        $response=[
            'success'=>true,
            'count'=>$count,
            'warehouse'=>$warehouse,
            'message'=>'Warehouse List Fetch Successfully'
        ];

        return response()->json($response, 200);
    }

    public function warehouseStatus(Request $request)
    {

        $validator=validator($request->all(),[
            'id'=>'required'
        ]);

        if ($validator->fails()) { 
            return [
                'success' => false, 
                'message' => $validator->errors()->first()
            ];
        } else {  

            try{

                $warehouse = Warehouse::findOrFail($request['id']);
                $warehouse['is_active']=$request['is_active'];
                $warehouse->update();

            } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
                // Return error message in JSON if ID not found
                return response()->json(['message' => 'Invalid Id to update '], 404);
            }

            $response=[
                'warehouse'=>$warehouse,
                'message'=>'Status Updated Successfully'
            ];

            return response()->json($response);
        }

    }

    public function warehouseDetails(Request $request){

        $user=Auth::user();

         // Validate Name
         $validator=validator($request->all(),[
            'warehouse_id'=>'required'
        ]);

        if ($validator->fails()) { 
            return [
                'success' => false, 
                'message' => $validator->errors()->first()
            ];
        } else {  
            $warehouse = Warehouse::where('id',$request['warehouse_id'])
                ->with('country:id,name','state:id,name','city:id,name')
                ->first();

            $item=Item::where('organisation_id',$user['active_organisation'])
                    ->where('is_disabled',0)
                    ->where('warehouse_id',$request['warehouse_id']);
             // Count all the items
             $item_count=$item->count();

             // Pagination
            $item=$item->skip($request['noofrec']*($request['currentpage']-1))->take($request['noofrec']??100)
                 ->orderBy('id','desc')
                 ->get();

            $zones=WarehouseZone::where('warehouse_id',$request['warehouse_id'])
                ->where('is_disabled',0)
                ->count();

            $racks=WarehouseRack::where('warehouse_id',$request['warehouse_id'])
                ->where('is_disabled',0)
                ->count();

            $bins=WarehouseBin::where('warehouse_id',$request['warehouse_id'])
                ->where('is_disabled',0)
                ->count();

            $response=[
                'success'=>true,
                'data'=>$warehouse,
                'item_count'=>$item_count,
                'items'=>$item,
                'no_of_zones'=>$zones,
                'no_of_racks'=>$racks,
                'no_of_bins'=>$bins
            ];

            return response()->json($response);
        }
    }

    public function status(Request $request){

        // Validate Item

        $validator=validator($request->all(),[

            'warehouse_id'=>'required|integer',

            'is_active'=>'required|integer'

        ]);

        if ($validator->fails()) { 

            return [

                'success' => false, 

                'message' => $validator->errors()->first(),

            ];

        } else {

            try{

                $warehouse =  Warehouse::where('id',$request->input('warehouse_id'))->first();

                $warehouse['is_active']=$request['is_active'];

                $warehouse->update();

                $response=[

                    'success'=>true,

                    'message'=>'Status Updated successfully.',

                    'data'=>$warehouse

                ];

            } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {

                // Return error message in JSON if ID not found

                return response()->json(['message' => 'Invalid Id found'], 404);

            }

            return response()->json($response);

        }

    }

}
