<?php

namespace App\Http\Controllers;
use App\Models\Order;
use App\Models\Address;
use App\Models\Customer;
use App\Models\Cart;
use App\Models\Shipping_Address;
use Illuminate\Support\Facades\Log;
use Illuminate\Http\Request;

class OrderController extends Controller
{
    ## STORE ORDERS
    public function storeorder(Request $request){
        log::info($request);
        $validate   =   $request->validate([
            'customer_id'                => 'required',
            'cart_id'                    => 'required', 
            'shipping_charge'            => 'required|numeric',
            'address_type'               => 'required',

        ]);
            $customer_id                                    = $request->customer_number;
            log::info($customer_id);

            $customer_number                                = $request->customer_number;
            $old_customer_data                              = Customer::where('customer_number', $customer_number)->latest()->first();
            log::info($old_customer_data);

            //  Unwanted Customer Id Remove and orders address update function
            if($old_customer_data){
                $old_customer_id                                = $old_customer_data->customer_id;

                if($customer_id != $old_customer_id){
                $carddata                                   = Cart::where('customer_id',$customer_id)->get();

                foreach($carddata as $item) {
                    $item->customer_id = $old_customer_id;
                }
                $carddata->each->save();

                // Customer::where('customer_id', $customer_id)->delete();

                }else{
                    return response()->json(['status'=> false, 'data'=> 'unwanted customer id deleted failed'],200);
                }     
            

            if ($request->address_type === 'same_as'){
            $shippingdata                                 = new Shipping_Address();
            $shippingdata->customer_id                    = $old_customer_id;
            $shippingdata->email                          = $request->email;
            $shippingdata->country                        = $request->country;
            $shippingdata->first_name                     = $request->first_name;
            $shippingdata->last_name                      = $request->last_name;
            $shippingdata->adresses                       = $request->adresses;
            $shippingdata->apartment                      = $request->apartment;
            $shippingdata->city                           = $request->city;
            $shippingdata->state                          = $request->state;
            $shippingdata->pincode                        = $request->pincode;
            $shippingdata->phone_number                   = $request->phone_number ;
            $shippingdata->customer_number                = $request->customer_number ;
            $shippingstore                                = $shippingdata->save();

            if($shippingstore == true){
                $billingdata                                 = new Address();
                $billingdata->customer_id                    = $old_customer_id;
                $billingdata->email                          = $request->email;
                $billingdata->country                        = $request->country;
                $billingdata->first_name                     = $request->first_name;
                $billingdata->last_name                      = $request->last_name;
                $billingdata->adresses                       = $request->adresses;
                $billingdata->apartment                      = $request->apartment;
                $billingdata->city                           = $request->city;
                $billingdata->state                          = $request->state;
                $billingdata->pincode                        = $request->pincode;
                $billingdata->phone_number                   = $request->phone_number ;
                $billingdata->customer_number                = $request->customer_number ;
                $billingstore                                = $billingdata->save();
            }
            else{
                return response()->json(['status' => false,'data' => 'Same as Shipping addresss stored failed'],200);
            }
    
        }elseif($request->address_type === 'use_diffeerent_billing'){
                $shippingdata                                 = new Shipping_Address();
                $shippingdata->customer_id                    = $old_customer_id;
                $shippingdata->email                          = $request->email;
                $shippingdata->country                        = $request->country;
                $shippingdata->first_name                     = $request->first_name;
                $shippingdata->last_name                      = $request->last_name;
                $shippingdata->adresses                       = $request->adresses;
                $shippingdata->apartment                      = $request->apartment;
                $shippingdata->city                           = $request->city;
                $shippingdata->state                          = $request->state;
                $shippingdata->pincode                        = $request->pincode;
                $shippingdata->phone_number                   = $request->phone_number ;
                $shippingdata->customer_number                = $request->customer_number ;
                $shippingstore                                = $shippingdata->save();
                if($shippingstore == true){
                    $billingdata                                 = new Address();
                    $billingdata->customer_id                    = $old_customer_id;
                    $billingdata->email                          = $request->email;
                    $billingdata->country                        = $request->billing_country;
                    $billingdata->first_name                     = $request->billing_first_name;
                    $billingdata->last_name                      = $request->billing_last_name;
                    $billingdata->adresses                       = $request->billing_adresses;
                    $billingdata->apartment                      = $request->billing_apartment;
                    $billingdata->city                           = $request->billing_city;
                    $billingdata->state                          = $request->billing_state;
                    $billingdata->pincode                        = $request->billing_pincode;
                    $billingdata->phone_number                   = $request->billing_phone_number;
                    $billingdata->customer_number                = $request->customer_number;
                    $billingstore                                = $billingdata->save();
                }else{
                    return response()->json(['status' => false,'data' => ' failed'],200);

                }
                
        }
        // Customerdata update
        if($old_customer_id){
            $id                             = $old_customer_id;
            $customer                       = Customer::find($id);
            $customer->customer_number      = $request->customer_number;
            $updated                        = $customer->save();
        }else{
            return response()->json(['status' => false,'message'=>'customer id  not exist '],400);
        }


        $storedata                                         = new Order();
        $storedata->customer_id                            = $old_customer_id;
        $storedata->product_id                             = $request->product_id;
        // billing id
        $storedata->address_id                             = $billingdata->address_id;
        $storedata->shipping_address_id                    = $shippingdata->shipping_address_id;
        $storedata->address_type                           = $request->address_type;
        $storedata->cart_id                                = $request->cart_id;
        $storedata->shipping_charge                        = $request->shipping_charge;
        $storedata->subtotal                               = $request->subtotal;
        $storedata->over_all_total                         = $request->over_all_total;
        $storedata->delivery_mode                          = $request->delivery_mode;
        $storedata->order_status                           = $request->order_status;
        $storedata->submitted_at                           = now(); 
        $storedata->promocode_id                           = $request->promocode_id;
        $storedata->promocode                              = $request->promocode;
        $storedata->promocode_value                        = $request->promocode_value;
        $store                                             = $storedata->save();

        if ($store == true){
            return response()->json(['status' => true,'data' => $storedata, 'shippingaddress' => $shippingdata,'billingaddress' => $billingdata,],200);
        }else{
            return response()->json(['status' => false,'data' => 'failed Store'],200);
        }
    }
        
    //  Not Unwanted Customer Id remove Functionlity and store orders and address else function 

        else {

        if ($request->address_type === 'same_as'){
            $shippingdata                                 = new Shipping_Address();
            $shippingdata->customer_id                    = $request->customer_id;
            $shippingdata->email                          = $request->email;
            $shippingdata->country                        = $request->country;
            $shippingdata->first_name                     = $request->first_name;
            $shippingdata->last_name                      = $request->last_name;
            $shippingdata->adresses                       = $request->adresses;
            $shippingdata->apartment                      = $request->apartment;
            $shippingdata->city                           = $request->city;
            $shippingdata->state                          = $request->state;
            $shippingdata->pincode                        = $request->pincode;
            $shippingdata->phone_number                   = $request->phone_number ;
            $shippingdata->customer_number                = $request->customer_number ;
            $shippingstore                                = $shippingdata->save();

            if($shippingstore == true){
                $billingdata                                 = new Address();
                $billingdata->customer_id                    = $request->customer_id;
                $billingdata->email                          = $request->email;
                $billingdata->country                        = $request->country;
                $billingdata->first_name                     = $request->first_name;
                $billingdata->last_name                      = $request->last_name;
                $billingdata->adresses                       = $request->adresses;
                $billingdata->apartment                      = $request->apartment;
                $billingdata->city                           = $request->city;
                $billingdata->state                          = $request->state;
                $billingdata->pincode                        = $request->pincode;
                $billingdata->phone_number                   = $request->phone_number ;
                $billingdata->customer_number                = $request->customer_number ;
                $billingstore                                = $billingdata->save();
            }
            else{
                return response()->json(['status' => false,'data' => 'Same as Shipping addresss stored failed'],200);
            }
    
        }elseif($request->address_type === 'use_diffeerent_billing'){
                $shippingdata                                 = new Shipping_Address();
                $shippingdata->customer_id                    = $request->customer_id;
                $shippingdata->email                          = $request->email;
                $shippingdata->country                        = $request->country;
                $shippingdata->first_name                     = $request->first_name;
                $shippingdata->last_name                      = $request->last_name;
                $shippingdata->adresses                       = $request->adresses;
                $shippingdata->apartment                      = $request->apartment;
                $shippingdata->city                           = $request->city;
                $shippingdata->state                          = $request->state;
                $shippingdata->pincode                        = $request->pincode;
                $shippingdata->phone_number                   = $request->phone_number ;
                $shippingdata->customer_number                = $request->customer_number ;
                $shippingstore                                = $shippingdata->save();
                if($shippingstore == true){
                    $billingdata                                 = new Address();
                    $billingdata->customer_id                    = $request->customer_id;
                    $billingdata->email                          = $request->email;
                    $billingdata->country                        = $request->billing_country;
                    $billingdata->first_name                     = $request->billing_first_name;
                    $billingdata->last_name                      = $request->billing_last_name;
                    $billingdata->adresses                       = $request->billing_adresses;
                    $billingdata->apartment                      = $request->billing_apartment;
                    $billingdata->city                           = $request->billing_city;
                    $billingdata->state                          = $request->billing_state;
                    $billingdata->pincode                        = $request->billing_pincode;
                    $billingdata->phone_number                   = $request->billing_phone_number;
                    $billingdata->customer_number                = $request->customer_number;
                    $billingstore                                = $billingdata->save();
                }else{
                    return response()->json(['status' => false,'data' => ' failed'],200);

                }
                
        }
        // Customerdata update
        if($request->customer_id){
            $id                             = $request->customer_id;
            $customer                       = Customer::find($id);
            $customer->customer_number      = $request->customer_number;
            $updated                        = $customer->save();
        }else{
            return response()->json(['status' => false,'message'=>'customer id  not exist '],400);
        }


        $storedata                                         = new Order();
        $storedata->customer_id                            = $request->customer_id;
        $storedata->product_id                             = $request->product_id;
        // billing id
        $storedata->address_id                             = $billingdata->address_id;
        $storedata->shipping_address_id                    = $shippingdata->shipping_address_id;
        $storedata->address_type                           = $request->address_type;
        $storedata->cart_id                                = $request->cart_id;
        $storedata->shipping_charge                        = $request->shipping_charge;
        $storedata->subtotal                               = $request->subtotal;
        $storedata->over_all_total                         = $request->over_all_total;
        $storedata->delivery_mode                          = $request->delivery_mode;
        $storedata->order_status                           = $request->order_status;
        $storedata->submitted_at                           = now(); 
        $storedata->promocode_id                           = $request->promocode_id;
        $storedata->promocode                              = $request->promocode;
        $storedata->promocode_value                        = $request->promocode_value;
        $store                                             = $storedata->save();
    // Cart delete value add like active status method
        $this->updateCartDelete($request);

        if ($store == true){
            return response()->json(['status' => true,'data' => $storedata, 'shippingaddress' => $shippingdata,'billingaddress' => $billingdata,],200);
        }else{
            return response()->json(['status' => false,'data' => 'failed Store'],200);
        }
    }
    }
// Cart delete value add like active status method
    public function updateCartDelete(Request $request)
    {
        log::info("delete function called");
        $validate   =   $request->validate([
                 'cart_id' => ['required'],
        ]);

        if ($validate === true) {
            // Update cart_delete to 1 for the specified cart_ids
           $hlo = Cart::whereIn('cart_id', $request->cart_id)->update(['cart_delete' => 1]);

           return response()->json(['status' => true,'data' => $hlo,],200);
        }else{
            return response()->json(['status' => false,'data' => 'failed cart update'],200);
        }

    }

