<?php

namespace App\Http\Controllers\Manufacturing;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class RequisitionController extends Controller
{
    public function index(Request $request)
    {
        $query = DB::table('requisition');

        // Apply filters based on request parameters
        if ($request->has('search')) {
            $search = $request->input('search');
            $query->where(function ($q) use ($search) {
                $q->where('order_id', 'LIKE', "%$search%")
                  ->orWhere('date', 'LIKE', "%$search%")
                  ->orWhere('warehouse', 'LIKE', "%$search%")
                  ->orWhere('status', 'LIKE', "%$search%");
            });
        }

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

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

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

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

    // Store a newly created requisition
    public function store(Request $request)
    {
        // $validator = Validator::make($request->all(), [
        //     'order_id' => 'required|max:255',
        //     'vendor' => 'required|max:255',
        //     'date' => 'required|date',
        //     'status' => 'required|max:50',
        //     'remarks' => 'nullable|string'
        // ]);

        // if ($validator->fails()) {
        //     return response()->json(['errors' => $validator->errors()], 400);
        // }

        // $requisitionId = DB::table('requisition')->insertGetId([
        //     'order_id' => $request->input('order_id'),
        //     'vendor' => $request->input('vendor'),
        //     'date' => $request->input('date'),
        //     'status' => $request->input('status'),
        //     'remarks' => $request->input('remarks'),
        //     'created_at' => now(),
        //     'updated_at' => now()
        // ]);
        
        // Handle file upload if there's an attachment
        if ($request->hasFile('attachment')) {
            $file = $request->file('attachment');
            $filename = time() . '_' . $file->getClientOriginalName();
            $filePath = $file->storeAs('attachments', $filename, 'public');
            // $validatedData['attachment'] = $filePath;
        }
        else{
            $filename="";
        }

        $requisitionId = DB::table('requisition')->insertGetId([
            'date' => $request->input('date'),
            'order_id' => $request->input('order'),
            'warehouse_id' => $request->input('warehouse_id'),
            'warehouse' => $request->input('warehouse'),
            'item' => $request->input('item'),
            // 'status' => $request->input('status'),
            'remarks' => $request->input('remarks'),
            'attachment' => $filename, 
            'created_at' => now(),
            'updated_at' => now()
            
        ]);

        foreach ($request->rows as $row) {
            DB::table('requisition_items')->insert([
                'requisition_id' => $requisitionId,
                'item_id' => $row['item_id'] ,
                'raw_material' => $row['raw_material'] ,
                'sku' => $row['sku'] ,
                'quantity' => $row['quantity'] ,
                'notes' => $row['remarks'] ,
                'created_at' => now(),
                'updated_at' => now()
            ]);
        }
    

        return response()->json(['message' => 'Requisition created successfully', 'id' => $requisitionId], 201);
    }

    // Display the specified requisition
    public function show(Request $request)
    {
        $id= $request->id;
        
        $requisition = DB::table('requisition')->where('id', $id)->first();
        $requisitionItems = DB::table('requisition_items')->where('requisition_id', $id)->get();

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

        return response()->json(['requisition' => $requisition, 'requisition_items' => $requisitionItems]);
    }

    // Requisition approval list
    public function requisition_approvals(Request $request, $id)
    {
        // $id= $request->requisition_id;
        $requisition = DB::table('requisition_approval')->where('requisition_id', $id)->first();

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

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


    public function approval_store(Request $request)
    {

        $date = date('Y-m-d');
        $approve_by="Rohan";
        $requisition_id = $request->input('requisition_id');
        $requisition_item_id = $request->input('requisition_item_id');
        $status = $request->input('status');

        $requisition = DB::table('requisition')->where('id', $requisition_id)->first();
        $warehouse_id= $requisition->warehouse_id;
        $order_id= $requisition->order_id;

            DB::table('requisition_approval')->insert([
                'requisition_id' => $request->input('requisition_id'),
                'date' => $date,
                'order_id' => $order_id,
                'item_id' => $request->input('item_id'),
                'item_name' => $request->input('item_name'),
                'approve_qty' => $request->input('quantity'),
                'approved_by' => $approve_by,
                'remarks' => $request->input('remarks'),
                'status' => $request->input('status'),
                'created_at' => now(),
                'updated_at' => now()
            ]);

        if($status=='Approve'){

            DB::table('stock_transactions')->insert([
                'warehouse_id' => $warehouse_id,
                'transaction_date' => $date,
                'item_id' => $request->input('item_id'),
                'inout' => 2,
                'transaction_type' => 9, // For production
                'reference_no' => $request->input('requisition_id'),
                'quantity' => $request->input('quantity'),
                // 'entrybyid' => $approve_by,
                'description' => $request->input('remarks'),
                'created_at' => now(),
                'updated_at' => now()
            ]);

            DB::table('stock_transactions')->insert([
                'warehouse_id' => "W005",
                'transaction_date' => $date,
                'item_id' => $request->input('item_id'),
                'inout' => 1, //
                'transaction_type' => 10, // For Store
                'reference_no' => $request->input('requisition_id'),
                'quantity' => $request->input('quantity'),
                // 'entrybyid' => $approve_by,
                'description' => $request->input('remarks'),
                'created_at' => now(),
                'updated_at' => now()
            ]);

             DB::table('requisition_items')
                 ->where('id', $requisition_item_id)
                 ->update([
                     'approved_qty' => $request->quantity,
                     'remarks' => $request->remarks,
                     'status' => 'Approved'
             ]);

        }
        else{
             DB::table('requisition_items')
                 ->where('id', $requisition_item_id)
                 ->update([
                     'remarks' => $request->remarks,
                     'status' => 'On Hold'
             ]);
        }



 $count= DB::table('requisition_items')
    ->where('requisition_id', $requisition_id)
    ->count();

 $approved_count= DB::table('requisition_items')
    ->where('requisition_id', $requisition_id)
    ->where('status', 'Approved')
    ->count();

if ($count==$approved_count) {
    $req_status="Approved";
}
elseif ($count>$approved_count) {
    $req_status="Partially Approved";
}
elseif ($approved_count==0) {
    $req_status="Pending";
}


 DB::table('requisition')
    ->where('id', $requisition_id)
    ->update([
        'status' => $req_status
    ]);


        return response()->json(['success' => true, 'message' => 'Requisition Approval created successfully'], 201);
   
        // return response()->json(['success' => false, 'message' => 'Failed to create Requisition Approval', 'error' => $e->getMessage()], 500);


    }

    // Update the specified requisition
    public function update(Request $request)
    {
        // $validator = Validator::make($request->all(), [
        //     'order_id' => 'required|max:255',
        //     'vendor' => 'required|max:255',
        //     'date' => 'required|date',
        //     'status' => 'required|max:50',
        //     'remarks' => 'nullable|string'
        // ]);

        // if ($validator->fails()) {
        //     return response()->json(['errors' => $validator->errors()], 400);
        // }

        $id= $request->id;
        
                // Handle file upload if there's an attachment
        if ($request->hasFile('attachment')) {
            $file = $request->file('attachment');
            $filename = time() . '_' . $file->getClientOriginalName();
            $filePath = $file->storeAs('attachments', $filename, 'public');
            // $validatedData['attachment'] = $filePath;
        }
        else{
               $requisition = DB::table('requisitions')->where('id', $id)->first();
              $filename = $requisition->attachment; // Default to existing filename
        }


        // Update the requisition details
        DB::table('requisition')->where('id', $id)->update([
            'order_id' => $request->input('order'),
            'date' => $request->input('date') ?? null,
            'warehouse_id' => $request->input('warehouse_id'),
            'warehouse' => $request->input('warehouse'),
            'status' => $request->input('status'),
            'remarks' => $request->input('remarks'),
            'attachment' => $filename, 
            'updated_at' => now()
        ]);

        DB::table('requisition_items')->where('requisition_id', $id)->delete();
        
        foreach ($request->rows as $row) {
            DB::table('requisition_items')->insert([
                'requisition_id' => $id,
                'item_id' => $row['item_id'] ,
                'raw_material' => $row['raw_material'] ,
                'sku' => $row['sku'] ,
                'quantity' => $row['quantity'] ,
                'notes' => $row['remarks'] ,
                'created_at' => now(),
                'updated_at' => now()
            ]);
        }
    


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

    // Remove the specified requisition
    public function destroy($id)
    {
        DB::table('requisition')->where('id', $id)->delete();
        DB::table('requisition_items')->where('requisition_id', $id)->delete();

        return response()->json(['message' => 'Requisition and its items deleted successfully']);
    }

    // Store a newly created requisition item
    public function storeItem(Request $request, $requisitionId)
    {
        $validator = Validator::make($request->all(), [
            'item_name' => 'required|max:255',
            'weight_per_pack' => 'required|numeric',
            'packet_quantity' => 'required|integer',
            'status' => 'required|max:50',
            'remarks' => 'nullable|string'
        ]);

        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 400);
        }

        DB::table('requisition_items')->insert([
            'requisition_id' => $requisitionId,
            'item_name' => $request->input('item_name'),
            'weight_per_pack' => $request->input('weight_per_pack'),
            'packet_quantity' => $request->input('packet_quantity'),
            'status' => $request->input('status'),
            'remarks' => $request->input('remarks'),
            'created_at' => now(),
            'updated_at' => now()
        ]);

        return response()->json(['message' => 'Requisition item created successfully'], 201);
    }

    // Update the specified requisition item
    public function updateItem(Request $request, $itemId)
    {
        $validator = Validator::make($request->all(), [
            'item_name' => 'required|max:255',
            'weight_per_pack' => 'required|numeric',
            'packet_quantity' => 'required|integer',
            'status' => 'required|max:50',
            'remarks' => 'nullable|string'
        ]);

        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 400);
        }

        DB::table('requisition_items')->where('id', $itemId)->update([
            'item_name' => $request->input('item_name'),
            'weight_per_pack' => $request->input('weight_per_pack'),
            'packet_quantity' => $request->input('packet_quantity'),
            'status' => $request->input('status'),
            'remarks' => $request->input('remarks'),
            'updated_at' => now()
        ]);

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

    // Remove the specified requisition item
    public function destroyItem($itemId)
    {
        DB::table('requisition_items')->where('id', $itemId)->delete();

        return response()->json(['message' => 'Requisition item deleted successfully']);
    }
}
