<?php

namespace App\Http\Controllers\Api\cms;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\cms\ContainerDetail;

class InventroyController extends Controller
{
    public function cmsInventoryList(Request $request)
    {
        try {
            // Base query for container details with conditions
            $container_detail = ContainerDetail::where('status', '!=', 'completed')
                ->whereNotNull('pid_no')
                ->whereNull('did_no')
                ->where('order_id','>', 0)
                ->with('orders', 'orders.arrival', 'container_owner','block','yard');

            // Filtering based on 'pid_no'
            if (!empty($request->pid_no)) {
                $container_detail->where('pid_no', $request->pid_no);
            }

            // Filtering based on 'pid_no'
            if (!empty($request->container_condition)) {
                $container_detail->where('container_condition', 'LIKE', '%' . $request['container_condition'] . '%');
            }

            // Filtering based on 'pid_no'
            if (!empty($request->status)) {
                $container_detail->where('status', 'LIKE', '%' . $request['status'] . '%');
            }

            // Filtering based on 'date'
            if (!empty($request->date)) {
                $container_detail->whereDate('created_at', $request->date);
            }

            // Searching based on 'search' keyword (searching in container_id)
            if (!empty($request->search)) {

                $container_detail = $container_detail->where(function ($query) use ($request) {

                    $query->where('container_id', 'LIKE', '%' . $request['search'] . '%')
                        ->orWhere('container_condition', 'LIKE', '%' . $request['search'] . '%')
                        ->orWhere('pid_no', 'LIKE', '%' . $request['search'] . '%')
                        ->orWhereHas('container_owner', function ($query) use ($request) 
                            {
                                $query->where('display_name', 'LIKE', '%' . $request['search'] . '%');
                            });

                });
            }

            // Count total records for pagination
            $count = $container_detail->count();

            // Pagination parameters (with defaults)
            $noOfRec = $request->noofrec ?? 100;
            $currentPage = $request->currentpage ?? 1;

            // Sorting functionality
            if (!empty($request->sort_by)) {
                $sortOrder = ($request->sort_order == 1) ? 'asc' : 'desc';
                $container_detail = $container_detail->orderBy($request->sort_by, $sortOrder);
            } else {
                $container_detail = $container_detail->orderBy('id', 'desc');
            }

            // Apply pagination
            $container_detail = $container_detail->skip($noOfRec * ($currentPage - 1))
                ->take($noOfRec)
                ->get();

            // Attach additional container details if needed
            // foreach ($container_detail as $container) {
            //     // Ensure container_detail_ids exists
            //     if (!empty($container->container_detail_ids)) {
            //         // Fetch additional container details
            //         $container_details = ContainerDetail::whereIn('id', explode(',', $container->container_detail_ids))
            //             ->select('id', 'container_id')
            //             ->get();

            //         $container['container_details'] = $container_details;
            //     } else {
            //         $container['container_details'] = collect();
            //     }
            // }

            // Response structure
            return response()->json([
                'success' => true,
                'total' => $count,
                'data' => $container_detail,
            ], 200);
        } catch (\Exception $e) {
            // Handle unexpected errors
            return response()->json([
                'success' => false,
                'message' => 'Error occurred while processing the request',
                'error' => $e->getMessage(),
            ], 500);
        }
    }


    public function filter(Request $request)
    {
        $container_detail = ContainerDetail::where('status', '!=', 'completed')
            ->where('pid_no', '!=', null)
            ->where('did_no', null)
            ->with('orders', 'orders.arrival', 'orders.arrival.block:id,block_name', 'container_owner:id,company_name');

        if ($request['status'] != 0 && isset($request['status'])) {
            $container_detail = $container_detail->where('status', $request['status']);
        }

        if ($request['container_id'] != '' && isset($request['container_id'])) {
            $container_detail = $container_detail->where('container_id', $request['container_id']);
        }
        if ($request['container_condition'] != '' && isset($request['container_condition'])) {
            $container_detail = $container_detail->where('container_condition', $request['container_condition']);
        }

        $container_detail = $container_detail->get();

        $currentRoute = \Route::currentRouteName();
        // dd($container_detail);
        return view('inventory.index', compact('container_detail', 'currentRoute'));
    }
}