    // Update Order admin status
    public function updateOrderAdmin(Request $request) {
        // $validate = $this->response->validate($request->all(), [
        //     'order_status' => ['required'],
        //     'order_id' => ['required'],
        // ]);
        log::info($request);
        $validate   =   $request->validate([
            'order_status' => ['required'],
            'order_id' => ['required'],
        ]);

        if ($validate) {
            $ordersModel = $this->findOrders($request->order_id);
            $ordersModel                                = Order::find($request->order_id);
            if ($request->order_status === 'Confirmed') {
                $ordersModel                                = Order::find($request->order_id);
                $ordersModel->order_status                  = $request->order_status;
                $ordersModel->order_confirmed_at            = now();
                $updated = $ordersModel->save();
            }else if ($request->order_status === 'OnHold') {
                $ordersModel                                = Order::find($request->order_id);
                $ordersModel->order_status                  = $request->order_status;
                $ordersModel->on_hold_at                    = now();
                $updated = $ordersModel->save();
            }else if ($request->order_status === 'Processing') {
                $ordersModel                                = Order::find($request->order_id);
                $ordersModel->order_status                  = $request->order_status;
                $ordersModel->order_processed_at            = now();
                $updated = $ordersModel->save();
            }else if ($request->order_status === 'Shipped') {
                $ordersModel                                = Order::find($request->order_id);
                $ordersModel->order_status                  = $request->order_status;
                $ordersModel->tracking_number               = $request->tracking_number;
                $ordersModel->tracking_link                 = $request->tracking_link;
                $ordersModel->order_shipped_at              = now();
                $updated = $ordersModel->save();

            }else if ($request->order_status === 'Delivered') {
                $ordersModel                                = Order::find($request->order_id);
                $invoiceNumber = $this->generateInvoiceNumber();
                $ordersModel->order_status                  = $request->order_status;
                $ordersModel->order_delivered_at            = now();
                $ordersModel->invoice_number            = $invoiceNumber;
                $updated = $ordersModel->save();
            }else if ($request->order_status === 'Canceled') {
                $ordersModel                                = Order::find($request->order_id);
                $ordersModel->order_status                  = $request->order_status;
                $ordersModel->order_canceled_at             = now();
                $updated = $ordersModel->save();
            }else {
                return response()->json(['status' => false,'data' => 'Failed Order update'],200);
            }
            $ordersModel->update($request->all());

            return response()->json(['status' => true,'data' => $ordersModel,],200);
        }else{
            return response()->json(['status' => false,'data' => 'Failed Order update'],200);
        }
    }
        //  data find function
    public function findOrders($id) {
        return Order::find($id);
    }
        //
    private function generateInvoiceNumber() {
        // Find the latest invoice number
        $latestInvoice = Order::whereNotNull('invoice_number')
            ->orderBy('invoice_number', 'desc')
            ->first();

        // Increment the latest invoice number or start from 1 if none exists
        $nextInvoiceNumber = $latestInvoice ? ++$latestInvoice->invoice_number : 1;
        // Format the invoice number (e.g., 001)
        return str_pad($nextInvoiceNumber, 3, '0', STR_PAD_LEFT);
    } 
    ## GET ORDERS
    public function getorder(){
        $ordersgetdata = Order::with('cartdetails')
                              ->get();
        if ($ordersgetdata->isNotEmpty()){
            return response()->json(['status' => true,'message' => 'Orders Data','data'=> $ordersgetdata ],200);
        }else if($ordersgetdata->isEmpty()){
            return response()->json(['status' => true,'message' => 'Orders Data Is Empty' ],200);
        }else{
            return response()->json(['status' => false,'data' => 'failed data'],200);
        }
    }

