<?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;
use App\Models\Order;
use App\Models\OrderItem;
use Auth;

class OrderController extends Controller
{
    // Display a listing of the orders with search, pagination, and filter
    public function index(Request $request)
    {
        $query = Order::where('rolledback',0)->with('entry_by:id,name','customer');

        // 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('customer', 'LIKE', "%$search%")
                  ->orWhere('status', 'LIKE', "%$search%");
            });
        }

        if ($request->has('customer')) {
            $customer = $request->input('vendor');
            $query->where('customer', 'LIKE', "%$customer%");
        }

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

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

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

        return $response=[
            'success'=>true,
            'total'=>$count,
            'orders'=>$orders,
            'message'=>'All Orders Listed Successfully'
        ];

        
    }

    // Store a newly created order
    public function store(Request $request)
    {
  
        try {
            
            $order = Order::create([
                'order_id' => $request->input('order_id'),
                'customer_id' => $request->input('customer_id'),
                'customer' => $request->input('customer'),
                'deadline' => $request->input('deadline') ?? '',
                'date' => $request->input('date'),
                'remarks' => $request->input('remarks'),
                'attachment' => $request->input('attachment'),
            ]);

            foreach ($request->rows as $row) {
                OrderItem::create([
                    'order_id' => $order['id'],
                    'item_id' => $row['item_id'] ,
                    'item_name' => $row['item_name'] ,
                    'hsn_code' => $row['hsn_code'] ,
                    'quantity' => $row['quantity'] ,
                    'unit' => $row['unit'] ,
                    'notes' => $row['notes'] ,
                    'deadline' => $row['deadline'] ,
                    'created_at' => now(),
                    'updated_at' => now()
                ]);
            }
            
            return response()->json(['success' => true, 'message' => 'Order created successfully'], 201);

        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['success' => false, 'message' => 'Failed to create order', 'error' => $e->getMessage()], 500);
        }

        return response()->json(['message' => 'Order created successfully', 'order' => $order], 201);
    }

    // Display the specified order
    public function show(Request $request)
    {
        $validator=validator($request->all(),[
            'id'=>'required',
        ]);
        if ($validator->fails()) { 

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

        } else {

            $id= $request->id;
            
            $order = Order::where('id', $id)->with('items','entry_by:id,name','customer')->first();

            $orderItems = OrderItem::where('order_id', $id)->get();

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

            return response()->json(['order' => $order, 'order_items' => $orderItems]);
        }
    }

    // Update the specified order
    public function update(Request $request)
    {
        
       $id= $request->id;

       try {
        
        // Update the order
        Order::where('id', $id)->update([
            'order_id' => $request->input('order_id'),
            'customer_id' => $request->input('customer_id'),
            'customer' => $request->input('customer'),
            'deadline' => $request->input('deadline') ?? '',
            'date' => $request->input('order_date'),
            'remarks' => $request->input('remarks'),
            'attachment' => $attachment, 
        ]);

        // Delete existing order items
        OrderItem::where('order_id', $id)->delete();

        // Insert new order items
        foreach ($request->rows as $row) {
            OrderItem::create([
                'order_id' => $id,
                'item_id' => $row['item_id'],
                'item_name' => $row['item_name'],
                'hsn_code' => $row['hsn_code'],
                'quantity' => $row['quantity'],
                'unit' => $row['unit'],
                'notes' => $row['notes'],
                'deadline' => $row['deadline']
            ]);
        }

        return response()->json(['success' => true, 'message' => 'Order updated successfully'], 200);
        
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['success' => false, 'message' => 'Failed to update order', 'error' => $e->getMessage()], 500);
        }
    }

    // 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);
        }
        Order::where('id', $request['id'])->update(['rolledback' => 1]);

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

    // Store a newly created order item
    public function storeItem(Request $request, $orderId)
    {
        $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('order_items')->insert([
            'order_id' => $orderId,
            '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' => 'Order item created successfully'], 201);
    }

    // Update the specified order 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('order_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' => 'Order item updated successfully']);
    }

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

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