<?php

namespace App\Http\Controllers\Api\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 App\Models\ProductionOperation;
use App\Service\SequenceService;
use Illuminate\Support\Facades\Validator;
use Carbon\Carbon;

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('workstation_id', 'like', '%' . $search . '%')
                  ->orWhere('location', 'like', '%' . $search . '%')
                  ->orWhere('capacity', 'like', '%' . $search . '%')
                  ->orWhere('department', '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['sort_order']==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,
            'workstations'=>$workstations,
            'message'=>'All Workstations Listed Successfully'
        ];
    }

    // Fetch a single workstation by ID
    public function show(Request $request)
    {
        $id= $request->id;
        $today=Carbon::today()->format('Y-m-d');

        $workstation = Workstation::with('entry_by:id,name')->where('id', $id)->first();
        if (!$workstation) {
            return response()->json(['error' => 'Workstation not found'], 404);
        }

        $operations = ProductionOperation::with('machinery','production','operations')->where('workstation_id', $id)
            ->whereHas('production',function($query) use ($today){
                $query->where('date_time',$today);
            })->get();

        $machinery = ProductionOperation::with('machinery','production','operations')->where('workstation_id', $id)
            ->whereHas('production',function($query) use ($today){
                $query->where('date_time',$today);
            })->get();
        
        return $response = [
            'success' => true,
            'message' => 'Workstation detail fetched Successfully',
            'workstation' => $workstation,
            'machinery'=>$machinery,
            'operations' => $operations
        ];
         
    }

    // 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;

        $obj['workstation_id']=$request['workstation_id'];
        $obj['name']=$request['name'];
        $obj['location']=$request['location'];
        $obj['capacity']=$request['capacity'];
        $obj['description']=$request['description'];
        $obj['status']=$request['status'];
        $obj['notes']=$request['notes'];
        $obj['department']=$request['department'];
        $obj['attachment']=$request['attachment'];

        $workstation=Workstation::create($obj);

        $module='workstation';

        // Update Sequence
        $sequence=new SequenceService;
        $sequence->updateSequence($module);

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

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

        $validator=validator($request->all(),[
            'id'=>'required|integer',
        ]);
 
        if ($validator->fails()) { 
 
            return [
                'success' => false, 
                'message' => $validator->errors()->first(),
            ];
 
        } else {
            $request['status'] = 1; 

            $obj['workstation_id']=$request['workstation_id'];
            $obj['name']=$request['name'];
            $obj['location']=$request['location'];
            $obj['capacity']=$request['capacity'];
            $obj['description']=$request['description'];
            $obj['status']=$request['status'];
            $obj['notes']=$request['notes'];
            $obj['department']=$request['department'];
            $obj['attachment']=$request['attachment'];

            try{

                $workstation=Workstation::findOrFail($request['id']);

                $workstation->update($obj);

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

                // Return error message in JSON if ID not found
                return response()->json(['success'=>false,'message' => 'Invalid Id found'], 404);
            }

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

    // 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(),[
           '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('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(['success'=>false,'message' => 'Invalid Id found'], 404);
           }

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

       }

    }

    // Fetch all active Production Operations for a Workstation
    public function activeOperations(Request $request)
    {
        $validator=validator($request->all(),[
            'id'=>'required',
        ]);

        if ($validator->fails()) { 

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

        } else {
            $currentTime = now(); // current datetime

            $production_operation = ProductionOperation::where('workstation_id', $request['id'])
                ->where('start_datetime', '<=', $currentTime)
                ->where('end_datetime', '>=', $currentTime)
                ->with('machinery', 'production', 'operations');

            $count = $production_operation->count();

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

            return response()->json([
                'success' => true,
                'total' => $count,
                'production_operations' => $production_operation,
                'message' => 'Active production operations fetched successfully'
            ]);
        }
    }

    // Fetch all active Machinery for a Workstation
    public function activeMachinery(Request $request)
    {
        $validator=validator($request->all(),[
            'id'=>'required',
        ]);

        if ($validator->fails()) { 

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

        } else {

            $machinery = Machinery::where('workstation_id', $request['id'])
                ->where('status', 1);

            $count = $machinery->count();

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

            return response()->json([
                'success' => true,
                'total' => $count,
                'machinery' => $machinery,
                'message' => 'Active machinery fetched successfully'
            ]);
        }
    }
}