    ## UPDATE ORDERS
    public function updateorders(Request $request){
        $validate   =   $request->validate([
            'customer_id'                => 'required',
            'cart_id'                    => 'required', 
            'shipping_charge'            => 'required|numeric',
        ]);
        $updatedata                                 = Order::find($request->id);
        $updatedata->customer_id                    = $request->customer_id;
        $updatedata->cart_id                        = $request->cart_id;
        $updatedata->subtotal_price                 = $request->subtotal_price;
        $updatedata->shipping_charge                = $request->shipping_charge;
        $updatedata->total_price                    = $request->total_price;
        $updatedata->discount_code                  = $request->discount_code;
        $updatedata->delivery_country               = $request->delivery_country;
        $updatedata->delivery_first_name            = $request->delivery_first_name;
        $updatedata->delivery_last_name             = $request->delivery_last_name;
        $updatedata->delivery_address               = $request->delivery_address;
        $updatedata->delivery_city                  = $request->delivery_city ;
        $updatedata->delivery_pincode               = $request->delivery_pincode;
        $updatedata->delivery_state                 = $request->delivery_state;
        $updatedata->delivery_phonenumber           = $request->delivery_phonenumber;
        $updatedata->billing_country                = $request->billing_country;
        $updatedata->billing_first_name             = $request->billing_first_name;
        $updatedata->billing_last_name              = $request->billing_last_name;
        $updatedata->billing_address                = $request->billing_address;
        $updatedata->billing_apartment              = $request->billing_apartment;
        $updatedata->billing_city                   = $request->billing_city;
        $updatedata->billing_state                  = $request->billing_state;
        $updatedata->billing_pincode                = $request->billing_pincode;
        $updatedata->billing_phonenumber            = $request->billing_phonenumber;
        $updatedata->payment_id                     = $request->payment_id;
        $updatedata->order_status                   = $request->order_status;
        $updatedata->delivery_mode                  = $request->delivery_mode;
        $updatedata->tax                            = $request->tax;
        $update                                     = $updatedata->save();
        if (!$updatedata){
            return response()->json(['status' => false,'message'=>'update data not found'],404);
        }else if ($update == true) {
            return response()->json(['status' => true,'message'=>'update Success'],200);
        }else{
            return response()->json(['status' => false,'message'=>'failed update'],400);
        }
    }


