<?php

namespace App\Http\Controllers\Api\Manufacturing;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use App\Models\Batch;
use App\Models\Production;
use Carbon\Carbon;
use App\Service\SequenceService;

class BatchesController extends Controller
{
    public function index(Request $request)
    {
        $query = Batch::where('rolledback',0)
            ->with('entry_by:id,name');

        if ($request->has('search')) {
            $search = $request->input('search');
            $query->where(function($q) use ($search) {
                $q->where('date', 'like', '%' . $search . '%')
                  ->orWhere('batch_number', 'like', '%' . $search . '%')
                  ->orWhere('batches_id', 'like', '%' . $search . '%')
                  ->orWhere('notes', '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['custom_date']!='' && isset($request['custom_date'])) {

            $customDate = $request->custom_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();

        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');
        }
        
        $batches=$query->skip($request['noofrec']*($request['currentpage']-1))->take($request['noofrec']??50)
                // ->orderBy('id','desc')
                ->get();

        return $response=[
            'success'=>true,
            'total'=>$count,
            'batches'=>$batches,
            'message'=>'All Batches Listed Successfully'
        ];
    
    }

    // Store a newly created machinery item
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'batch_number' => 'required',
           
        ]);
        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 400);
        }

        $obj['date']=$request['date'];
        $obj['batches_id']=$request['batches_id'];
        $obj['batch_number']=$request['batch_number'];
        $obj['notes']=$request['notes'];
        $obj['status']=$request['status'];

        $batch=Batch::create($obj);

        $module='batches';

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


        return response()->json(['success'=>true,'message' => 'Batch created successfully','batch'=>$batch], 200);
    }

    // Display the specified machinery item
    public function show(Request $request)
    {
        $id= $request->id;

        $today=Carbon::today()->format('Y-m-d');

        $batch = Batch::where('id', $id)
                     ->first();

        if (!$batch) {
            return response()->json(['message' => 'Batch not found'], 404);
        }

        $production=Production::with('bom','item','order','entry_by','bom.item')
            ->where('date_time',$today)
            ->where('batch_id',$request['id'])
            ->get();

        return $response = [
            'success' => true,
            'message' => 'Batches detail fetched Successfully',
            'productions' => $production,
            'batch'=>$batch
        ];
    }

    // Update the specified machinery item
    public function update(Request $request)
    {

        $id= $request->id;

        $obj['date']=$request['date'];
        $obj['batches_id']=$request['batches_id'];
        $obj['batch_number']=$request['batch_number'];
        $obj['notes']=$request['notes'];
        $obj['status']=$request['status'];

        $batch=Batch::where('id',$request['id'])->first();
        $batch->update($obj);

        // if ($affected === 0) {
        //     return response()->json(['success'=>false,'message' => 'Batch not found or no changes made'], 404);
        // }

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

    // Remove the specified machinery item
    public function destroy($id)
    {
        $affected = DB::table('machinery')->where('machine_id', $id)->delete();

        if ($affected === 0) {
            return response()->json(['success'=>false,'message' => 'Machinery item not found'], 404);
        }

        return response()->json(['success'=>false,'message' => 'Machinery item deleted successfully']);
    }

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

        // Validate Item

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

       if ($validator->fails()) { 

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

       } else {

           try{

               $batch =  Batch::where('id',$request->input('batch_id'))->first();

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

               $batch->update();

               $response=[
                   'success'=>true,
                   'message'=>'Batch 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);

       }

   }
}
