<?php

namespace App\Http\Controllers\Api\cms;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Carbon\Carbon;
use App\Models\cms\PreArrivalDeparture;
use App\Models\cms\Order;
use App\Models\cms\ContainerOwner;
use App\Models\cms\LogisticProvider;
use App\Models\cms\Masters\ContainerType;
use App\Models\cms\Masters\VehicleType;
use App\Models\cms\Yard;
// use App\Models\cms\Document;
use App\Models\cms\ContainerDetail;
use App\Service\cms\ImageService;
use App\Service\cms\ContainerDetailsService;
use App\Service\cms\OrderService;
use App\Service\cms\PreArrivalService;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Validator;
use App\Service\cms\DocumentService;
use App\Service\cms\PreDepartureService;
use ActivityService;
use DB;

class PreArrivalController extends Controller
{

    public function index(Request $request)
    {
        try {
            // Base query for pre-arrival orders
            $pre_arrival = PreArrivalDeparture::where('status', 0)
                ->where('order_type', 'pre_arrival')
                ->with('entrybyid');


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

             // Filtering based on from date to date
            if (!empty($request->fromDate) && !empty($request->toDate)) {
                $pre_arrival->whereBetween('date', [$request->fromDate, $request->toDate]);
            }

            // Searching based on 'search' keyword ( container_id,)
           if (!empty($request->search)) {
                $search = $request->search;
                $pre_arrival->where(function ($query) use ($search) {
                    $query->whereExists(function ($subQuery) use ($search) {
                        $subQuery->select(DB::raw(1))
                            ->from('container_details')
                            ->whereRaw('FIND_IN_SET(container_details.id, pre_arrival_departure.container_detail_ids)')
                            ->where('container_details.container_id', 'like', '%' . $search . '%');
                    });
                });
            }

            // Counting total records
            $count = $pre_arrival->count();

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

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

            // Apply pagination
            $pre_arrival = $pre_arrival->skip($request['noofrec']*($request['currentpage']-1))->take($request['noofrec']??20)
                ->get();

            // Adding container details
            foreach ($pre_arrival as $container) {
                if (!empty($container->container_detail_ids)) {
                    $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,
                'message' => 'Pre Arrival List Fetched Successfully',
                'total' => $count,
                'data' => $pre_arrival,
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error occurred while processing the request',
                'error' => $e->getMessage()
            ], 200);
        }
    }