    // all data get function
    public function listOfAllCurrentOrders() {
        $data        =  Order::where('order_status', '!=', 'Canceled')->where('order_status', '!=', 'Delivered')->latest()->get();
        if ($data->isNotEmpty()){
            return response()->json(['status' => true, 'data' => $data], 200);
        } else {
            return response()->json(['status' => false,'data' => 'failed data get'], 400);
        }  
      }
      public function getOrdersCount(){
        $data = [];
        $data['canceled']             = Order::where('order_status', '==', 'Canceled')->count();
        $data['confirmed']            = Order::where('order_status', '==', 'Confirmed')->count();
        $data['all']                  = Order::all()->count();

        if ($data == true){
            return response()->json(['status' => true, 'data' => $data], 200);
        } else {
            return response()->json(['status' => false,'data' => 'failed data'], 400);
        }
    }

    //  Delivered Orderes Data get 
      public function listOfAllDeliveredOrders() {
        $data        =  Order::where('order_status', 'Delivered')->latest()->get();
        if ($data->isNotEmpty()){
            return response()->json(['status' => true, 'data' => $data], 200);
        } else {
            return response()->json(['status' => false,'data' => 'failed data get'], 400);
        }  
    }
    // Cancel Orders Data get
    public function listOfAllCancelOrders() {
        $data        =  Order::where('order_status', 'Canceled')->latest()->get();
        if ($data->isNotEmpty()){
            return response()->json(['status' => true, 'data' => $data], 200);
        } else {
            return response()->json(['status' => false,'data' => 'failed data get'], 400);
        }  
    }
    // Particular Customer order
    public function customerAllOrders($id) {
        $data        =  Order::where('customer_id', $id)->latest()->get();
        if ($data->isNotEmpty()){
            return response()->json(['status' => true, 'data' => $data], 200);
        } else {
            return response()->json(['status' => false,'data' => 'failed data get'], 400);
        }  
    }

    //   $orderDetails = Order::where('order_id', $order_id)->with('billingaddressdetails','shippingaddressdetails','productdetails')->orderBy('order_id', 'desc')->latest()->first();

    public function getorderDetailsById($order_id)
    {
        // Retrieve the order details by order_id
        $orderDetails = Order::where('order_id', $order_id)->with('billingaddressdetails','shippingaddressdetails','productdetails')->orderBy('order_id', 'desc')->latest()->first();
        log::info($orderDetails);
    
        // Check if orderDetails is not null before proceeding
        if ($orderDetails) {
            // Convert the cart_id string into an array
            $cartIds = array_map('trim', explode(',', $orderDetails->cart_id));
            log::info($cartIds);
    
            // Retrieve the cart details based on cart_ids
            $cartDetails = Cart::whereIn('cart_id', $cartIds)->with('productdetails','othercustomizationdetails')->get();
            log::info($cartDetails);
    
            // Append cart details to order details
            $orderDetails->cart_details = $cartDetails;
    
            // Return the response with order details and cart details
            return response()->json(['status' => true, 'data' => $orderDetails], 200);
        } else {
            // Return an error response if order details are not found
            return response()->json(['status' => false, 'data' => 'failed data get'], 400);
        }
    }
    




// 
}
