<?php

namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Auth;
use App\Models\User;
use App\Models\Currency;
use App\Models\Order;
use App\Models\OrderDetail;
use App\Models\OrderMessage;
use App\Models\OrderCurrency;
use App\Models\Coupon;
use App\Models\AppliedCoupon;
use App\Models\Product;
use App\Models\ProductExtra;
use App\Models\ProductImage;
use App\Models\AssignOrderDetail;
use \PDF;

use Illuminate\Support\Facades\Storage;
use ZipArchive;
use Illuminate\Support\Str;
use Symfony\Component\HttpFoundation\StreamedResponse;


// use Excel;

class OrderController extends CommonController
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }
 

    public function list(Request $request){

        // if($this->checkPermission('orders','list') == false && $this->checkSuperPermission('orders','list') == false ){
        //     $request->session()->flash('alert-danger', "You don't have permissions to access this page.");
        //     return redirect()->route('admin.home');
        // }


        $where = $orWhere = [];

        $where = [['payment_status', '=', 'C'], ['type', '<>', 'cancel']];

        // search confitions
        if($request->search != null){
            if (str_contains($request->search, '@')) { 
                $userDtl = User::where(['email'=> $request->search])->first();
                if($userDtl){
                    $orWhere[] = ['user_id', '=', $userDtl->id];
                }
            }

            $orWhere[] = ['unique_order_id', 'LIKE', '%'.$request->search.'%'];
            $orWhere[] = ['delivery_user_name', 'LIKE', '%'.$request->search.'%'];
            $orWhere[] = ['billing_user_name', 'LIKE', '%'.$request->search.'%'];
        }

        $order_list = Order::where($where)
                        ->where(function($query) use ($orWhere){
                            // creating "OR" queries for search
                            foreach($orWhere as $key => $where){
                                if($key == 0){
                                    $query->where([$where]);
                                }else{
                                    $query->orWhere([$where]);
                                }
                            }
                        })
                        ->when($request->sort && $request->direction, function($query) use ($request){
                            $query->orderBy($request->sort, $request->direction);
                        }, function($query){
                            $query->orderBy('purchase_date', 'desc');
                        })
                        ->paginate(30);

        $agent_assinged = DB::connection('mysql')->table('agent_assinged')->get();
        $agent = DB::connection('mysql')->table('agents')->get();                

        return view('admin.order.list', ['agent' => $agent, 'agent_assinged' => $agent_assinged, 'result' => $order_list, 'request' => $request]);
    }

    /**
     * View Order Details
     *
     * @return \Illuminate\Http\Response
     */

    public function SiteNamewiseList(Request $request,$sitename){

        $sitename = decrypt($sitename);

        $where = $orWhere = [];

        $where = [['payment_status', '=', 'C'], ['type', '<>', 'cancel']];

        // search confitions
        if($request->search != null){
            if (str_contains($request->search, '@')) { 
                $userDtl = User::where(['email'=> $request->search])->first();
                if($userDtl){
                    $orWhere[] = ['user_id', '=', $userDtl->id];
                }
            }

            $orWhere[] = ['unique_order_id', 'LIKE', '%'.$request->search.'%'];
            $orWhere[] = ['delivery_user_name', 'LIKE', '%'.$request->search.'%'];
            $orWhere[] = ['billing_user_name', 'LIKE', '%'.$request->search.'%'];
        }

        $order_list = Order::where($where)
                        ->where('sitename',$sitename)
                        ->where(function($query) use ($orWhere){
                            // creating "OR" queries for search
                            foreach($orWhere as $key => $where){
                                if($key == 0){
                                    $query->where([$where]);
                                }else{
                                    $query->orWhere([$where]);
                                }
                            }
                        })
                        ->when($request->sort && $request->direction, function($query) use ($request){
                            $query->orderBy($request->sort, $request->direction);
                        }, function($query){
                            $query->orderBy('purchase_date', 'desc');
                        })
                        ->paginate(30);

        $agent_assinged = DB::connection('mysql')->table('agent_assinged')->get();
        $agent = DB::connection('mysql')->table('agents')->get();    
        return view('admin.list', ['agent' => $agent, 'agent_assinged' => $agent_assinged, 'result' => $order_list, 'request' => $request,'sitename' => $sitename]);            

    }
    public function view($id = null, Request $request)
    {
        /* check permission */
        // if($this->checkPermission('orders','view') == false && $this->checkSuperPermission('orders','view') == false){
        //     $request->session()->flash('alert-danger', "You don't have permissions to access this page.");
        //     return redirect()->route('admin.dashboard');
        //     exit;
        // }

        if($id == null){
            return redirect()->route('admin.home');
        }
        $id = base64_decode($id);

        $order_dtl = Order::find($id);
        //dd($order_dtl);

        $customer_dtl = User::find($order_dtl->user_id);

        $total_cart_price = 0.00; $occasion_product_price = 0;
        
        $cart_array = array();
        if( $order_dtl != null ) {
            if( isset($order_dtl->order_detail_admin) && count($order_dtl->order_detail_admin) > 0 ) {
                $i = 0;
                foreach( $order_dtl->order_detail_admin as $productLists ) {

                    $extra_addon_array = []; $extra_addon_ids_array = [];
                    //If Extra Addons NOT exist
                    if( $productLists->order_details_id == 0 ) {
                        //If Gift Addons NOT exist
                        if( $productLists->gift_addon_id == 0 ) {

                            $product_image_name = '';
                            if( isset($productLists->product->default_product_image) && $productLists->product->default_product_image != null ) {
                                $product_image_name = $productLists->product->default_product_image['name'];
                                // dd($productLists->product->default_product_image);
                            }
                            
                            //dd($order_dtl);
                            
                            $cart_array[$i]['order_detail_id']  = $productLists->id;
                            $cart_array[$i]['category_id']      = $productLists->category_id;
                            $cart_array[$i]['occasion_id']      = $productLists->occasion_id;
                            $cart_array[$i]['product_id']       = $productLists->product->id;
                            $cart_array[$i]['fnid']             = $productLists->product->fnid;
                            $cart_array[$i]['delivery_type']    = $productLists->product->delivery_type;
                            $cart_array[$i]['product_attr_id']  = $productLists->product_attr_id;
                            $cart_array[$i]['gift_addon_id']    = $productLists->gift_addon_id;
                            $cart_array[$i]['product_name']     = $productLists->product->product_name;
                            $cart_array[$i]['image']            = $product_image_name;
                            $cart_array[$i]['qty']              = $productLists->qty;

                            $cart_array[$i]['delivery_pincode'] = $productLists->delivery_pincode;
                            $cart_array[$i]['delivery_country'] = $order_dtl->delivery_country;
                            $cart_array[$i]['hold_reason']      = $order_dtl->hold_reason;
                            $cart_array[$i]['delivery_city']    = $productLists->delivery_city_name;
                            $cart_array[$i]['delivery_date']    = $productLists->delivery_date;
                            $cart_array[$i]['shippingmethod_id']= $productLists->shippingmethod_id;
                            $cart_array[$i]['shippingmethod_name']= $productLists->shippingmethod_name;
                            $cart_array[$i]['ship_price']       = $productLists->ship_price;
                            $cart_array[$i]['delivery_time_id'] = $productLists->delivery_time_id;
                            $cart_array[$i]['deliverytime']     = $productLists->deliverytime;
                            $cart_array[$i]['order_details_id_giftaddon']     = $productLists->order_details_id_giftaddon;

                            //If product attribute exist
                            //if(isset($productLists->product->order_product_all_attributes) && $productLists->product->order_product_all_attributes != null){
                            if( $productLists->product_attr_id != 0 ) {
                                // dd($productLists->product->order_product_all_attributes);
                                foreach ( $productLists->product->order_product_all_attributes as $key => $value) {
                                    // dd("hello");
                                    if( $value->id == $productLists->product_attr_id ) {
                                        //$cart_array[$i]['attribute_name'] = $value->title;
                                        $cart_array[$i]['attribute_name'] = $value->content;
                                    }
                                }
                            }
                            else{
                                $cart_array[$i]['attribute_name'] = '';
                            }

                            // dd($cart_array);

                            //If extra addon exists
                            if( isset($productLists->order_related_detail) && ($productLists->order_related_detail != null) ) {

                                if( $productLists->order_related_detail->product_extras_addon_id != '' ) {
                                    if( strpos($productLists->order_related_detail->product_extras_addon_id, ',') !== false ) { //For multiple extra addon
                                        $extra_array  = explode(',', $productLists->order_related_detail->product_extras_addon_id);
                                        asort($extra_array);
                                        foreach ( $extra_array as $key_extra => $val_extra ) {
                                            $get_pro_extra = ProductExtra::where('id',$val_extra)->first();

                                            $extra_addon_array[]     = $get_pro_extra['title'];
                                            $extra_addon_ids_array[] = $get_pro_extra['id'];
                                        }
                                    }else{  //For single extra addon
                                        $get_pro_extra = ProductExtra::where('id',$productLists->order_related_detail->product_extras_addon_id)->first();

                                            $extra_addon_array[]     = $get_pro_extra['title'];
                                            $extra_addon_ids_array[] = $get_pro_extra['id'];
                                    }
                                }
                                asort($extra_addon_ids_array);
                                $cart_array[$i]['product_extra_addon_name'] = $extra_addon_array;
                                $cart_array[$i]['product_extra_addon_ids']  = $extra_addon_ids_array;

                                $cart_array[$i]['product_unit_price']       = $productLists->unit_price;

                                $cart_array[$i]['unit_price']       = $productLists->unit_price + $productLists->order_related_detail->unit_price;
                                $cart_array[$i]['total_price']      = $productLists->total_price + $productLists->order_related_detail->total_price;
                                $total_cart_price                   = $total_cart_price + $productLists->total_price + $productLists->order_related_detail->total_price;

                                //For occasion related product (Total Price)//
                                if( $productLists->product->occasions_id != null ) {
                                    $occasion_product_price = $occasion_product_price + $productLists->unit_price + $productLists->order_related_detail->total_price;
                                }
                                //For occasion related product (Total Price)//
                            }
                            else{   //If NOT extra addon exists
                                $cart_array[$i]['product_extra_addon_name'] = $extra_addon_array;
                                $cart_array[$i]['product_extra_addon_ids']  = $extra_addon_ids_array;
                                $cart_array[$i]['product_unit_price']       = $productLists->unit_price;
                                $cart_array[$i]['unit_price']               = $productLists->unit_price;
                                $cart_array[$i]['total_price']              = $productLists->total_price;
                                $total_cart_price                           = $total_cart_price + $productLists->total_price;

                                //For occasion related product (Total Price)//
                                if( $productLists->product->occasions_id != null ) {
                                    $occasion_product_price = $occasion_product_price + $productLists->total_price;
                                }
                                //For occasion related product (Total Price)//
                            }
                        }
                        else{   //If Gift Addons exist
                            $giftaddon_image_name = '';
                            //$giftaddon_image_name = $productLists->extraaddon_detail->image;
                            if( isset($productLists->extraaddon_detail->default_product_image) && $productLists->extraaddon_detail->default_product_image != null ) {
                                $giftaddon_image_name = $productLists->extraaddon_detail->default_product_image->name;
                            }

                            $getAddonDtl = Product::where(['id' => $productLists->gift_addon_id])->first();
                            
                            $cart_array[$i]['order_detail_id']  = $productLists->id;
                            $cart_array[$i]['category_id']      = $productLists->category_id;
                            $cart_array[$i]['occasion_id']      = $productLists->occasion_id;
                            $cart_array[$i]['product_id']       = $productLists->product_id;
                            $cart_array[$i]['fnid']             = $getAddonDtl->fnid;
                            $cart_array[$i]['delivery_type']    = $getAddonDtl->delivery_type;
                            $cart_array[$i]['product_attr_id']  = $productLists->product_attr_id;
                            $cart_array[$i]['gift_addon_id']    = $productLists->gift_addon_id;
                            //$cart_array[$i]['product_name']     = $productLists->extraaddon_detail->title;
                            $cart_array[$i]['product_name']     = $productLists->extraaddon_detail->product_name;
                            $cart_array[$i]['image']            = $giftaddon_image_name;
                            $cart_array[$i]['qty']              = $productLists->qty;

                            $cart_array[$i]['delivery_pincode'] = $productLists->delivery_pincode;
                            $cart_array[$i]['delivery_country'] = $order_dtl->delivery_country;
                            $cart_array[$i]['hold_reason']      = $order_dtl->hold_reason;
                            $cart_array[$i]['delivery_city']    = $productLists->delivery_city_name;
                            $cart_array[$i]['delivery_date']    = $productLists->delivery_date;
                            $cart_array[$i]['shippingmethod_id']= $productLists->shippingmethod_id;
                            $cart_array[$i]['shippingmethod_name']= $productLists->shippingmethod_name;
                            $cart_array[$i]['ship_price']       = $productLists->ship_price;
                            $cart_array[$i]['delivery_time_id'] = $productLists->delivery_time_id;
                            $cart_array[$i]['deliverytime']     = $productLists->deliverytime;
                            $cart_array[$i]['order_details_id_giftaddon']     = $productLists->order_details_id_giftaddon;



                            //If product attribute exist
                            if(isset($productLists->product->order_product_attribute) && $productLists->product->order_product_attribute['title'] != null){
                                //$cart_array[$i]['attribute_name']=$productLists->product->order_product_attribute['title'];
                                $cart_array[$i]['attribute_name']=$productLists->product->order_product_attribute['content'];
                            }
                            else{
                                $cart_array[$i]['attribute_name'] = '';
                            }

                            $cart_array[$i]['product_extra_addon_name'] = $extra_addon_array;
                            $cart_array[$i]['product_extra_addon_ids']  = $extra_addon_ids_array;

                            $cart_array[$i]['product_unit_price']= $productLists->unit_price;
                            $cart_array[$i]['unit_price']       = $productLists->unit_price;
                            $cart_array[$i]['total_price']      = $productLists->total_price;
                            $total_cart_price                   = $total_cart_price+$productLists->total_price;
                        }
                    }   //If Extra Addons NOT exist condition end here
                    $i++;
                    unset($extra_addon_array); unset($extra_addon_ids_array);
                }
            }
            //dd($cart_array);
        }

        $addon_gift_array = [];
        if(count($cart_array)>0){
            foreach ($cart_array as $key => $cart_product) {
                if($cart_product['gift_addon_id'] >0){
                    unset($cart_array[$key]);
                    $addon_gift_array[] = $cart_product;
                }
            }
        }

        $status_array = array('P'=>'Pending','PC'=>'Processed','CL'=>'Cancel','H'=>'Hold','D'=>'Delivered','S'=>'Shipped');
        if($order_dtl != null){
            if($order_dtl->order_delivery_status == 'P'){
                $status_array = array('P'=>'Pending','PC'=>'Processed','CL'=>'Cancel','H'=>'Hold','D'=>'Delivered','S'=>'Shipped');
            }else if($order_dtl->order_delivery_status == 'PC'){
                $status_array = array('PC'=>'Processed','CL'=>'Cancel','H'=>'Hold','D'=>'Delivered','S'=>'Shipped');
            }else if($order_dtl->order_delivery_status == 'D'){
                $status_array = array('D'=>'Delivered');
            }else if($order_dtl->order_delivery_status == 'H'){
                $status_array = array('PC'=>'Processed','CL'=>'Cancel','H'=>'Hold','D'=>'Delivered','S'=>'Shipped');
            }else if($order_dtl->order_delivery_status == 'CL'){
                $status_array = array('PC'=>'Processed','CL'=>'Cancel');
            }else if($order_dtl->order_delivery_status == 'S'){
                $status_array = array('S'=>'Shipped','D'=>'Delivered');
            }
        }

        //For further logic
        $orderId = $id;
        $order = DB::connection('mysql')->table('orders')->where('id',$orderId)->first();
        $order_details = DB::connection('mysql')->table('order_details')->where('order_id',$orderId)->get();
        $product = DB::connection('mysql')->table('products')->get();
        $agents = DB::connection('mysql')->table('agents')->get();
        $assinged = DB::connection('mysql')->table('agent_assinged')->where('OID', $orderId)->get();        
        $assinedCount = DB::connection('mysql')->table('agent_assinged')->where('OID', $orderId)->where('isConfirmCl', 0)->get();
        $agent_product_list =  DB::connection('mysql')->table('agent_product_list')->get();

        $agent_details_product = [];

            $groupByProduct = [];

                foreach($order_details as $order_detail){

                    foreach($product as $products){

                        if($order_detail->product_id == $products->id){

                            $groupByProduct[] = $products;

                        }

                    }

                }



            $assigned_agent_product_map = DB::connection('mysql')->table('assigned_agent_product_map')->get();

            $groupByProductCollection = collect($groupByProduct);

            $groupedByDeliveryType = $groupByProductCollection->groupBy('product_delivery_type');

            // return $groupedByDeliveryType['C'];

        $agentasGroupBy = DB::connection('mysql')
            ->table('agent_assinged')
            ->select('agent_order_id', 'status', 'track_no', 'tracking_link', DB::raw('COUNT(*) as total'))
            ->where('OID', $orderId)
            ->groupBy('agent_order_id', 'status', 'track_no', 'tracking_link')
            ->get();




            $disable = count($assinedCount); 



            // dd($disable);

            

            //Filter

            $agentsAfterCancel = [];

            $agent_ids = [];

            $assingedCancel = DB::connection('mysql')->table('agent_assinged')

                              ->where('OID', $orderId)

                              ->whereIn('status', ['P','PC','CL','H','D','S'])

                              ->get();

            // return $assingedCancel;



            foreach($assingedCancel as $assingedCancels){

                

                $agent_ids[]=$assingedCancels->agent_id;

            }

            // return $agent_ids;             

            

            $agentsAfterCancel[] = DB::connection('mysql')->table('agents')

                                   ->whereNotIn('id',$agent_ids)

                                   ->get();

        return view('admin.order.view', ['order_dtl' => $order_dtl, 'cart_array' => $cart_array, 'addon_gift_array' => $addon_gift_array, 'customer_dtl' => $customer_dtl, 'status_array' => $status_array, 'order' => $order, 'order_details' => $order_details, 'product' => $product, 'agents' => $agents, 'assinged' => $assinged, 'groupedByDeliveryType' => $groupedByDeliveryType, 'assigned_agent_product_map' => $assigned_agent_product_map, 'disable' => $disable, 'agentasGroupBy' => $agentasGroupBy, 'agent_product_list' => $agent_product_list, 'agentsAfterCancel' => $agentsAfterCancel]);
    }

    public function saveProduct(Request $request){

        // return $request->all();
        // dd($request->all());

        $agents = $request['agents'];

        $OrderID = $request['OrderID'];

        $OrderOriginalID = $request['OrderOriginalID'];



        $counter = 0; 

        foreach($agents as $agent) {

            if($agent['agent_id'] != null){

                $suffix = chr(65 + $counter); 



                $agent_assignedId = DB::connection('mysql')->table('agent_assinged')->insertGetId([

                    'agent_order_id' => $OrderID . '-' . $suffix, 

                    'OID' => $OrderOriginalID,

                    'agent_id' => $agent['agent_id'],

                    'totalPrice' => $agent['total_price'],

                    'status' => 'P',

                    'isConfirmCl' => 0,
                    'delivery_type' => $agent['delivery_type'],
                    'delivery_date' => $agent['date'],
                    'delivery_time' => $agent['time'],
                    'comments' => $agent['comments'],
                    'placed_userid' => Auth::user()->id,

                    'created_at' => now(),

                    'updated_at' => now(),

                ]);



                foreach($agent as $key => $productData) {

                    if (is_array($productData) && isset($productData['products'])) {

                        foreach($productData['products'] as $index => $productId) {
                           $imageLink = [];

                            

                            if($productId != null && $productData['product_prices'][$index] != null && $productData['product_qty'][$index] != null){

                                if ($productData['imgLink'][$index] != 'null') {
                                        $lines = preg_split('/\r\n|\r|\n/', $productData['imgLink'][$index]);
                                        foreach ($lines as $line) {
                                            if (trim($line) !== '') {
                                                $imageLink[] = trim($line);
                                            }
                                        }
                                    }

                                $imageLinkJson = !empty($imageLink) ? json_encode($imageLink) : null;


                                DB::connection('mysql')->table('assigned_agent_product_map')->insert([

                                    'agent_assinged_id' => $agent_assignedId,

                                    'product_id' => $productId,

                                    'price' => $productData['product_prices'][$index],

                                    'qty' => $productData['product_qty'][$index],
                                    
                                    'imagePath' => $imageLinkJson,

                                    'imageText' => $productData['text'][$index],

                                    'created_at' => now(),

                                    'updated_at' => now(),

                                ]);

                            }

                        }

                    }

                }
                // return $imageLink;
                $counter++; 

            }

        }

        return back();
    }

    public function ProductByAgent(Request $request){

        $agent_id = $request['agent_id'];
        $products = DB::connection('mysql')->table('agent_product_list')->where('agent_id',$agent_id)->get();
        return $products;

    }

    public function EditAgentAssigned(Request $request, $OrderId)
    {
        $OrderId = decrypt($OrderId);

        $order = DB::connection('mysql')->table('orders')->where('id', $OrderId)->first();
        $agents = DB::connection('mysql')->table('agents')->get();
        $agent_product_list = DB::connection('mysql')->table('agent_product_list')->get();

        $agent_assigned = DB::connection('mysql')
            ->table('agent_assinged')
            ->where('OID', $OrderId)
            ->where('isConfirmCl', 0)
            ->get();

        $agent_assigned_ids = $agent_assigned->pluck('id');

        $assigned_agent_product_map = DB::connection('mysql')
            ->table('assigned_agent_product_map')
            ->whereIn('agent_assinged_id', $agent_assigned_ids)
            ->get();

        $tableItem = [];

        foreach ($agent_assigned as $agent_assigneds) {
            $agent = $agents->firstWhere('id', $agent_assigneds->agent_id);

            $agent_delivery_charge = DB::connection('mysql')
                ->table('agent_delivery_charge')
                ->where('agent_id', $agent_assigneds->agent_id)
                ->first();

            $product_Details = [];

            foreach ($assigned_agent_product_map as $assigned_agent_product_maps) {
                if ($agent_assigneds->id == $assigned_agent_product_maps->agent_assinged_id) {
                    $product = $agent_product_list->firstWhere('id', $assigned_agent_product_maps->product_id);
                    $product_Details[] = [
                        'id' => $assigned_agent_product_maps->id,
                        'agent_assinged_id' => $assigned_agent_product_maps->agent_assinged_id,
                        'product' => $product,
                        'qty' => $assigned_agent_product_maps->qty,
                        'price' => $assigned_agent_product_maps->price,
                        'imagePath' => $assigned_agent_product_maps->imagePath,
                        'imageText' => $assigned_agent_product_maps->imageText,
                    ];
                }
            }

            $tableItem[] = [
                'OrderId' => $OrderId,
                'agentAssignId' =>  $agent_assigneds->id,
                "agent_order_id" => $agent_assigneds->agent_order_id,
                'agent' => $agent,
                'delivery_type' => $agent_assigneds->delivery_type,
                'delivery_price' => $agent_delivery_charge,
                'totalPrice' => $agent_assigneds->totalPrice,
                'delivery_date' => $agent_assigneds->delivery_date,
                'delivery_time' => $agent_assigneds->delivery_time,
                'comments' => $agent_assigneds->comments,
                'products' => $product_Details,
            ];
        }
        //  dd($tableItem);
        return view('admin.order.viewEdit', compact('OrderId', 'order', 'tableItem','agents','agent_product_list'));
    }


    public function UpdateAgentAssigned(Request $request){
        // return $request->all();

        $agents = $request['agents'];
        $OrderID = $request['OrderID'];
        $OrderOriginalID = $request['OrderOriginalID'];

        $counter = 0;

        foreach ($agents as $agent) {
            // if ($counter == 3) {
            //     $counter = 4;
            // }

            $suffix = chr(65 + $counter); // A, B, C, D...

            if (!empty($agent['agent_id'])) {

                if (!empty($agent['agentAssignId'])) {
                    // Update existing
                    DB::connection('mysql')->table('agent_assinged')->where('id', $agent['agentAssignId'])->update([
                        'agent_id' => $agent['agent_id'],
                        'totalPrice' => $agent['total_price'],
                        'delivery_type' => $agent['delivery_type'],
                        'delivery_date' => $agent['date'],
                        'delivery_time' => $agent['time'],
                        'comments' => $agent['comments'] ?? null,
                        'placed_userid' => Auth::user()->id,
                    ]);

                    // Remove previous mappings
                    DB::connection('mysql')->table('assigned_agent_product_map')->where('agent_assinged_id', $agent['agentAssignId'])->delete();

                    $assignedId = $OrderOriginalID;
                } else {
                    // Insert new
                    $assignedId = DB::connection('mysql')->table('agent_assinged')->insertGetId([
                        'agent_order_id' => $OrderID . '-' . $suffix,
                        'OID' => $OrderOriginalID,
                        'agent_id' => $agent['agent_id'],
                        'totalPrice' => $agent['total_price'],
                        'status' => 'P',
                        'isConfirmCl' => 0,
                        'delivery_type' => $agent['delivery_type'],
                        'delivery_date' => $agent['date'],
                        'delivery_time' => $agent['time'],
                        'comments' => $agent['comments'] ?? null,
                        'placed_userid' => Auth::user()->id,
                        'created_at' => now(),
                        'updated_at' => now(),
                    ]);
                }


                // return 'hello';
                // Now insert product mappings
                foreach ($agent as $key => $productData) {
                    if (is_array($productData) && isset($productData['products'])) {
                        foreach ($productData['products'] as $index => $productId) {
                            if ( $productId != null && $productData['product_prices'][$index] != null && $productData['product_qty'][$index] != null) {
                                // Process image links
                                $imageLink = [];
                                if (!empty($productData['imgLink'][$index]) && $productData['imgLink'][$index] !== 'null') {
                                    $productData['imgLink'][$index];
                                    $lines = preg_split('/\r\n|\r|\n/', $productData['imgLink'][$index]);
                                    foreach ($lines as $line) {
                                        if (trim($line) !== '') {
                                            $imageLink[] = trim($line);
                                        }
                                    }
                                }
                                
                                $imageLinkJson = !empty($imageLink) ? json_encode($imageLink) : null;

                                // Insert product map
                                DB::connection('mysql')->table('assigned_agent_product_map')->insert([
                                   'agent_assinged_id' => $agent['agentAssignId'] ?? $assignedId,
                                    'product_id' => $productId,
                                    'price' => $productData['product_prices'][$index],
                                    'qty' => $productData['product_qty'][$index],
                                    'imagePath' => $imageLinkJson,
                                    'imageText' => $productData['text'][$index] ?? null,
                                    'created_at' => now(),
                                    'updated_at' => now(),
                                ]);
                            }
                        }
                    }
                }

                $counter++;
            }
        }
        // return $imageLinkJson;
        return back();
    }
    public function DeleteOrderProduct($id){
        $id = decrypt($id);
        DB::connection('mysql')->table('assigned_agent_product_map')->where('id',$id)->delete();
        return back();
    }


    public function getAgentId(Request $request){

        // $agent_id = $request['agent_id'];

        $agentsArray = $request['agentsArray'];

        $agentIndex = $request['agentIndex'];



        // dd($agentsArray);



        if($agentsArray == null){



            $agents = DB::connection('mysql')->table('agents')

                      ->get();

        }else{



            // $products = DB::connection('mysql')->table('agent_product_list')->where('agent_id',$agent_id)->get();

            $agents = DB::connection('mysql')->table('agents')

                      ->whereNotIn('id',$agentsArray)

                      ->get(); 

            // dd($agents);       

            // return $products;

        } 

                  

        $response = [

            // 'products' => $products

            'agents' => $agents,

            'agentIndex'=>$agentIndex,

        ];



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

    }

    public function GetPriceByProduct(Request $request){
        $agentIndex = $request['agentIndex'];
        $productIndex = $request['productIndex'];
        $selectProduct = $request['product_id'];
        $price = DB::connection('mysql')->table('agent_product_list')->where('id',$selectProduct)->first();
        $data = compact('agentIndex','price','productIndex');
        return $data;

    }

    public function GetDeliveryType(Request $request){

        $productqty = $request['productqty'];

        $total = 0;

        $Dtype = $request['Dtype'];

        $agent_id = $request['agent_id'];

        $productPrices = $request['productPrices'];

        $agent_delivery_charge = DB::connection('mysql')

        ->table('agent_delivery_charge')

        ->where('agent_id', $agent_id)

        ->first();

        $i = 0;

        foreach($productPrices as $productPrice){

            $total+=$productPrice * $productqty[$i];

            $i++;

        }

        $data = compact('agent_delivery_charge','Dtype','total','productqty','productqty');

        return $data;

    }

    public function getOrderID(Request $request){

        $orderId =  $request['orderId'];

        $reassignAggent = $request['reassignAggent'];

        $assigned = DB::connection('mysql')->table('agent_assinged')->where('id',$orderId)->first();

        return $assigned;
    }

    public function ReAssignProduct(Request $request){

        // return $request->all();

        $OrderID = $request['agent_order_id'];

        $agents = $request['agents'];

        
        $singleAgentAssinged = DB::connection('mysql')->table('agent_assinged')->where('agent_order_id',$OrderID)->first();

        $agent_assinged = DB::connection('mysql')->table('agent_assinged')->where('agent_order_id',$OrderID)->get();

        $orders = DB::connection('mysql')->table('orders')->where('id',$singleAgentAssinged->OID)->first();

        $order_specific_agent = DB::connection('mysql')->table('agent_assinged')->where('OID',$orders->id)->get();

        $reassignascii = 0;
        $counter = 0; 

        // return $request->all();
       
        // return $counter;

        DB::connection('mysql')->table('agent_assinged')->where('agent_order_id',$OrderID)->update([

            'isConfirmCl'=>1,

        ]);

        foreach($agent_assinged as $agent_assingeds){

            $reassignascii++;

        }

        foreach($order_specific_agent as $order_specific_agents){
            $counter++;
        }


        

        $suffix = chr(65 + $counter);

        foreach($agents as $agent) {

            $agent_assignedId = DB::connection('mysql')->table('agent_assinged')->insertGetId([

                'agent_order_id' => $orders->unique_order_id . '-' . $suffix, 
                'OID' => $orders->id,
                'agent_id' => $agent['agent_id'],
                'totalPrice' => $agent['total_price'],
                'status' => 'P',
                'isConfirmCl' => 0,
                'delivery_date' => $agent['date'],
                'delivery_time' => $agent['time'],
                'comments' => $agent['comments'],
                'placed_userid' => Auth::user()->id,
                'created_at' => now(),
                'updated_at' => now(),

            ]);



            foreach($agent as $key => $productData) {

                if (is_array($productData) && isset($productData['products'])) {

                    foreach($productData['products'] as $index => $productId) {
                        $imageLink = [];
                        if (!empty($productData['imgLink'][$index]) && $productData['imgLink'][$index] !== 'null') {
                            $lines = preg_split('/\r\n|\r|\n/', $productData['imgLink'][$index]);
                            foreach ($lines as $line) {
                                if (trim($line) !== '') {
                                    $imageLink[] = trim($line);
                                }
                            }
                        }

                        $imageLinkJson = !empty($imageLink) ? json_encode($imageLink) : null;

                        DB::connection('mysql')->table('assigned_agent_product_map')->insert([

                            'agent_assinged_id' => $agent_assignedId,
                            'product_id' => $productId,
                            'price' => $productData['product_prices'][$index],
                            'qty' => $productData['product_qty'][$index],
                            'imagePath' => $imageLinkJson,
                            'imageText' => $productData['text'][$index] ?? null,
                            'created_at' => now(),
                            'updated_at' => now(),

                        ]);

                    }

                }

            }




        }



        return back();

    }

    public function DeleteAgentAssigned($id,$asssignId){
        $id = decrypt($id);
        $assignedId = decrypt($asssignId);
        DB::connection('mysql')->table('agent_assinged')->where('id',$assignedId)->delete();
        DB::connection('mysql')->table('assigned_agent_product_map')->where('agent_assinged_id',$assignedId)->delete();

        return back();

    }

    public function getReAssignPrice(Request $request){

        $totalPrice = 0;

        $OrderId = $request['OrderId'];

        $reassignAggent = $request['reassignAggent'];

        $price = DB::connection('mysql')->table('agent_assinged')->where('id',$OrderId)->first();

        return $price->totalPrice;

    }

    public function Reassign(Request $request){

        // dd($request->all());

        $counter = 0; 

        $agent_product_list = [];

        $OrderId=$request['OrderId'];

        $reassignAggent=$request['reassignAggent'];

        $re_price=$request['re_price'];

        $assigned = DB::connection('mysql')->table('agent_assinged')->where('id',$OrderId)->first();

        $order =  DB::connection('mysql')->table('orders')->where('id',$assigned->OID)->first();

        $product_maped = DB::connection('mysql')->table('assigned_agent_product_map')->where('agent_assinged_id',$assigned->id)->get();

        foreach($product_maped as $product_mapeds){

            $agent_product_list[] = DB::connection('mysql')->table('agent_product_list')->where('id',$product_mapeds->product_id)->first();

        }



        DB::connection('mysql')->table('agent_assinged')->where('id',$assigned->id)->update([

            'isConfirmCl'=>1,

        ]);

        $AgentOrderId = $assigned->agent_order_id;

        $lastChar = substr($AgentOrderId, -1); 

        $CharInt = ord($lastChar); 

        $suffix = chr($CharInt + 5); 

            $assinedId = DB::connection('mysql')->table('agent_assinged')->insertGetId([

            'agent_order_id'=>  $order->unique_order_id.'-'.$suffix,

            'OID'=>$order->id,  

            'agent_id'=>$reassignAggent,    

            'totalPrice'=>$re_price,    

            'status'=>'P',

            'isConfirmCl'=>0,

            'created_at'=>date('Y-m-d H:i:s'),

            'updated_at'=>date('Y-m-d H:i:s'),

        ]);

        foreach($product_maped as $product_mapeds){

            $agent_product_list = DB::connection('mysql')->table('agent_product_list')->where('agent_id',$assigned->agent_id)->where('id',$product_mapeds->product_id)->first();





            DB::connection('mysql')->table('assigned_agent_product_map')->insert([

                'agent_assinged_id' =>$assinedId,

                'product_id'=>  $product_mapeds->product_id,

                'qty' =>$product_mapeds->qty,

                'price' => $agent_product_list->price,

                'created_at'=>date('Y-m-d H:i:s'),

                'updated_at'=>date('Y-m-d H:i:s'),

            ]);

        }

        return 'done';
        
    }

    public function mailStatus(Request $request){

        $mail_status = $request['mail_status'];

        $OrderID = $request['OrderID'];



        DB::connection('mysql')->table('orders')->where('id',$OrderID)->update([

            'order_delivery_status'=>  $mail_status = $request['mail_status'],

        ]);

        if($request['OrderIdArray'] && $request['track_no'] || $request['tracking_link']){
            return $request->all();
        }
        return "done";

    }

    // public function assignOrderList(){

    //     $agent_assigned = DB::connection('mysql')

    //     ->table('agent_assinged')

    //     ->get();



    //     $products = [];

    //     $agent_product_list=[];

    //     $assined = DB::connection('mysql')

    //     ->table('agent_assinged')

    //     ->get();

    //     $product_maped = DB::connection('mysql')->table('assigned_agent_product_map')->get();



    //     foreach($product_maped as $product_mapeds){

    //         $products[] = DB::connection('mysql')->table('products')->where('id',$product_mapeds->product_id)->first();

    //         $agent_product_list[] = DB::connection('mysql')->table('agent_product_list')->where('id',$product_mapeds->product_id)->first();



    //     }

    //     $agents = DB::connection('mysql')->table('agents')->get();

    //     $order_details = DB::connection('mysql')->table('order_details')->get();

    //     $orders = DB::connection('mysql')->table('orders')->get();

    //     return view('admin.order.assign_order_list', compact('agent_assigned','products','order_details','orders','agents','assined','product_maped','agent_product_list'));
             
    // }

    public function assignOrderList(Request $request){

        $where = $orWhere = [];

        if($request->agents != null){
            $where[] = ['agent_id', '=', $request->agents];
        }

        if($request->delstatus != null){
            $where[] = ['status', '=', $request->delstatus];
        }



        //search confitions
        if($request->search != null){
            if (str_contains($request->search, '@')) { 
                $userDtl = Admin::where(['email'=> $request->search])->first();
                if($userDtl){
                    $orWhere[] = ['placed_userid', '=', $userDtl->id];
                }
            }

            $orWhere[] = ['agent_order_id', 'LIKE', '%'.$request->search.'%'];
            //$orWhere[] = ['delivery_user_name', 'LIKE', '%'.$request->search.'%'];
            //$orWhere[] = ['billing_user_name', 'LIKE', '%'.$request->search.'%'];
        }

        $result = DB::connection('mysql')->table('agent_assinged')->where($where)
                        ->where(function($query) use ($orWhere, $request){
                            // creating "OR" queries for search
                            foreach($orWhere as $key => $where){
                                if($key == 0){
                                    $query->where([$where]);
                                }else{
                                    $query->orWhere([$where]);
                                }
                            }

                            if ($request->date_type != null && $request->date_type == 'd_date') {
                                if ($request->fromDate && $request->toDate) {
                                    $query->orWhereBetween('delivery_date', [$request->fromDate, $request->toDate]);
                                }
                            }elseif ($request->date_type != null && $request->date_type == 'a_date') {
                                if ($request->fromDate && $request->toDate) {
                                    $query->orWhereBetween('created_at', [$request->fromDate, $request->toDate]);
                                }
                            }else{
                                if ($request->fromDate && $request->toDate) {
                                    $query->orWhereBetween('delivery_date', [$request->fromDate, $request->toDate]);
                                }
                            }


                        })
                        ->when($request->sort && $request->direction, function($query) use ($request){
                            $query->orderBy($request->sort, $request->direction);
                        }, function($query){
                            $query->orderBy('created_at', 'desc');
                        })
                        ->paginate(30);

        
        $agents = DB::connection('mysql')->table('agents')->get();     

        return view('admin.order.assign_order_list', compact('result', 'agents', 'request'));           
             
    }

    public function search(Request $request){


        // $order = DB::connection('mysql')->table('orders')

        // ->where('payment_status', 'C')

        // ->where('type', 'order')

        // ->whereBetween('created_at', [$request['fromDate'], $request['toDate']])

        // ->where('order_delivery_status', $request['status'])

        // ->get();

        // $order_details = DB::connection('mysql')->table('order_details')->get();

        // $products = DB::connection('mysql')->table('products')->get();

        // return view('admin.search',compact('order','order_details','products'));
        $search_type = $request['search_type'];
        $status = $request['status']; // no need for ternary

        if ($search_type == 'd_date') {
            $query = DB::connection('mysql')
                ->table('agent_assinged')
                ->whereBetween('delivery_date', [$request['fromDate'], $request['toDate']]);
        } else {
            $query = DB::connection('mysql')
                ->table('agent_assinged')
                ->whereBetween('created_at', [$request['fromDate'], $request['toDate']]);
        }

        // Only filter by status if not 'A'
        if ($status != 'A') {
            $query->where('status', $status);
        }

        $agent_assigned = $query->get();
        // $agent_assigned = DB::connection('mysql')

        //                   ->table('agent_assinged')

        //                   ->whereBetween('created_at', [$request['fromDate'], $request['toDate']])

        //                   ->where('status', $request['status'])

        //                   ->get();



        $products = [];

        $agent_product_list=[];

        $assined = DB::connection('mysql')

                   ->table('agent_assinged')

                   ->whereBetween('created_at', [$request['fromDate'], $request['toDate']])

                   ->where('status', $request['status'])

                   ->get();



        $product_maped = DB::connection('mysql')->table('assigned_agent_product_map')->get();



        foreach($product_maped as $product_mapeds){

            $products[] = DB::connection('mysql')->table('products')->where('id',$product_mapeds->product_id)->first();

            $agent_product_list[] = DB::connection('mysql')->table('agent_product_list')->where('id',$product_mapeds->product_id)->first();



        }

        $agents = DB::connection('mysql')->table('agents')->get();

        $order_details = DB::connection('mysql')->table('order_details')->get();

        $orders = DB::connection('mysql')->table('orders')->get();

        return view('admin.order.assign_order_list', compact('agent_assigned','products','order_details','orders','agents','assined','product_maped','agent_product_list'));

    }

    public function assignOrderView($id,$agentId){

        require_once app_path('Http/Helper.php');
        $userResponse = AssignOrderView($id,$agentId);
        return $userResponse;
    }

    public function updateAssignOrderStatus($orderId,$agentID,Request $request){

        // $request = Request $request;

        require_once app_path('Http/Helper.php');

        $userResponse = UpdateAssignOrderStatus($orderId,$agentID,$request);

        return $userResponse;
    }

    public function OrderInvoice($Orderid, $AgentAssignedId){

        $id = decrypt($Orderid);
        $agentId = decrypt($AgentAssignedId);

        $user = Auth::guard('AgentLogin')->user();

        $agent_assinged = DB::connection('mysql')->table('agent_assinged')->where('agent_order_id',$id)->where('agent_id',$agentId)->first();

        $agents = DB::connection('mysql')->table('agents')->where('id',$agentId)->first();

        $product = [];

        //$agent_product_list=[];

        $product_maped = DB::connection('mysql')->table('assigned_agent_product_map')->where('agent_assinged_id',$agent_assinged->id)->get();

        $orders = DB::connection('mysql')->table('orders')->where('id',$agent_assinged->OID)->first();

        $order_details = DB::connection('mysql')->table('order_details')->where('order_id',$orders->id)->get();

        $orders_Msg = DB::connection('mysql')->table('order_messages')->where('order_id',$agent_assinged->OID)->first();

        $agent_product_list = DB::connection('mysql')->table('assigned_agent_product_map')
                ->join('agent_product_list', 'assigned_agent_product_map.product_id', '=', 'agent_product_list.id')
                ->where('agent_assinged_id',$agent_assinged->id)->get();

        //dd($agent_product_list);


            // foreach($product_maped as $product_mapeds){

            //     if($agent_assinged->id == $product_mapeds->agent_assinged_id){

            //         // $products[] = DB::connection('mysql')->table('products')->where('id',$product_mapeds->product_id)->first();

            //          $agent_product_list[] =  DB::connection('mysql')->table('agent_product_list')->where('id',$product_mapeds->product_id)->first();



            //     }

            // }

            $data=compact('agent_assinged','product_maped','orders','order_details','orders_Msg','user','agent_product_list','agents','agentId');



            $agent_assinged=$data['agent_assinged'];

            $product_maped=$data['product_maped'];

            $orders=$data['orders'];

            $order_details=$data['order_details'];

            $orders_Msg=$data['orders_Msg'];

            $user=$data['user'];

            $agent_product_list=$data['agent_product_list'];

            $agents=$data['agents'];

            $agentId=$data['agentId'];

        // return $Orderid;
        return view('admin.order.invoice',compact('agent_assinged','product_maped','orders','order_details','orders_Msg','user','agent_product_list','agents','agentId','id'));
    }

    public function report(Request $request){

        $agents = DB::connection('mysql')->table('agents')->get();
        $data = "";

        return view('admin.order.report', compact('agents', 'data'));

    }

    public function reportTable(Request $request){ 


        $agent_product_list = [];

        $assigned_agent_product_map = [];

        $agent_product_list = [];



        $agentId = $request['agent'];

        $startDate = $request['start-date'];

        $endDate = $request['end-date'];



        $agent_assinged = DB::connection('mysql')

            ->table('agent_assinged')

            ->where('agent_id', $agentId)

            ->whereBetween('created_at', [$startDate, $endDate])

            ->get();



        // echo "<pre>";

        // print_r($agent_assinged);

        // die;    

        // dd($agent_assinged);

            

        $agents = DB::connection('mysql')->table('agents')->where('id', $agentId)->first();

        // $agent_product_list[] =  DB::connection('mysql')->table('agent_product_list')->where('agent_id', $agentId)->get();

        // dd($agent_product_list);

        // foreach ($agent_assinged as $agent_assingeds) {

        //     $assigned_agent_product_map[] = DB::connection('mysql')->table('assigned_agent_product_map')->where('agent_assinged_id', $agent_assingeds->id)->get();

        // }

        // dd($assigned_agent_product_map);

        $assigned_agent_product_map = DB::connection('mysql')->table('assigned_agent_product_map')->get();



        foreach($assigned_agent_product_map as $product_mapeds) {

            $agent_product_list[] = DB::connection('mysql')->table('agent_product_list')

                                    ->where('id', $product_mapeds->product_id)

                                    ->first();

        }

        // dd($agent_product_list);



        // $data = compact('agent_assinged','agents','agent_product_list','assigned_agent_product_map');

        return view('admin.order.reportSearch', compact('agent_assinged', 'agents', 'agent_product_list', 'assigned_agent_product_map'));

    }

    public function ProfitReport(){

        return view('admin.order.ProfitReport');

    }

    public function ProfitReportSearch(Request $request){


        // return $request->all();

        // $user = Auth::guard('AdminLogin')->user();

        // return $user->name;



        $order = [];

        $orderDetails = [];

        $AgentAssign = [];

        $Agent = [];

        $tableItem = [];

        $agent_name = [];

        $totalPrice = 0;

        $placementPrice = 0;



        $profitType = $request['profitType'];

        $start_date = $request['start-date'];

        $end_date = $request['end-date'];



        $agentAssigned = DB::connection('mysql')->table('agent_assinged')

                        ->where('status','D')

                        ->whereBetween('created_at', [$start_date, $end_date])

                        ->get();

        // echo "<pre>";

        // print_r($agentAssigned);

        // die;                



        $uniques = array();

            foreach ($agentAssigned as $agentAssigneds) {

                $uniques[$agentAssigneds->OID] = $agentAssigneds->OID; 

            }



        // echo "<pre>";

        // print_r($uniques);

        // die;     

            // dd($uniques);

        foreach($uniques as $unique){

            $order[] = DB::connection('mysql')->table('orders')->where('id',$unique)->first();

            $AgentAssign[] = DB::connection('mysql')

                            ->table('agent_assinged')

                            ->where('OID',$unique)

                            ->where('status', 'D')

                            ->get();



        }

        foreach($order as $order_details){

            $orderDetails[] = DB::connection('mysql')->table('order_details')->where('order_id',$order_details->id)->get();

        }

        foreach($AgentAssign as $AgentAssigns){

            foreach($AgentAssigns as $details){

                $Agent[] = DB::connection('mysql')->table('agents')->where('id',$details->agent_id)->get();

            }

        }  

        $tableItem = [];



        foreach ($order as $orders) {

            $delivery_date = null;

            $delivery_city_name = null;

            $totalPrice = 0;

            $placementPrice = 0;

            $agent_name = [];

        

            foreach ($orderDetails as $orderDetail) {

                foreach ($orderDetail as $orderDet) {

                    if ($orders->id == $orderDet->order_id) {

                        $delivery_date = $orderDet->delivery_date;

                        $delivery_city_name = $orderDet->delivery_city_name;

                        $totalPrice += $orderDet->total_price;

                    }

                }

            }

        

            foreach ($AgentAssign as $AgentAssigns) {

                foreach ($AgentAssigns as $key => $details) {

                    if ($details->OID == $orders->id) {

                        $placementPrice += $details->totalPrice;

            

                        foreach ($Agent as $Agents) {

                            foreach ($Agents as $agented) {

                                if ($details->agent_id == $agented->id) {

                                    $agent_name[] = $agented->name;

                                }

                            }

                        }

                    }

                }

                

            }

            // foreach ($agent_name as $agent_names) {

            //     $agent_name[$agent_names->name] = $agent_names->name; 

            // }

            $agent_name=array_unique($agent_name);

        

            $profit = ($totalPrice > 0) ? ($placementPrice / $totalPrice) * 100 : 0;



            if (($profitType == '20' && $profit >= 20 && $profit <= 30) ||

                ($profitType == '31' && $profit >= 31 && $profit <= 40) ||

                ($profitType == '41' && $profit >= 41 && $profit <= 50) ||

                ($profitType == '51' && $profit >= 51 && $profit <= 60) ||

                ($profitType == '60' && $profit >= 60) ||

                ($profitType == "ALL" && $profit > 0) ||

                !$profitType

            ) {

            

                $tableItem[] = [

                    'uniqueId' => $orders->unique_order_id,

                    'delivery_date' => $delivery_date,

                    'delivery_city_name' => $delivery_city_name,

                    'totalOrderPrice' => $totalPrice,

                    'placementTotal' => $placementPrice,

                    'profit' => $profit,

                    'agent_name' => $agent_name,

                    'status' => "DELIVERED",

                ];

            }

        }

        

        // return $tableItem;

        // echo "<pre>";

        // print_r($tableItem);

        // die;

         return view('admin.order.ProfitReportSearch',compact('tableItem','start_date','end_date'));

    }

    public function downloadPersonalizedImages($zid, $oid, $pid)
    {
        $images = DB::table('personalized_image_details')
                        ->where(['order_detail_id' => $oid, 'product_id' => $pid])->get();

        if ($images->isEmpty()) {
            abort(404, 'No images found');
        }

        // Define a temporary zip file path
        $zipFileName = $zid . '.zip';
        $zipFilePath = storage_path('app/public/' . $zipFileName);

        $zip = new ZipArchive;
        if ($zip->open($zipFilePath, ZipArchive::CREATE | ZipArchive::OVERWRITE) === TRUE) {
            foreach ($images as $img) {
                $filePath = public_path('uploaded/personalized_image/' . $img->image);
                if (file_exists($filePath)) {
                    $zip->addFile($filePath, basename($filePath));
                }
            }
            $zip->close();
        } else {
            abort(500, 'Could not create ZIP file.');
        }

        // Return response as download
        return response()->download($zipFilePath)->deleteFileAfterSend(true);
    }

    public function updateDeliveryAddress(Request $request){
        //dd($request);
        if($request->odr_id){
            if($request->del_add_access_code != 'rspl'){
                return json_encode(['type' => 'json', 'status' => 'failed', 'msg' => 'Access code not matched..']);
            }else{
                Order::where('id',base64_decode($request->odr_id))
                    ->update(['delivery_user_name'=> $request->rec_name, 'delivery_address' => $request->rec_address, 'delivery_state' => $request->rec_state, 'delivery_city' => $request->rec_city, 'delivery_pincode' => $request->rec_zipcode, 'delivery_mobile' => $request->rec_phone]);
                return json_encode(['type' => 'json', 'status' => 'success', 'msg' => 'Update Successful..']);
            }
        }else{
            return json_encode(['type' => 'json', 'status' => 'error']);
        }
    }
    
    public function updateMessages(Request $request){
        if($request->odr_id){
            if($request->message_access_code != 'rspl'){
                return json_encode(['type' => 'json', 'status' => 'failed', 'msg' => 'Access code not matched..']);
            }else{
                OrderMessage::where('order_id',base64_decode($request->odr_id))
                    ->update(['sender_name' => $request->sender_name, 'sender_message' => $request->sender_msg, 'sender_special_instruction' => $request->spl_inst]);
                    //->update(['occasion_type'=> $request->occ_type, 'sender_name' => $request->sender_name, 'sender_message' => $request->sender_msg, 'sender_special_instruction' => $request->spl_inst]);
                return json_encode(['type' => 'json', 'status' => 'success', 'msg' => 'Update Successful..']);
            }
        }else{
            return json_encode(['type' => 'json', 'status' => 'error']);
        }
    }
}