<?php

namespace App\Http\Controllers\Manufacturing;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Auth;
use App\Models\Workstation;
use App\Models\Machinery;
use Illuminate\Support\Facades\Validator;

class WorkstationController extends Controller
{
    // Fetch all workstations
    public function index(Request $request)
    {
        $query = Workstation::with('entry_by:id,name')->where('rolledback',0)
            ->where('rolledback',0);
        
        
        if ($request->has('search')) {
            $search = $request->input('search');
            $query->where(function($q) use ($search) {
                $q->where('name', 'like', '%' . $search . '%')
                  ->orWhere('location', 'like', '%' . $search . '%')
                  ->orWhere('capacity', 'like', '%' . $search . '%')
                //   ->orWhere('description', 'like', '%' . $search . '%')
                  ->orWhere('status', 'like', '%' . $search . '%');
            });
        }

        if ($request->has('status')) {
            $status = $request->input('status');
            $query->where('status', $status);
        }

        if ($request->has('is_active')) {
            $is_active = $request->input('is_active');
            $query->where('is_active', $is_active);
        }
        
        if ($request['specific_date']!='' && isset($request['specific_date'])) {

            $customDate = $request->specific_date;

            $query = $query->whereDate('date', $customDate);

        }

        if ($request['from_date']!='' && isset($request['to_date'])) {

            $fromDate = $request->from_date;

            $toDate = $request->to_date;

            // 'fromDate' and 'toDate'

            $query = $query->whereBetween('date', [$fromDate, $toDate]);

        }

        $count=$query->count();

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

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

        }else{
            $query = $query->orderby('id','desc');
        }
        
        $workstations=$query->skip($request['noofrec']*($request['currentpage']-1))->take($request['noofrec']??50)
                // ->orderBy('id','desc')
                ->get();

        return $response=[
            'success'=>true,
            'total'=>$count,
            'requisitions'=>$workstations,
            'message'=>'All Workstations Listed Successfully'
        ];
    }

    // Fetch a single workstation by ID
    public function show(Request $request)
    {
        $id= $request->id;
        $workstation = Workstation::with('entry_by:id,name')->where('id', $id)->first();
        if (!$workstation) {
            return response()->json(['error' => 'Workstation not found'], 404);
        }

        $machines = Machinery::where('warehouse_id', $id)->get();
        
        return $response = [
             'success' => true,
             'message' => 'Workstation detail fetched Successfully',
             'workstation' => $workstation,
             'machines' => $machines
         ];
         
        // return response()->json($workstation);
    }

    // Create a new workstation
    public function store(Request $request)
    {

        $check=Workstation::where('workstation_id',$request['workstation_id'])->first();
        if($check){
            return response()->json(['error' => 'Workstation ID already exists'], 400);
        }

        $request['status'] = 1; // Assuming new workstation is active
        // return $request;
        $id = Workstation::create([
            'workstation_id'=>$request->workstation_id,
            'name' => $request->name,
            'location' => $request->location,
            'capacity' => $request->capacity,
            'description' => $request->description,
            'status' => $request->status,
            'notes'=>$request->notes,
            'department'=>$request->department,
            'attachment'=>$request->attachment
        ]);

        // return response()->json(['workstation' => $id], 201);
        return $response=[
            'success'=>true,
            'workstation'=>$id,
            'message'=>'Workstation Created Successfully'
        ];
    }

    // Update an existing workstation
    public function update(Request $request)
    {

        $id= $request->id;

        $request['status'] = 1; 

        Workstation::where('id', $id) 
        ->update([
            'name' => $request->name,
            'location' => $request->location,
            'capacity' => $request->capacity,
            'description' => $request->remarks,
            'status' => $request->status,
            'attachment'=>$request->attachment
        ]);

        return response()->json(['message' => 'Workstation updated successfully']);
    }

    // Delete a workstation (soft delete by setting status to 0)
    public function destroy(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'id' => 'required',
        ]);
                                                                                                    
        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 400);
        }
        Workstation::where('id', $request['id'])->update(['rolledback' => 1]);

        return response()->json(['message' => 'Workstation deleted successfully','success'=>true]);
    }

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

        // Validate Item

        $validator=validator($request->all(),[
           'workstation_id'=>'required|integer',
           'is_active'=>'required|integer'
       ]);

       if ($validator->fails()) { 

           return [
               'success' => false, 
               'message' => $validator->errors()->first(),
           ];

       } else {

           try{

               $workstation =  Workstation::where('id',$request->input('workstation_id'))->first();

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

               $workstation->update();

               $response=[
                   'success'=>true,
                   'message'=>'Workstation Status Updated successfully.'
               ];

           } 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);

       }

   }
}