    public function details(Request $request)
    {
        try {
            // Validate the request
            $validator = Validator::make($request->all(), [
                'id' => 'required',
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->errors()->first(),
                    'data' => null
                ], 200);
            }

            // Fetch the pre-arrival record with related documents
            $pre_arrival = PreArrivalDeparture::with('items','port_details','vendor','ship_details','ship_details.country','trip_booking',
                'trip_booking.driver','trip_booking.vehicle','logistic_provider')
                ->findOrFail($request->id);

            // Get container details with relationships
            $container_details = ContainerDetail::whereIn('id', explode(',', $pre_arrival->container_detail_ids))
                ->with([
                    // 'images' => function ($query) {
                    //     $query->where('order_type', 'pre_arrival');
                    // },
                    'container_owner',
                    'container_types',
                    'logisticProvider',
                    'vehicleMaster',
                    'yard'
                ])
                ->get();

            return response()->json([
                'success' => true,
                'message' => 'Pre-arrival details fetched successfully',
                'data' => [
                    'pre_arrival' => $pre_arrival,
                    'container_details' => $container_details
                ]
            ], 200);
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return response()->json([
                'success' => false,
                'message' => 'Pre-arrival record not found',
                'data' => null
            ], 404);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'An unexpected error occurred',
                'error' => $e->getMessage(),
                'data' => null
            ], 500);
        }
    }



    public function store(Request $request)
    {
        try {
            // Get today's date
            $today = new Carbon();
            $request['date'] = $today->format('Y-m-d');

            // Creation of Services
            // $documentService = new DocumentService;
            $containerDetailService = new ContainerDetailsService;

            $orders = [];
            $prearrival = null; // Initialize prearrival variable

            // Pre Arrival order Type
            if ($request['order_type'] == 'pre_arrival') {
                $order_container_id = $containerDetailService->createOrderContainer($request);

                $prearrival = new PreArrivalService;
                $prearrival = $prearrival->savePreArrival($request);
                $prearrival['container_detail_ids'] = implode(',', $order_container_id);
                $prearrival->update();

                // Save Documents
                // $documentService->addDocument($request, $prearrival['id'], 'pre_arrival');

                $orders[] = $prearrival;
            }

            // Other Order Types (arrival, pre_departure, departure)
            if ($request['order_type'] == 'arrival') {
                if (!isset($request['order_container_id'])) {
                    $order_container_id = $containerDetailService->createOrderContainer($request);
                }

                $arrived = new PreArrivalService;
                $arrived = $arrived->saveArrival($request);
                $arrived['container_detail_ids'] = implode(',', $request['order_container_id'] ?? $order_container_id);
                $arrived->update();

                // $documentService->addDocument($request, $arrived['id'], 'arrival');

                $orders[] = $arrived;
            }

            if ($request['order_type'] == 'pre_departure') {
                $pre_departure = new PreDepartureService;

                if (isset($request['order_container_id'])) {
                    $order_container_id = $containerDetailService->updateContainerDetail($request);

                    foreach ($request['order_container_id'] as $key => $value) {
                        $container_detail = ContainerDetail::where('id', $request['order_container_id'][$key])->first();
                        $container_detail['status'] = "ongoing";
                        $container_detail->update();
                    }
                } else {
                    $order_container_id = $containerDetailService->createOrderContainer($request);
                }

                $pre_departure = $pre_departure->savePreDeparture($request);
                $pre_departure['container_detail_ids'] = implode(',', $request['order_container_id']);
                $pre_departure->update();

                // $documentService->addDocument($request, $pre_departure['id'], 'pre_departure');

                $orders[] = $pre_departure;
            }

            if ($request['order_type'] == 'departure') {
                $departure = new PreDepartureService;

                if (isset($request['order_container_id'])) {
                    $order_container_id = $containerDetailService->updateContainerDetail($request);

                    foreach ($request['order_container_id'] as $key => $value) {
                        $container_detail = ContainerDetail::where('id', $request['order_container_id'][$key])->first();
                        $container_detail['status'] = "process";
                        $container_detail->update();
                    }
                } else {
                    $order_container_id = $containerDetailService->createOrderContainer($request);
                }

                $departure = $departure->saveDeparture($request);
                $departure['container_detail_ids'] = implode(',', $request['order_container_id']);
                $departure->update();

                // $documentService->addDocument($request, $departure['id'], 'departure');

                $orders[] = $departure;
            }

            return response()->json([
                'success' => true,
                'total' => $prearrival ? 1 : 0, // Avoid calling count() on an object
                'data' => [
                    'prearrival' => $prearrival // Include the prearrival data in the response
                ]
            ], 201);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error occurred while processing the request',
                'error' => $e->getMessage()
            ], 500);
        }
    }



    public function cancelPreArrival(Request $request)
    {
        //  Validate Input Data
        $validator = Validator::make($request->all(), [
            'id' => 'required', // Ensure ID is required and must be an integer
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => $validator->errors()->first(),
                'data' => null,
            ], 422);
        }

        try {
            // Find the Pre-Arrival Record
            $pre_arrival = PreArrivalDeparture::find($request->id);
            if (!$pre_arrival) {
                return response()->json([
                    'success' => false,
                    'message' => 'Pre Arrival record not found.',
                    'data' => null,
                ], 404);
            }

            //  Roll Back Container Details
            $container_details = ContainerDetail::whereIn('id', explode(',', $pre_arrival->container_detail_ids))->get();
            foreach ($container_details as $detail) {
                $detail->delete();
            }

            // Roll Back Documents
            // $document = Document::where('user_type', 'pre_arrival')->where('user_id', $pre_arrival->id)->first();
            if ($document) {
                $attachmentPath = public_path($document->attachment);
                if (file_exists($attachmentPath)) {
                    unlink($attachmentPath); // Delete the file
                }
                $document->delete();
            }

            // Delete Pre-Arrival Record
            $pre_arrival->delete();

            // Return Response with Total and Data
            return response()->json([
                'message' => 'Pre Arrival canceled successfully.',
                'success' => true,
                'total' => 1, // Since one record is deleted
                'data' => $pre_arrival, // Return the deleted record details

            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'An error occurred while canceling pre-arrival.',
                'error' => $e->getMessage(),
                'data' => null,
            ], 500);
        }
    }


    public function update(Request $request)
    {
        //Validate Input Data
        $validator = Validator::make($request->all(), [
            'id' => 'required', // Ensure ID is required and must be an integer
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => $validator->errors()->first(),
                'data' => null,
            ], 422);
        }

        try {
            //  Find the Pre-Arrival Record
            $pre_arrival = PreArrivalDeparture::where('id', $request->id)
                // ->with('documents')
                ->first();

            if (!$pre_arrival) {
                return response()->json([
                    'success' => false,
                    'message' => 'Pre Arrival record not found.',
                    'data' => null,
                ], 404);
            }

            // Fetch Related Data
            $container_details = ContainerDetail::whereIn('id', explode(',', $pre_arrival->container_detail_ids))
            ->with([
                // 'images' => function ($query) {
                //     $query->where('order_type', 'pre_arrival');
                // },
                'container_owner',
                'container_types',
                'logisticProvider',
                'vehicleMaster',
                'yard'
            ])
            ->get();

        return response()->json([
            'success' => true,
            'message' => 'Pre-arrival details fetched successfully',
            'data' => [
                'pre_arrival' => $pre_arrival,
                'container_details' => $container_details
            ]
        ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'An error occurred while fetching pre-arrival details.',
                'error' => $e->getMessage(),
                'data' => null,
            ], 500);
        }
    }





    // public function approveCreate(Request $request)
    // {
    //     // Validate Input Data
    //     $validator = validator($request->all(), [
    //         'pre_arrival_id' => 'required',
    //     ]);

    //     if ($validator->fails()) {
    //         return response()->json([
    //             'success' => false,
    //             'message' => $validator->errors()->first(),
    //         ], 422);
    //     }

    //     try {
    //         // Fetch Pre-Arrival Data
    //         $pre_arrival = PreArrivalDeparture::with('documents')
    //             ->findOrFail($request->pre_arrival_id);

    //         $container_details = ContainerDetail::whereIn('id', explode(',', $pre_arrival['container_detail_ids']))->get();

    //         $containerOwners = ContainerOwner::where('status', 0)->get();
    //         $containertype = ContainerType::where('status', 0)->get();
    //         $logisticProviders = LogisticProvider::where('status', 0)->get();
    //         $vehicleMaster = VehicleType::where('status', 0)->get();
    //         $yards = Yard::where('status', 0)->get();

    //         return response()->json([
    //             'success' => true,
    //             'message' => 'Pre-arrival data retrieved successfully.',
    //             'data' => [
    //                 'pre_arrival' => $pre_arrival,
    //                 'container_details' => $container_details,
    //                 'containerOwners' => $containerOwners,
    //                 'containertype' => $containertype,
    //                 'logisticProviders' => $logisticProviders,
    //                 'vehicleMaster' => $vehicleMaster,
    //                 'yards' => $yards,
    //             ],
    //         ], 200);
    //     } catch (\Exception $e) {
    //         return response()->json([
    //             'success' => false,
    //             'message' => 'An error occurred during approval: ' . $e->getMessage(),
    //         ], 500);
    //     }
    // }




    // public function moveToArrived(Request $request, $id)
    // {
    //     $today = Carbon::now();
    //     $request['date'] = $today->format('Y-m-d');

    //     try {
    //         $pre_arrival = PreArrivalDeparture::findOrFail($request['pre_arrival_id']);

    //         // Update Containers
    //         $containerDetailService = new ContainerDetailsService;
    //         $order_container_id = $containerDetailService->updateContainerDetail($request);

    //         // Save Arrival
    //         $arrivedservice = new PreArrivalService;
    //         $arrived = $arrivedservice->saveArrival($request);
    //         $arrived['container_detail_ids'] = implode(',', $order_container_id);
    //         $arrived->update();

    //         // Update Pre-Arrival Status
    //         $pre_arrival->update(['status' => 1]);

    //         // Save Documents if provided
    //         if ($request->has('document_id')) {
    //             foreach ($request['document_id'] as $documentId) {
    //                 $doc = Document::find($documentId);
    //                 if ($doc) {
    //                     Document::create([
    //                         'user_type' => 'arrival',
    //                         'user_id' => $arrived['id'],
    //                         'document_name' => $doc['document_name'],
    //                         'attachment' => $doc['attachment'],
    //                         'extension' => $doc['extension'],
    //                     ]);
    //                 }
    //             }
    //         }

    //         return response()->json([
    //             'success' => true,
    //             'message' => 'Order moved to Arrived successfully.',
    //             'data' => [
    //                 'arrived' => $arrived,
    //                 'pre_arrival' => $pre_arrival,
    //             ],
    //         ], 200);
    //     } catch (\Exception $e) {
    //         return response()->json([
    //             'success' => false,
    //             'message' => 'An error occurred: ' . $e->getMessage(),
    //         ], 500);
    //     }
    // }


    // public function backToArrival(Request $request, $id)
    // {
    //     $arrived = PreArrivalDeparture::where('id', $id)
    //         ->where('order_type', 'arrival')->first();

    //     if ($arrived) {
    //         // Update the arrived record
    //         $arrived->status = 0;
    //         $arrived->reject_reason = $request->input('reason');
    //         $arrived->update();

    //         // Prepare the response data (total count and data)
    //         $yards = $arrived;
    //         $count = 1;

    //         // Return a JSON response with success message, total count, and data
    //         return response()->json([
    //             'success' => true,
    //             'total' => $count,
    //             'data' => $yards,
    //         ]);
    //     } else {
    //         // If the arrived record is not found, return an error message
    //         return response()->json([
    //             'success' => false,
    //             'message' => 'Order not found',
    //             'total' => 0,
    //             'data' => [],
    //         ], 404);
    //     }
    // }


    //     public function approveCreate(Request $request)
    // {
    //     // Validate Input Data
    //     $validator = validator($request->all(), [
    //         'pre_arrival_id' => 'required|integer|exists:pre_arrival_departures,id',
    //         'yard_id' => 'required|integer|exists:yards,id',
    //         'container_types' => 'required|array',
    //         'stored_containers' => 'required|array',
    //     ]);

    //     if ($validator->fails()) {
    //         return response()->json([
    //             'success' => false,
    //             'message' => $validator->errors()->first(),
    //         ], 422);
    //     }

    //     try {
    //         // Fetch Pre-Arrival Data
    //         $pre_arrival = PreArrivalDeparture::with('documents')
    //             ->findOrFail($request->pre_arrival_id);

    //         $container_details = ContainerDetail::whereIn('id', explode(',', $pre_arrival['container_detail_ids']))->get();

    //         $containerOwners = ContainerOwner::where('status', 0)->get();
    //         $containertype = ContainerType::where('status', 0)->get();
    //         $logisticProviders = LogisticProvider::where('status', 0)->get();
    //         $vehicleMaster = VehicleType::where('status', 0)->get();
    //         $yards = Yard::where('status', 0)->get();

    //         // Calculate Total Capacity
    //         $container_types = $request->input('container_types', []);
    //         $stored_containers = $request->input('stored_containers', []);

    //         $total_capacity = 0;
    //         $containers_types = [];

    //         foreach ($container_types as $key => $value) {
    //             if (isset($value)) {
    //                 $container_type = ContainerType::findOrFail($value);

    //                 if ($container_type['type_size'] == 40) {
    //                     $total_capacity += $stored_containers[$key] ?? 0;
    //                 } elseif ($container_type['type_size'] == 20) {
    //                     $total_capacity += ($stored_containers[$key] ?? 0) / 2;
    //                 }

    //                 $containers_types[] = [
    //                     'id' => $key + 1,
    //                     'container_type' => $value,
    //                     'capacity' => $stored_containers[$key] ?? 0,
    //                     'stored_containers' => $stored_containers[$key] ?? 0,
    //                 ];
    //             }
    //         }

    //         // Ensure Capacity Does Not Exceed
    //         if (intval($request['capacity']) < $total_capacity) {
    //             return response()->json([
    //                 'success' => false,
    //                 'message' => 'You cannot add container types exceeding the capacity.',
    //             ], 400);
    //         }

    //         // Create Approved Block
    //         $block = new Block;
    //         $block->yard_id = $request->input('yard_id');
    //         $block->block_name = $request->input('block_name', 'Approved Block');
    //         $block->container_types = json_encode($containers_types);
    //         $block->area = $request->input('area', 0);
    //         $block->area_unit = $request->input('area_unit', 'sqft');
    //         $block->capacity = $request->input('capacity');
    //         $block->description = $request->input('description', 'Auto-approved block from pre-arrival');
    //         $block->available_space = $request->input('capacity') ?? 0;
    //         $block->save();

    //         // Update Block ID
    //         $block->block_id = 'BLK000' . $block->id;
    //         $block->update();

    //         return response()->json([
    //             'success' => true,
    //             'message' => 'Pre-arrival approved and block created successfully.',
    //             'data' => [
    //                 'block' => $block,
    //                 'pre_arrival' => $pre_arrival,
    //             ],
    //         ], 200);
    //     } catch (\Exception $e) {
    //         return response()->json([
    //             'success' => false,
    //             'message' => 'An error occurred during approval: ' . $e->getMessage(),
    //         ], 500);
    //     }
    // }

    // public function approveCreate($id)
    // {
    //     $pre_arrival = PreArrivalDeparture::with('documents')->where('id', $id)->first();
    //     // dd($logisticProvider);

    //     $container_details = ContainerDetail::whereIn('id', explode(',', $pre_arrival['container_detail_ids']))->get();

    //     $containerOwners = ContainerOwner::where('status', 0)->get();

    //     $containertype = ContainerType::where('status', 0)->get();

    //     $logisticProviders = LogisticProvider::where('status', 0)->get();

    //     $vehicleMaster = VehicleType::where('status', 0)->get();

    //     $yards = Yard::where('status', 0)->get();

    //     return view('pre-arrival.approved-arrival', compact('pre_arrival', 'containerOwners', 'containertype', 'logisticProviders', 'vehicleMaster', 'yards', 'container_details'));
    // }

    // public function moveToArrived(Request $request, $id)
    // {

    //     $today = new Carbon();
    //     $request['date'] = $today->format('Y-m-d');

    //     $pre_arrival = PreArrivalDeparture::where('id', $request['pre_arrival_id'])
    //         ->first();

    //     // $request['order_id']=$pre_arrival['order_id'];

    //     // Update Containers
    //     $containerDetailService = new ContainerDetailsService;
    //     $order_container_id = $containerDetailService->updateContainerDetail($request);

    //     $arrivedservice = new PreArrivalService;
    //     $arrived = $arrivedservice->saveArrival($request);
    //     $arrived['container_detail_ids'] = implode(',', $order_container_id);
    //     $arrived->update();

    //     $pre_arrival['status'] = 1;
    //     $pre_arrival->update();

    //     // save Documents
    //     if (isset($request['document_id'])) {
    //         foreach ($request['document_id'] as $key => $value) {
    //             $doc = Document::where('id', $value)->first();
    //             Document::create([
    //                 'user_type' => 'arrival',
    //                 'user_id' => $arrived['id'],
    //                 'document_name' => $doc['document_name'],
    //                 'attachment' => $doc['attachment'],
    //                 'extension' => $doc['extension']
    //             ]);
    //         }
    //     }

    //     // set session
    //     Session::flash('success', ' Arrived Successfully');

    //     if (isset($request['inspection']) && $request['inspection'] == 1) {
    //         return redirect()->route('dashboard.home')->with('success', 'Order Moved to Arrived Successfully');
    //     }

    //     return redirect()->route('arrival.index')->with('success', 'Order Moved to Arrived Successfully');
    // }

    // public function backToArrival(Request $request, $id)
    // {

    //     // $pre_arrival=PreArrivalDeparture::where('order_id',$id)
    //     //     ->where('order_type','pre_arrival')->first();

    //     $arrived = PreArrivalDeparture::where('id', $id)
    //         ->where('order_type', 'arrival')->first();

    //     $arrived['status'] = 0;
    //     $arrived['reject_reason'] = $request['reason'];
    //     $arrived->update();

    //     // set session

    //     Session::flash('success', 'Order Rejected Successfully');

    //     return redirect()->route('arrival.index')->with('success', 'Order Moved to Arrived Successfully');
    // }

    public function filter(Request $request)
    {
        // dd($request);
        $pre_arrival = PreArrivalDeparture::where('status', 0)->where('order_type', 'pre_arrival')
            ->with('orders', 'orders.container_owner:id,company_name');

        if ($request['date'] != '' && isset($request['date']) && $request['date'] != null) {
            $pre_arrival = $pre_arrival->whereDate('date', $request['date']);
        }
        if ($request['container_id'] != '' && isset($request['container_id']) && $request['container_id'] != null) {
            $pre_arrival = $pre_arrival->where('container_id', $request['container_id']);
        }
        if ($request['container_status'] != '' && isset($request['container_status']) && $request['container_status'] != null) {
            // $pre_arrival=$pre_arrival->where('container_status',$request['container_status']);
            $pre_arrival = $pre_arrival->whereHas('orders', function ($query) use ($request) {
                $query->where('container_status', $request['container_status']);
            });
        }
        if ($request['container_condition'] != '' && isset($request['container_condition']) && $request['container_condition'] != null) {
            $pre_arrival = $pre_arrival->whereHas('orders', function ($query) use ($request) {
                $query->where('container_condition', $request['container_condition']);
            });
        }

        $pre_arrival = $pre_arrival->get();

        return view('pre-arrival.index', compact('pre_arrival'));
    }
}
