<?php

namespace App\Http\Controllers\Api\Warehouse;

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

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

       if ($validator->fails()) { 
           return [
               'success' => false, 
               'message' => $validator->errors()->first()
           ];
       } else {  
           $obj['name']=$request['name'];
           $obj['warehouse_id']=$request['warehouse_id'];
           $obj['zone_no']=$request['zone_no']??0;
           $obj['zone_type']=$request['zone_type'];
           $obj['capacity']=$request['capacity']??0;
           $obj['no_of_racks']=$request['no_of_racks']??0;
           $obj['no_of_aisle']=$request['no_of_aisle']??0;
           $obj['level']=$request['level']??0;
           $obj['description']=$request['description']??0;

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

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

                   // Creating Activities
                   $activity=new ActivityService;
                   $activity->activityCreateUpdate('Warehouse Zones',$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=WarehouseZone::create($obj);

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

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

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

        $warehouse= WarehouseZone::with('warehouse');

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

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

                $query->where('name', '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->whereHas('warehouse',function($query) use ($decodedValues){
                $query->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,
            'data'=>$warehouse,
            'message'=>'Warehouse Zones List',
        ];

        return response()->json($response);
    }
    
    public function details(Request $request){
        $user=Auth::user();
        // Validate Name
        $validator=validator($request->all(),[
           'zone_id'=>'required'
       ]);

       if ($validator->fails()) { 
           return [
               'success' => false, 
               'message' => $validator->errors()->first()
           ];
       } else {  
            $warehouse= WarehouseZone::with('warehouse')
                ->where('id',$request['zone_id'])->first();

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

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

            $response=[
                'success'=>true,
                'data'=>$warehouse,
                'message'=>'Warehouse Zones Details',
                'no_of_racks'=>$racks,
                'no_of_bins'=>$bins
            ];

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

    }

    // Update status Active and In Active
    public function status(Request $request){

        // Validate Item

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

           'zone_id'=>'required|integer',

           'is_active'=>'required|integer'

       ]);

       if ($validator->fails()) { 

           return [

               'success' => false, 

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

           ];

       } else {

           try{

               $warehouse =  WarehouseZone::where('id',$request->input('zone_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);

       }

   }
}
